blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
52fc88313f21880cf038e0cb5f33070517e25e4d
97e53e8028ffb9d3f736a0999cc470f9942ddcd0
/02 控件应用/06 列表视图控件典型实例/006 具有文本录入功能的列表视图控件-例1/TextInList/TextInList.cpp
f8e49e72d31fb104cf065e271cc06118b0af6642
[]
no_license
BambooMa/VC_openSource
3da1612ca8285eaba9b136fdc2c2034c7b92f300
8c519e73ef90cdb2bad3de7ba75ec74115aab745
refs/heads/master
2021-05-14T15:22:10.563149
2017-09-11T07:59:18
2017-09-11T07:59:18
115,991,286
1
0
null
2018-01-02T08:12:01
2018-01-02T08:12:00
null
UTF-8
C++
false
false
2,087
cpp
// TextInList.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "TextInList.h" #include "TextInListDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTextInListApp BEGIN_MESSAGE_MAP(CTextInListApp, CWinApp) //{{AFX_MSG_MAP(CTextInListApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTextInListApp construction CTextInListApp::CTextInListApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CTextInListApp object CTextInListApp theApp; ///////////////////////////////////////////////////////////////////////////// // CTextInListApp initialization BOOL CTextInListApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. ::CoInitialize(NULL); #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CTextInListDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } ::CoUninitialize(); // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "xiaohuh421@qq.com" ]
xiaohuh421@qq.com
a27e893e1c27c357f3db64f0095a78a5acc12f8f
b1c4af0509ef0698d0fa7c2ce52eff72f49b88be
/src/testApp.h
be8496d688b67ac254ea754fb676cc2e0e0d19ed
[]
no_license
arlduc/KinectOcean
b917b5e93bf4d88823e9bbab48a526e8e5e3a035
5b8de85e752d67926ba022155527aa32f0d003a5
refs/heads/master
2021-01-01T18:27:56.483709
2012-06-18T22:52:57
2012-06-18T22:52:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
#pragma once #include "ofMain.h" #include "ofxOpenCv.h" #include "ofxKinect.h" #include "ofImage.h" #include "ofxFlocking.h" // uncomment this to read from two kinects simultaneously //#define USE_TWO_KINECTS class testApp : public ofBaseApp { public: void setup(); void update(); void draw(); void exit(); void drawPointCloud(); void keyPressed(int key); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); ofxKinect kinect; ofxFlocking flock; #ifdef USE_TWO_KINECTS ofxKinect kinect2; #endif ofxCvColorImage colorImg; ofxCvGrayscaleImage grayImage; // grayscale depth image ofxCvGrayscaleImage grayThreshNear; // the near thresholded image ofxCvGrayscaleImage grayThreshFar; // the far thresholded image ofxCvContourFinder contourFinder; ofImage compositeImg; bool bThreshWithOpenCV; bool bDrawPointCloud; int nearThreshold; int farThreshold; int angle; // used for viewing the point cloud ofEasyCam easyCam; void makeRGBAComposite(ofxCvColorImage* _colorImg, ofxCvGrayscaleImage* _maskImg, ofImage* _composite, int _w, int _h, bool _fillBlack=false); bool overlapsRGBAComposite(ofImage* _composite, Boid b, int _w, int _h); };
[ "arlduc@blabla.local" ]
arlduc@blabla.local
25c6581ef25df1829a7403545f0e5897d9dd4be8
f94677a128a1702e11175ce9ec2a7d8dc4c20424
/src/include/utils/vec.h
f1ffd6f5a5808553ad4fa7abfcfc41b92a5ffc02
[ "MIT" ]
permissive
VenkatDatta/RhinoDB
8801ed9dae3862d98c3c5966f5c0e1824e3d0dff
1ed15b8e35e21e9c3a6b59db30619ad8e0bdb35a
refs/heads/main
2023-01-20T10:53:52.578625
2020-11-27T22:46:56
2020-11-27T22:46:56
312,355,242
1
0
MIT
2020-11-27T22:46:57
2020-11-12T17:56:03
C++
UTF-8
C++
false
false
1,316
h
#ifndef _DB_UTILS_VEC_H_ #define _DB_UTILS_VEC_H_ #include <vector> using std::vector; /// @class Vec /// @brief Allows terse construction of vectors. /// /// Vec might be better described by the name VectorStream, but since its /// purpose is to allow vectors to be built extremely tersely in unit tests. /// /// Terse Vec example: /// vector<int> v = Vec<int>() | 4 | 8 | 15 | 16 | 23 || 42; /// /// Verbose alternative: /// vector<int> v; /// v.push_back(4); /// v.push_back(8); /// v.push_back(15); /// v.push_back(16); /// v.push_back(23); /// v.push_back(42); /// /// Note: Vec is NOT fast, and should NOT be used in benchmarking or production /// code. /// template<class T> class Vec { public: inline Vec() {} inline Vec(const vector<T>& v) : v_(v) {} inline Vec(const Vec<T>& vec) : v_(vec.v_) {} // All but the last element in the terse vector declaration must be preceded // by '|'. inline Vec& operator | (T t) { v_.push_back(t); return *this; } // The final element in the terse vector declaration must be preceded by '||'. inline vector<T> operator||(T t) { v_.push_back(t); return v_; } private: // Vector being constructed. vector<T> v_; }; #endif // _DB_UTILS_VEC_H_
[ "nhvenkatdatta@gmail.com" ]
nhvenkatdatta@gmail.com
385beb75e8602c75e8a714d7514b0b824c2d20aa
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_patch_hunk_434.cpp
63ee6f5b64df81ba898139235820a68783701582
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,167
cpp
"Notifications can be dispatched at any time and can be received with register_notification."; static int Notification_init(PyObject *s, PyObject *args, PyObject *kwds) { Notification *self = (Notification *) s; int severity = 0; double time = 0; - char *message = NULL; - char *type = NULL, *plugin_instance = NULL, *type_instance = NULL, *plugin = NULL, *host = NULL; + const char *message = ""; + const char *type = "", *plugin_instance = "", *type_instance = "", *plugin = "", *host = ""; static char *kwlist[] = {"type", "message", "plugin_instance", "type_instance", "plugin", "host", "time", "severity", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etetetetetetdi", kwlist, NULL, &type, NULL, &message, NULL, &plugin_instance, NULL, &type_instance, NULL, &plugin, NULL, &host, &time, &severity)) return -1; - if (type && plugin_get_ds(type) == NULL) { + if (type[0] != 0 && plugin_get_ds(type) == NULL) { PyErr_Format(PyExc_TypeError, "Dataset %s not found", type); - FreeAll(); - PyMem_Free(message); return -1; } - sstrncpy(self->data.host, host ? host : "", sizeof(self->data.host)); - sstrncpy(self->data.plugin, plugin ? plugin : "", sizeof(self->data.plugin)); - sstrncpy(self->data.plugin_instance, plugin_instance ? plugin_instance : "", sizeof(self->data.plugin_instance)); - sstrncpy(self->data.type, type ? type : "", sizeof(self->data.type)); - sstrncpy(self->data.type_instance, type_instance ? type_instance : "", sizeof(self->data.type_instance)); - sstrncpy(self->message, message ? message : "", sizeof(self->message)); + sstrncpy(self->data.host, host, sizeof(self->data.host)); + sstrncpy(self->data.plugin, plugin, sizeof(self->data.plugin)); + sstrncpy(self->data.plugin_instance, plugin_instance, sizeof(self->data.plugin_instance)); + sstrncpy(self->data.type, type, sizeof(self->data.type)); + sstrncpy(self->data.type_instance, type_instance, sizeof(self->data.type_instance)); self->data.time = time; - self->severity = severity; - FreeAll(); - PyMem_Free(message); + sstrncpy(self->message, message, sizeof(self->message)); + self->severity = severity; return 0; } static PyObject *Notification_dispatch(Notification *self, PyObject *args, PyObject *kwds) { int ret; const data_set_t *ds; notification_t notification; double t = self->data.time; int severity = self->severity; - char *host = NULL, *plugin = NULL, *plugin_instance = NULL, *type = NULL, *type_instance = NULL; - char *message = NULL; + const char *host = self->data.host; + const char *plugin = self->data.plugin; + const char *plugin_instance = self->data.plugin_instance; + const char *type = self->data.type; + const char *type_instance = self->data.type_instance; + const char *message = self->message; static char *kwlist[] = {"type", "message", "plugin_instance", "type_instance", "plugin", "host", "time", "severity", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|etetetetetetdi", kwlist, NULL, &type, NULL, &message, NULL, &plugin_instance, NULL, &type_instance, NULL, &plugin, NULL, &host, &t, &severity)) return NULL; - notification.time = DOUBLE_TO_CDTIME_T(t); - notification.severity = severity; - sstrncpy(notification.message, message ? message : self->message, sizeof(notification.message)); - sstrncpy(notification.host, host ? host : self->data.host, sizeof(notification.host)); - sstrncpy(notification.plugin, plugin ? plugin : self->data.plugin, sizeof(notification.plugin)); - sstrncpy(notification.plugin_instance, plugin_instance ? plugin_instance : self->data.plugin_instance, sizeof(notification.plugin_instance)); - sstrncpy(notification.type, type ? type : self->data.type, sizeof(notification.type)); - sstrncpy(notification.type_instance, type_instance ? type_instance : self->data.type_instance, sizeof(notification.type_instance)); - notification.meta = NULL; - FreeAll(); - PyMem_Free(message); - - if (notification.type[0] == 0) { + if (type[0] == 0) { PyErr_SetString(PyExc_RuntimeError, "type not set"); return NULL; } - ds = plugin_get_ds(notification.type); + ds = plugin_get_ds(type); if (ds == NULL) { - PyErr_Format(PyExc_TypeError, "Dataset %s not found", notification.type); + PyErr_Format(PyExc_TypeError, "Dataset %s not found", type); return NULL; } + notification.time = DOUBLE_TO_CDTIME_T(t); + notification.severity = severity; + sstrncpy(notification.message, message, sizeof(notification.message)); + sstrncpy(notification.host, host, sizeof(notification.host)); + sstrncpy(notification.plugin, plugin, sizeof(notification.plugin)); + sstrncpy(notification.plugin_instance, plugin_instance, sizeof(notification.plugin_instance)); + sstrncpy(notification.type, type, sizeof(notification.type)); + sstrncpy(notification.type_instance, type_instance, sizeof(notification.type_instance)); + notification.meta = NULL; if (notification.time == 0) notification.time = cdtime(); if (notification.host[0] == 0) sstrncpy(notification.host, hostname_g, sizeof(notification.host)); if (notification.plugin[0] == 0) sstrncpy(notification.plugin, "python", sizeof(notification.plugin));
[ "993273596@qq.com" ]
993273596@qq.com
93e7cac26f90571d8719aa5ef9c766257ac78468
4a960c6095f21a70098e6660b83e9978afc72ddb
/Source/ProjetDecouverte/LayerPiece.cpp
c05ce814ba78ba96584ae964d10519e1b7aaea23
[]
no_license
Saturn1B/ProjetDecouverte
9dd1cb96cbaeae5d8b6da948eba0c8d201b6a010
9ed717d3795556e3def7ed3e235ee1159c18c649
refs/heads/master
2023-05-31T06:38:20.011118
2021-06-23T13:51:53
2021-06-23T13:51:53
356,182,685
0
0
null
null
null
null
UTF-8
C++
false
false
7,373
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "LayerPiece.h" #include "NiagaraComponent.h" #include "NiagaraFunctionLibrary.h" #include "NiagaraSystem.h" #include "MyPlayerController2.h" #define LOG(fstring) GLog->Log(fstring) // Sets default values ALayerPiece::ALayerPiece() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); //Visible Component Visible = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Cube")); Visible->SetupAttachment(RootComponent); Visible->bHiddenInGame = false; static ConstructorHelpers::FObjectFinder<UForceFeedbackEffect> MyVisualAsset1(TEXT("/Game/FeedBack/Haptic02.Haptic02")); if (MyVisualAsset1.Succeeded()) { haptic1 = MyVisualAsset1.Object; } static ConstructorHelpers::FObjectFinder<UForceFeedbackEffect> MyVisualAsset2(TEXT("/Game/FeedBack/Haptic03.Haptic03")); if (MyVisualAsset2.Succeeded()) { haptic2 = MyVisualAsset2.Object; } static ConstructorHelpers::FObjectFinder<UMaterialInstance> MyVisualAsset3(TEXT("/Game/02_Materials/M_Planet/inst/Lave/M_Crame_inst.M_Crame_inst")); if (MyVisualAsset3.Succeeded()) { indestructibleMat = MyVisualAsset3.Object; } // find sound static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset1(TEXT("/Game/06_SFX/Sound/SFX_Pickaxe1.SFX_Pickaxe1")); if (MyAudioAsset1.Succeeded()) { pickaxeSound.Add(MyAudioAsset1.Object); } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset2(TEXT("/Game/06_SFX/Sound/SFX_Pickaxe2.SFX_Pickaxe2")); if (MyAudioAsset2.Succeeded()) { pickaxeSound.Add(MyAudioAsset2.Object); } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset3(TEXT("/Game/06_SFX/Sound/SFX_Pickaxe2.SFX_Pickaxe2")); if (MyAudioAsset3.Succeeded()) { pickaxeSound.Add(MyAudioAsset3.Object); } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset4(TEXT("/Game/06_SFX/Sound/SFX_Pump2.SFX_Pump2")); if (MyAudioAsset4.Succeeded()) { liquidSound = MyAudioAsset4.Object; } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset5(TEXT("/Game/06_SFX/Sound/SFX_Explosion1.SFX_Explosion1")); if (MyAudioAsset5.Succeeded()) { explosionSound.Add(MyAudioAsset5.Object); } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset6(TEXT("/Game/06_SFX/Sound/SFX_Explosion2.SFX_Explosion2")); if (MyAudioAsset6.Succeeded()) { explosionSound.Add(MyAudioAsset6.Object); } static ConstructorHelpers::FObjectFinder<USoundBase> MyAudioAsset7(TEXT("/Game/06_SFX/Sound/SFX_Explosion3.SFX_Explosion3")); if (MyAudioAsset7.Succeeded()) { explosionSound.Add(MyAudioAsset7.Object); } } // Called when the game starts or when spawned void ALayerPiece::BeginPlay() { Super::BeginPlay(); HP = LayerHp + PieceHP; MyController = Cast<APlayerController>(GetWorld()->GetFirstPlayerController()); TArray<AActor*> FoundPlayer; UGameplayStatics::GetAllActorsOfClass(GetWorld(), AMyPlayerController2::StaticClass(), FoundPlayer); Player = Cast<AMyPlayerController2>(FoundPlayer[0]); if (core) { dynamicMaterial = UMaterialInstanceDynamic::Create(coreMat, this); Visible->SetMaterial(0, dynamicMaterial); HPMultiplier = HP / 10; TArray<AActor*> FoundChildren2; Planet->GetAttachedActors(FoundChildren); int layersFound = FoundChildren.Num(); LOG(FString::FromInt(FoundChildren.Num()) + "part found"); for (size_t j = 0; j < layersFound; j++) { FoundChildren[j]->GetAttachedActors(FoundChildren2); FoundChildren += FoundChildren2; FoundChildren2.Empty(); } } } void ALayerPiece::LooseHP(int damageValue, FVector destroyLoc) { HP -= damageValue; if (liquid) { UGameplayStatics::PlaySound2D(GetWorld(), liquidSound); } else { int r = FMath::RandRange(0, pickaxeSound.Num() - 1); UGameplayStatics::PlaySound2D(GetWorld(), pickaxeSound[r]); } if (core) { dynamicMaterial->SetScalarParameterValue(FName("EmissiveMultiplier"), (HP / HPMultiplier) / 10); } if (HP <= 0) { if(!liquid && !core) { Visible->SetSimulatePhysics(true); Visible->SetEnableGravity(false); Visible->AddImpulse(Visible->GetRelativeLocation() * strength); if (!Player->tuto1 && Tutorisation != NULL) { Player->tuto1 = true; Tutorisation->ResetPopup(); FString text = "Hey, bien joue pilleur! Belle explosion! Va dans l'onglet ressource pour voir ce que t'as recolte."; Tutorisation->SetPopup(text, 15.0f, 1); } else if (Player->tuto1 && !Player->tuto2 && Tutorisation != NULL) { Player->tuto2 = true; Tutorisation->ResetPopup(); FString text = "Tiens on dirait qu'il y a de l'eau la dessous, il te faut peut etre un autre outil pour l'enlever. Va dans la carte galactique, il y a la boutique, tu pourras y trouver de nouveaux outils."; Tutorisation->SetPopup(text, 15.0f, 0); } } if(core) { MyController->ClientPlayForceFeedback(haptic2, false, FName("Haptic3")); GetWorld()->GetFirstPlayerController()->PlayerCameraManager->StartCameraShake(CamShakeBig, 1); } else { MyController->ClientPlayForceFeedback(haptic1, false, FName("Haptic2")); GetWorld()->GetFirstPlayerController()->PlayerCameraManager->StartCameraShake(CamShakeSmall, 1); } UNiagaraFunctionLibrary::SpawnSystemAtLocation(GetWorld(), DestroyVFX, destroyLoc); if (lavaPiece != NULL && lavaPiece->lava == true) { lavaPiece->LavaSpread(destroyLoc); } if (liquid) { UGameplayStatics::PlaySound2D(GetWorld(), explosionSound[2]); } else if (core) { UGameplayStatics::PlaySound2D(GetWorld(), explosionSound[1]); } else { UGameplayStatics::PlaySound2D(GetWorld(), explosionSound[0]); } if (liquid) { Kill(); } else if (core) { FTimerHandle handle; GetWorldTimerManager().SetTimer(handle, this, &ALayerPiece::Kill, 0.1f, false); } else { FTimerHandle handle; GetWorldTimerManager().SetTimer(handle, this, &ALayerPiece::Kill, 1, false); } } } void ALayerPiece::Kill() { if (core) { Player->tuto2 = false; if (CoreAchieve != NULL) { CoreAchieve->CompleteAchievment(); } for (AActor* piece : FoundChildren) { if (piece != NULL && Cast<ALayerPiece>(piece) && !Cast<ALayerPiece>(piece)->core) { piece->Destroy(); } else if (piece != NULL && !Cast<ALayerPiece>(piece)) { piece->Destroy(); } } //FoundChildren.Empty(); Destroy(); /*if (FoundChildren.Num() > 1) { DestroyPiece(0); }*/ } else { Destroy(); } } void ALayerPiece::DestroyPiece(int i) { if (FoundChildren[i] != NULL && Cast<ALayerPiece>(FoundChildren[i]) && !Cast<ALayerPiece>(FoundChildren[i])->core) { FoundChildren[i]->Destroy(); } if (i + 1 < FoundChildren.Num()) { FTimerHandle handle; FTimerDelegate TimerDel = FTimerDelegate::CreateUObject(this, &ALayerPiece::DestroyPiece, i+1); GetWorldTimerManager().SetTimer(handle, TimerDel, 0.1f, false); } else { Destroy(); } } void ALayerPiece::LavaSpread(FVector destroyLoc) { UNiagaraFunctionLibrary::SpawnSystemAtLocation(GetWorld(), LavaSpreadFX, destroyLoc); for(ALayerPiece* spreadPiece : spreadPieces) { spreadPiece->indestructible = true; spreadPiece->Visible->SetMaterial(0, indestructibleMat); } }
[ "60229050+Saturn1B@users.noreply.github.com" ]
60229050+Saturn1B@users.noreply.github.com
4d329a32161135e49a1ab447e610f3df6f670a99
b509795eb74cb2f4e7544e382636ee70a9907a1a
/map.h
df016465a1de704e3dc13ef9d55864471cf1668e
[]
no_license
JustinHue/Bouncer_CPlusPlus
5dc3dc1e696f82d0e2d5678ccfd48d48d60bab5b
e76cf99b12cb55e1fa189f7b9cc1237a38fecdba
refs/heads/master
2021-01-18T14:15:54.735234
2013-06-27T03:24:18
2013-06-27T03:24:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef __MAP_H__ #define __MAP_H__ #include <allegro.h> class Map { private: public: Map(); ~Map(); void render(BITMAP *g2d); void update(const double delta); }; #endif
[ "justinhellsten@gmail.com" ]
justinhellsten@gmail.com
8a39cbfd165a44794e7bbfef0bf991c3b19f3711
a6df07a3e96467b46c3066059c9691468ecb6f91
/Scintilla/src/Catalogue.cxx
0357a73487897c26c64d8c92a107a05401b2e4dc
[ "LicenseRef-scancode-scintilla" ]
permissive
cnsheds/SouiEditor
7555b26c899619e9da5f697f6b6c4c83d63443c4
b2a62f185398608ccfab968f6aa3be489982c665
refs/heads/master
2020-12-02T07:48:56.393076
2017-08-10T05:45:39
2017-08-10T05:45:39
96,729,035
5
1
null
null
null
null
UTF-8
C++
false
false
1,988
cxx
// Scintilla source code edit control /** @file Catalogue.cxx ** Colourise for particular languages. **/ // Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstdlib> #include <cassert> #include <cstring> #include <stdexcept> #include <vector> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "LexerModule.h" #include "Catalogue.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static std::vector<LexerModule *> lexerCatalogue; static int nextLanguage = SCLEX_AUTOMATIC+1; const LexerModule *Catalogue::Find(int language) { Scintilla_LinkLexers(); for (const LexerModule *lm : lexerCatalogue) { if (lm->GetLanguage() == language) { return lm; } } return 0; } const LexerModule *Catalogue::Find(const char *languageName) { Scintilla_LinkLexers(); if (languageName) { for (const LexerModule *lm : lexerCatalogue) { if (lm->languageName && (0 == strcmp(lm->languageName, languageName))) { return lm; } } } return 0; } void Catalogue::AddLexerModule(LexerModule *plm) { if (plm->GetLanguage() == SCLEX_AUTOMATIC) { plm->language = nextLanguage; nextLanguage++; } lexerCatalogue.push_back(plm); } // To add or remove a lexer, add or remove its file and run LexGen.py. // Force a reference to all of the Scintilla lexers so that the linker will // not remove the code of the lexers. int Scintilla_LinkLexers() { static int initialised = 0; if (initialised) return 0; initialised = 1; // Shorten the code that declares a lexer and ensures it is linked in by calling a method. #define LINK_LEXER(lexer) extern LexerModule lexer; Catalogue::AddLexerModule(&lexer); //++Autogenerated -- run scripts/LexGen.py to regenerate //**\(\tLINK_LEXER(\*);\n\) LINK_LEXER(lmHTML); LINK_LEXER(lmPHPSCRIPT); LINK_LEXER(lmXML); //--Autogenerated -- end of automatically generated section return 1; }
[ "cnsheds@gmail.com" ]
cnsheds@gmail.com
a3377a1b59e978d700f074d7eb58d4288b07c6c5
b2b9e4d616a6d1909f845e15b6eaa878faa9605a
/C++/201510020918.cpp
07203d2165caacc3c8f98a4af08a18639fb20c07
[]
no_license
JinbaoWeb/ACM
db2a852816d2f4e395086b2b7f2fdebbb4b56837
021b0c8d9c96c1bc6e10374ea98d0706d7b509e1
refs/heads/master
2021-01-18T22:32:50.894840
2016-06-14T07:07:51
2016-06-14T07:07:51
55,882,694
0
0
null
null
null
null
UTF-8
C++
false
false
4,123
cpp
#include<iostream> #include<cstdio> #include<cstring> #define N 100001*2 #define inf 0x7fffffff using namespace std; int n,q,cnt=1,sz; int head[N],deep[N],size[N],pos[N],belong[N]; int fa[N][17],id[N]; int array[N]; struct edge{int to,next,v;}e[N<<1]; struct seg{int l,r,mx,a,c;}t[N<<2]; void insert(int u,int v,int w) { e[++cnt].to=v;e[cnt].next=head[u];e[cnt].v=w;head[u]=cnt; e[++cnt].to=u;e[cnt].next=head[v];e[cnt].v=w;head[v]=cnt; } int lca(int x,int y) { if(deep[x]<deep[y])swap(x,y); int t=deep[x]-deep[y]; for(int i=0;i<=16;i++) if(t&(1<<i))x=fa[x][i]; for(int i=16;i>=0;i--) if(fa[x][i]!=fa[y][i]) {x=fa[x][i];y=fa[y][i];} if(x==y)return x; return fa[x][0]; } void pushdown(int k) { if(t[k].l==t[k].r)return; if(t[k].c!=-1) { t[k<<1].a=t[k<<1|1].a=0; t[k<<1].c=t[k<<1|1].c=t[k].c; t[k<<1].mx=t[k<<1|1].mx=t[k].c; t[k].c=-1; } if(t[k].a) { t[k<<1].mx+=t[k].a;t[k<<1|1].mx+=t[k].a; if(t[k<<1].c!=-1)t[k<<1].c+=t[k].a; else t[k<<1].a+=t[k].a; if(t[k<<1|1].c!=-1)t[k<<1|1].c+=t[k].a; else t[k<<1|1].a+=t[k].a; t[k].a=0; } } void build(int k,int l,int r) { t[k].l=l;t[k].r=r;t[k].c=-1; if(l==r)return; int mid=(l+r)>>1; build(k<<1,l,mid);build(k<<1|1,mid+1,r); } void pushup(int k) {t[k].mx=max(t[k<<1].mx,t[k<<1|1].mx);} void change(int k,int x,int y,int v) { pushdown(k); int l=t[k].l,r=t[k].r; if(l==x&&y==r){t[k].mx=t[k].c=v;return;} int mid=(l+r)>>1; if(mid>=y)change(k<<1,x,y,v); else if(mid<x)change(k<<1|1,x,y,v); else { change(k<<1,x,mid,v); change(k<<1|1,mid+1,y,v); } pushup(k); } void add(int k,int x,int y,int v) { pushdown(k); int l=t[k].l,r=t[k].r; if(l==x&&y==r){t[k].mx+=v;t[k].a=v;return;} int mid=(l+r)>>1; if(mid>=y)add(k<<1,x,y,v); else if(mid<x)add(k<<1|1,x,y,v); else { add(k<<1,x,mid,v); add(k<<1|1,mid+1,y,v); } pushup(k); } int ask(int k,int x,int y) { pushdown(k); int l=t[k].l,r=t[k].r; if(l==x&&y==r)return t[k].mx; int mid=(l+r)>>1; if(mid>=y)return ask(k<<1,x,y); else if(mid<x)return ask(k<<1|1,x,y); else return max(ask(k<<1,x,mid),ask(k<<1|1,mid+1,y)); } void solvechange(int x,int f,int v) { while(belong[x]!=belong[f]) { change(1,pos[belong[x]],pos[x],v); x=fa[belong[x]][0]; } if(pos[f]+1<=pos[x]) change(1,pos[f]+1,pos[x],v); } void solveadd(int x,int f,int v) { while(belong[x]!=belong[f]) { add(1,pos[belong[x]],pos[x],v); x=fa[belong[x]][0]; } if(pos[f]+1<=pos[x]) add(1,pos[f]+1,pos[x],v); } int solveask(int x,int f) { int mx=-inf; while(belong[x]!=belong[f]) { mx=max(mx,ask(1,pos[belong[x]],pos[x])); x=fa[belong[x]][0]; } if(pos[f]+1<=pos[x]) mx=max(mx,ask(1,pos[f]+1,pos[x])); return mx; } void solve(int q) { char s[10]; int u,v,w,f,t,a,b,c; while(q--) { scanf("%d",&a); switch(a) { case '1':scanf("%d%d%d",&u,&v,&w);f=lca(u,v); solvechange(u,f,w);solvechange(v,f,w); break; case '2':scanf("%d%d%d",&u,&v,&w);f=lca(u,v); printf("%d\n",max(solveask(u,f),solveask(v,f))); break; } } } void dfs1(int x,int f) { size[x]=1; for(int i=1;i<=16;i++) if((1<<i)<=deep[x]) fa[x][i]=fa[fa[x][i-1]][i-1]; else break; for(int i=head[x];i;i=e[i].next) { if(e[i].to==f)continue; deep[e[i].to]=deep[x]+1; fa[e[i].to][0]=x; dfs1(e[i].to,x); size[x]+=size[e[i].to]; } } void dfs2(int x,int chain) { belong[x]=chain; pos[x]=++sz; int k=0; for(int i=head[x];i;i=e[i].next) { if(deep[x]<deep[e[i].to]) { if(size[e[i].to]>size[k])k=e[i].to; } else {id[i>>1]=x;add(1,pos[x],pos[x],e[i].v);} } if(!k)return; dfs2(k,chain); for(int i=head[x];i;i=e[i].next) if(deep[x]<deep[e[i].to]&&k!=e[i].to) dfs2(e[i].to,e[i].to); } int main() { scanf("%d%d",&n,&q); for (int i=1;i<=n;i++){ scanf("%d",&array[i]); } for(int i=1;i<=n-1;i++) { int u,v,w; scanf("%d%d",&u,&v); w=array[i]; insert(u,v,w); } build(1,1,n); dfs1(1,0); dfs2(1,1); solve(q); return 0; }
[ "jinbaosite@yeah.net" ]
jinbaosite@yeah.net
dcb0876302f93e0120a298cd7b1a309941b429df
94e5a9e157d3520374d95c43fe6fec97f1fc3c9b
/UVA/uva 11192.cpp
ddd7ffd60754dae26b0235653b84a65e3ee8dc53
[ "MIT" ]
permissive
dipta007/Competitive-Programming
0127c550ad523884a84eb3ea333d08de8b4ba528
998d47f08984703c5b415b98365ddbc84ad289c4
refs/heads/master
2021-01-21T14:06:40.082553
2020-07-06T17:40:46
2020-07-06T17:40:46
54,851,014
8
4
null
2020-05-02T13:14:41
2016-03-27T22:30:02
C++
UTF-8
C++
false
false
800
cpp
#include<cstdio> #include<sstream> #include<cstdlib> #include<cctype> #include<cmath> #include<algorithm> #include<set> #include<queue> #include<stack> #include<list> #include<iostream> #include<fstream> #include<numeric> #include<string> #include<vector> #include<cstring> #include<map> #include<iterator> using namespace std; int main() { while(1) { int g; char a[102]; scanf("%d",&g); if(g==0) break; scanf("%s",a); int s=strlen(a); int k=s/g; for(int i=0;i<s;i=i+k) { for(int j=i,l=i+k-1,m=0;m<k/2;m++,j++,l--) { char temp; temp=a[l]; a[l]=a[j]; a[j]=temp; } } printf("%s\n",a); } }
[ "iamdipta@gmail.com" ]
iamdipta@gmail.com
8f4d1025b11ecb9ba4c8b40993e94414ced9f629
0ace88b033ed0e9b7ca366bcfd37b850279ddd7f
/Tagger/Widgets/LaunchDialog.cpp
36230f6d965b15c2eb3a8c8f639245643056d4fb
[]
no_license
ankelesh/qTagger
42c9b93a0b98066074ae717e58c5a331d43bf0ff
8e235a49ef326b8c7278a61aff10b82e1ba1e89b
refs/heads/master
2020-05-16T00:32:14.881965
2019-11-29T15:54:06
2019-11-29T15:54:06
181,184,266
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
#include "LaunchDialog.h" #include <QtWidgets/QLabel> #include <QtWidgets/qpushbutton.h> LaunchDialog::LaunchDialog(LaunchInfo::options& opt, QRect& rct) : opts(opt), mainlayout(new QVBoxLayout(this)), header(new QLabel("Please check tagger settings:", this)), setform(new settingsForm(this, opts)), butlay(new QHBoxLayout(this)), ok(new QPushButton("Ok", this)), cancel(new QPushButton("Cancel", this)), scr(rct) // This constructor is optimal { //Creating gui this->setLayout(mainlayout); mainlayout->addWidget(header); mainlayout->addWidget(setform); mainlayout->addLayout(butlay); butlay->addWidget(ok); butlay->addWidget(cancel); header->show(); ok->show(); cancel->show(); header->show(); setform->show(); QObject::connect(setform, &settingsForm::done, this, &LaunchDialog::onOk); QObject::connect(ok, &QPushButton::clicked, this, &LaunchDialog::onOk); QObject::connect(cancel, &QPushButton::clicked, this, &QWidget::close); } void LaunchDialog::onOk() // this slot transmits ok-button clicks outside { emit done(); }
[ "ankeleshbnet@inbox.ru" ]
ankeleshbnet@inbox.ru
4eed6d00a12cbc6c467e1ab786e5f209f8e5eb6d
5e26a971e0195b18eed85c87b91d0baf17f40061
/tests/test_mmm_int8.cpp
51686b1ab41ce4fcc3eb33c7efb9a1d663656480
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-2-Clause" ]
permissive
xgmiao/bolt
2f28bf81b4c53eaaa71740b2184d4b1c68f0c6df
75b0aafad318d250db7cb96492c18f16a913929d
refs/heads/master
2022-11-08T01:38:53.465700
2020-06-18T14:35:03
2020-06-18T14:35:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,301
cpp
// Copyright (C) 2019. Huawei Technologies Co., Ltd. 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. #include <string.h> #include "blas-enhance.h" #include "ut_util.h" int main(int argc, char** argv) { CHECK_REQUIREMENT(argc == 4); U32 m = atoi(argv[1]); U32 k = atoi(argv[2]); U32 n = atoi(argv[3]); DataType dt = DT_I8; DataType odt = DT_I32; TensorDesc A_desc = tensor2df(dt, DF_NORMAL, m, k); TensorDesc B_desc = tensor2df(dt, DF_NORMAL, k, n); TensorDesc tranDescB; TensorDesc C_desc = tensor2df(odt, DF_NORMAL, m, n); U32 bytes = 0; U32 k4 = k; if (k4 % 4 != 0) { k4 = (k4 / 4) * 4 + 4; } INT8* A = (INT8*)ut_input_v(m * k, DT_I8, UT_INIT_RANDOM); INT8* B = (INT8*)ut_input_v(k * n, DT_I8, UT_INIT_RANDOM); INT8* B_tran = (INT8*)ut_input_v(k4 * n + 32, DT_I8, UT_INIT_ZERO); I32* C = (I32*)ut_input_v(m * n, DT_I32, UT_INIT_ZERO); I32* C_ref = (I32*)ut_input_v(m * n, DT_I32, UT_INIT_ZERO); CHECK_STATUS(matrix_matrix_multiply_tmp_bytes(A_desc, B_desc, &bytes, UT_ARCH)); INT8* tmp = (INT8 *)ut_input_v(bytes, DT_I8, UT_INIT_ZERO); matrix_matrix_multiply_transform_rhs(B_desc, B, &tranDescB, B_tran); if (UT_CHECK){ CHECK_STATUS(matrix_matrix_multiply(A_desc, A, tranDescB, B_tran, bytes, tmp, C_desc, C, UT_ARCH)); // naive implement CHECK_STATUS(matrix_matrix_multiply(A_desc, A, B_desc, B, bytes, tmp, C_desc, C_ref, CPU_GENERAL)); // check ut_check_v(C, C_ref, m*n, DT_I32, 1, __FILE__, __LINE__); } // benchmark double time_start = ut_time_ms(); for (int iter = 0; iter < UT_LOOPS; iter++) { matrix_matrix_multiply(A_desc, A, tranDescB, B_tran, bytes, tmp, C_desc, C, UT_ARCH); } double time_end = ut_time_ms(); double time = (time_end - time_start) / UT_LOOPS; // log performance data char buffer[150]; char params[120]; sprintf(params, "(%u %u)+(%u %u)=(%u %u)", m, k, k, n, m, n); sprintf(buffer, "%20s, %80s", "MatrixMultiply", params); double ops = 2.0 * m * n * k + 1.0 * m * n; ut_log(DT_I8, buffer, ops, time); free(A); free(B); free(B_tran); free(C); free(C_ref); free(tmp); return 0; }
[ "jianfeifeng@outlook.com" ]
jianfeifeng@outlook.com
62c6779ca5c168ef95fa14a8c3ffb16ea747db4e
7e6ec7aa30a113650f66e8f945d0b6a2ded825d5
/XLOOPS-GiNaC_TransformTest/KhiemCode/my_fns.h
94593e1aa78f12c20ddf4c8da4ffb3cfe1039d11
[]
no_license
quanpla/xloops-ginac
d1db82c0de54a8894deecc99de936488248049d0
b8d2487ed07da49aa7b7b9e5a054040209734f34
refs/heads/master
2020-05-18T03:52:57.026251
2009-09-13T14:38:44
2009-09-13T14:38:44
32,206,011
1
0
null
null
null
null
UTF-8
C++
false
false
1,946
h
/******************************************************************************* ** ** xloop-ginacs Project ** 1Loop4Pt implementation ** ** ** HCMUNS, ** June 2008 ** ** ** Author(s): Son, D. H. (sondo01@gmail.com) ** Khiem, Phan (phanhongkhiem@gmail.com) ** Quan, Phan (anhquan.phanle@gmail.com) ******************************************************************************** ** Historial Log: ** Date Version Author Description ** _________ _______ _________ ________________________________ ** 20090214 1.0 Quan Phan Extract this file from the big code ** *******************************************************************************/ #ifndef __XLOOPS_ONELOOP_4PT_MY_FUNS_H__ #define __XLOOPS_ONELOOP_4PT_MY_FUNS_H__ #include <ginac/ginac.h> using namespace std; using namespace GiNaC; namespace xloops{ /* I override some functions for the case of small argument. Those functions include: is_zero, csgn, step */ DECLARE_FUNCTION_1P(my_is_zero); DECLARE_FUNCTION_1P(my_csgn); DECLARE_FUNCTION_1P(my_step); DECLARE_FUNCTION_1P(my_is_negative); DECLARE_FUNCTION_1P(my_is_positive); ex my_evalf(const ex &x); // III.9 Misc. Functions DECLARE_FUNCTION_1P(myfn_delta);//Delta Function DECLARE_FUNCTION_1P(myfn_IvZero); DECLARE_FUNCTION_1P(myfn_Zero); DECLARE_FUNCTION_1P(myfn_IvTheta); DECLARE_FUNCTION_1P(myfn_Sign0); DECLARE_FUNCTION_2P(fn_eta); ex fn_eta_plus(const ex &sigma, const ex &z1, const ex &z2, const ex &P); ex fn_eta_minus(const ex &sigma, const ex &z1, const ex &z2, const ex &P); ex fn_R(const ex &T1, const ex &T2); ex fn_LogACG(const ex &a, const ex &b, const ex &x, const ex &y); ex fn_LogARG(const ex &a, const ex &b, const ex &x, const ex &y); ex fn_LogAG(const ex &a, const ex &b, const ex &x, const ex &y); ex p2q(const ex &p); // convert p to q } // Namespace xloops #endif // __XLOOPS_ONELOOP_4PT_MY_FUNS_H__
[ "anhquan.phanle@d83109c4-a28d-11dd-9dc9-65bc890fb60a" ]
anhquan.phanle@d83109c4-a28d-11dd-9dc9-65bc890fb60a
0280e83b1a6be6eb791882ff09ac25f145795660
73e5c6dbf80eb7ce7eb597ed286bf1771f7ad405
/examples/smp/libsrc/smpread.cpp
9f8b2ca27a604cfa0859bf424bb247a64a81fe3a
[ "MIT" ]
permissive
arunsathvik/KTAB
62100ddb03b3c748509a11c046036e60d514d083
afbd45c8ba6011d65c420f85c7791edf78c6524a
refs/heads/master
2021-04-03T02:30:44.847412
2016-11-23T06:18:30
2016-11-23T06:18:30
64,843,640
0
0
null
2016-08-17T07:24:25
2016-08-03T12:16:53
C++
UTF-8
C++
false
false
12,292
cpp
// -------------------------------------------- // Copyright KAPSARC. Open source MIT License. // -------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2015 King Abdullah Petroleum Studies and Research Center // // 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. // -------------------------------------------- // Demonstrate a very basic, but highly parameterizable, Spatial Model of Politics. // -------------------------------------------- // TODO: consolidate error checking for read functions. // These reader functions do a lot of very similar error checking, // so duplicative code should be put in sub-functions. // -------------------------------------------- #include <string> #include <tinyxml2.h> #include <vector> #include "kmodel.h" #include "smp.h" #include "minicsv.h" namespace SMPLib { using std::cout; using std::endl; using std::flush; using std::function; using std::get; using std::string; using KBase::PRNG; using KBase::KMatrix; using KBase::KException; using KBase::Actor; using KBase::Model; using KBase::Position; using KBase::VctrPstn; using KBase::BigRAdjust; using KBase::BigRRange; using KBase::VPModel; using KBase::State; using KBase::StateTransMode; using KBase::VotingRule; using KBase::PCEModel; using KBase::ReportingLevel; using tinyxml2::XMLElement; using tinyxml2::XMLDocument; // -------------------------------------------- // -------------------------------------------- SMPModel * SMPModel::csvRead(string fName, uint64_t s, vector<bool> f) { using KBase::KException; char * errBuff; // as sprintf requires csv::ifstream inStream(fName.c_str()); inStream.set_delimiter(',', "$$"); inStream.enable_trim_quote_on_str(true, '\"'); const bool opened = inStream.is_open(); assert (opened); string scenName = ""; string scenDesc = ""; unsigned int numActor = 0; unsigned int numDim = 0; inStream.read_line(); inStream >> scenName >> scenDesc >> numActor >> numDim; cout << "Scenario name: |" << scenName << "|" << endl; cout << flush; assert(scenName.length() <= Model::maxScenNameLen); printf("Number of actors: %u \n", numActor); printf("Number of dimensions: %u \n", numDim); cout << endl << flush; if (numDim < 1) { // lower limit throw(KBase::KException("SMPModel::readCSVStream: Invalid number of dimensions")); } assert(0 < numDim); if ((numActor < minNumActor) || (maxNumActor < numActor)) { // avoid impossibly low or ridiculously large throw(KBase::KException("SMPModel::readCSVStream: Invalid number of actors")); } assert(minNumActor <= numActor); assert(numActor <= maxNumActor); // get the names of dimensions. // format (for 3 dimensions) is like this: // Actor,Description,Power,Pstn1,Sal1,Pstn2,Sal2,Pstn3,Sal3, inStream.read_line(); string dummyField; inStream >> dummyField; // skip "Actor" inStream >> dummyField; // skip "Descripton" inStream >> dummyField; // skip "Power" auto dNames = vector<string>(); for (unsigned int d = 0; d < numDim; d++) { string dimName, salName; inStream >> dimName; inStream >> salName; assert(dimName.length() <= maxDimDescLen); dNames.push_back(dimName); printf("Dimension %2u: %s \n", d, dNames[d].c_str()); } cout << endl; // Read actor data auto actorNames = vector<string>(); auto actorDescs = vector<string>(); auto cap = KMatrix(numActor, 1); auto nra = KMatrix(numActor, 1); auto pos = KMatrix(numActor, numDim); auto sal = KMatrix(numActor, numDim); for (unsigned int i = 0; i < numActor; i++) { string aName = ""; string aDesc = ""; double aCap = 0.0; inStream.read_line(); inStream >> aName >> aDesc >> aCap; // names must have at least 1 character assert(0 < aName.length()); assert(aName.length() <= Model::maxActNameLen); actorNames.push_back(aName); printf("Actor %3u name: %s \n", i, actorNames[i].c_str()); // empty descriptions are allowed assert(aDesc.length() <= Model::maxActDescLen); actorDescs.push_back(aDesc); printf("Actor %3u desc: %s \n", i, actorDescs[i].c_str()); printf("Actor %3u power: %5.1f \n", i, aCap); assert(0 <= aCap); // zero weight is pointless, but not incorrect assert(aCap < 1E8); // no real upper limit, so this is just a sanity-check cap(i, 0) = aCap; // get position and salience for each dimension double salI = 0.0; for (unsigned int d = 0; d < numDim; d++) { double dPos = 0.0; // on [0, 100] scale double dSal = 0.0; // on [0, 100] scale inStream >> dPos >> dSal; printf("pos[%3u , %3u] = %5.3f \n", i, d, dPos); cout << flush; if ((dPos < 0.0) || (+100.0 < dPos)) { // lower and upper limit errBuff = newChars(100); sprintf(errBuff, "SMPModel::readCSVStream: Out-of-bounds position for actor %u on dimension %u: %f", i, d, dPos); throw(KException(errBuff)); } assert(0.0 <= dPos); assert(dPos <= 100.0); pos(i, d) = dPos; if ((dSal < 0.0) || (+100.0 < dSal)) { // lower and upper limit errBuff = newChars(100); sprintf(errBuff, "SMPModel::readCSVStream: Out-of-bounds salience for actor %u on dimension %u: %f", i, d, dSal); throw(KException(errBuff)); } assert(0.0 <= dSal); salI = salI + dSal; printf("sal[%3u, %3u] = %5.3f \n", i, d, dSal); cout << flush; if (+100.0 < salI) { // upper limit: no more than 100% of attention to all issues errBuff = newChars(100); sprintf(errBuff, "SMPModel::readCSVStream: Out-of-bounds total salience for actor %u: %f", i, salI); throw(KException(errBuff)); } assert(salI <= 100.0); sal(i, d) = dSal; } cout << endl << flush; } cout << "Position matrix:" << endl; pos.mPrintf("%5.1f "); cout << endl << endl << flush; cout << "Salience matrix:" << endl; sal.mPrintf("%5.1f "); cout << endl << flush; // get them into the proper internal scale: pos = pos / 100.0; sal = sal / 100.0; // TODO: figure out representation of "accomodate" matrix cout << "Setting ideal-accomodation matrix to identity matrix" << endl; auto accM = KBase::iMat(numActor); // now that it is read and verified, use the data auto sm0 = SMPModel::initModel(actorNames, actorDescs, dNames, cap, pos, sal, accM, s, f); return sm0; } // end of readCSVStream SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) { using KBase::enumFromName; cout << "Start SMPModel::readXML of " << fName << endl; SMPModel* smp = nullptr; auto getFirstChild = [](XMLElement* prntEl, const char * name) { XMLElement* childEl = prntEl->FirstChildElement(name); assert(nullptr != childEl); return childEl; }; XMLDocument d1; try { d1.LoadFile(fName.c_str()); auto eid = d1.ErrorID(); if (0 != eid) { cout << "ErrorID: " << eid << endl; throw KException(d1.GetErrorStr1()); } else { // missing data causes the missing XMLElement* to come back as nullptr XMLElement* scenEl = d1.FirstChildElement("Scenario"); assert(nullptr != scenEl); auto scenNameEl = getFirstChild(scenEl, "name"); try { const char * sName = scenNameEl->GetText(); printf("Name of scenario: %s\n", sName); } catch (...) { throw (KException("Error reading file header")); } auto scenDescEl = getFirstChild(scenEl, "desc"); const char* sn2 = scenDescEl->GetText(); assert(nullptr != sn2); auto seedEl = getFirstChild(scenEl, "prngSeed"); const char* sd2 = seedEl->GetText(); assert(nullptr != sd2); uint64_t seed = std::stoull(sd2); printf("Read PRNG seed: %020llu \n", seed); smp = new SMPModel(sn2, seed); // TODO: something besides default SQL flags auto modelParamsEl = getFirstChild(scenEl, "ModelParameters"); function <string (const char*)> showChild = [getFirstChild, modelParamsEl](const char* name ) { auto el = getFirstChild(modelParamsEl, name); string s = el->GetText(); cout << " " << name << ": " << s << endl << flush; return s; }; cout << "Reading model parameters from XML scenario ..." << endl << flush; auto vpmScen = enumFromName<VPModel>(showChild("VictoryProbModel"), KBase::VPModelNames); auto vrScen = enumFromName<VotingRule>(showChild("VotingRule"), KBase::VotingRuleNames); auto pcemScen = enumFromName<PCEModel>(showChild("PCEModel"), KBase::PCEModelNames); auto stmScen = enumFromName<StateTransMode>(showChild("StateTransitions"), KBase::StateTransModeNames); auto bigRRangScen = enumFromName<BigRRange>(showChild("BigRRange"), KBase::BigRRangeNames); auto bigRAdjScen = enumFromName<BigRAdjust>(showChild("BigRAdjust"), KBase::BigRAdjustNames); auto tpcScen = enumFromName<ThirdPartyCommit>(showChild("ThirdPartyCommit"), KBase::ThirdPartyCommitNames); auto ivbScen = enumFromName<InterVecBrgn>(showChild("InterVecBrgn"), InterVecBrgnNames); auto bModScen = enumFromName<SMPBargnModel>(showChild("BargnModel"), SMPBargnModelNames); cout << "Setting SMPModel parameters from XML scenario ..." << endl << flush; smp->vpm = vpmScen; smp->vrCltn = vrScen; smp->pcem = pcemScen; smp->stm = stmScen; smp->bigRRng = bigRRangScen; smp->bigRAdj = bigRAdjScen; smp->tpCommit = tpcScen; smp->ivBrgn = ivbScen; smp->brgnMod = bModScen; // IF we have an SMPModel, try to read all the actors into it try { unsigned int na = 0; XMLElement* actorsEl = scenEl->FirstChildElement("Actors"); assert(nullptr != actorsEl); XMLElement* aEl = actorsEl->FirstChildElement("Actor"); assert(nullptr != aEl); // has to be at least one while (nullptr != aEl) { const char* aName = aEl->FirstChildElement("name")->GetText(); const char* aDesc = aEl->FirstChildElement("description")->GetText(); double cap = 0.0; // another impossible value aEl->FirstChildElement("capability")->QueryDoubleText(&cap); assert(0.0 < cap); auto ri = new SMPActor(aName, aDesc); ri->sCap = cap; ri->vr = vrScen; smp->addActor(ri); // move to the next, if any na++; aEl = aEl->NextSiblingElement("Actor"); } printf("Found %u actors \n", na); assert(minNumActor <= na); assert(na <= maxNumActor); } catch (...) { throw (KException("SMPModel::readXML: Error reading Actors data")); } } } catch (const KException& ke) { cout << "Caught KException in SMPModel::readXML: " << ke.msg << endl << flush; } catch (...) { cout << "Caught unidentified exception in SMPModel::readXML" << endl << flush; } cout << "End SMPModel::readXML of " << fName << endl; assert (smp != nullptr); return smp; } // end of readXML }; // end of namespace // -------------------------------------------- // Copyright KAPSARC. Open source MIT License. // --------------------------------------------
[ "arunsathvik.n@gmail.com" ]
arunsathvik.n@gmail.com
a7f2c7e44e2e50bd13a542dcd684c725d7c8038d
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/FingerSuite/FingerNotification/NotifWindow.h
99e0fd3fae9b4308ff5304c5642459ed8eeeeaff
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
12,364
h
// WTLApp1View.h : interface of the CWTLApp1View class // ///////////////////////////////////////////////////////////////////////////// #pragma once #include "InterceptEngine.h" #include <initguid.h> //#include <piedocvw.h> #include <webvw.h> #define IDT_TIMER_MENU_ANIMATION 10110 #define TMR_MENU_ANIMATION 10 #define BORDER_WIDTH 10 #define UM_STARTANIM WM_USER + 1 #define UM_MINIMIZE WM_USER + 2 #define IDC_HTMLVIEW 10 //#define CUSTOM_CSS _T("INPUT[type='button'] { BORDER-RIGHT: #7b8194 1px solid; PADDING-RIGHT: 4px; BACKGROUND-POSITION: left bottom; BORDER-TOP: #a5a9b6 1px solid; PADDING-LEFT: 4px; FONT-WEIGHT: bold; FONT-SIZE: 9pt! important; BACKGROUND-IMAGE: url(btn_background.gif); PADDING-BOTTOM: 4px; MARGIN: 2px; VERTICAL-ALIGN: middle; BORDER-LEFT: #a5a9b6 1px solid; COLOR: #586073! important; LINE-HEIGHT: 20px; PADDING-TOP: 4px; BORDER-BOTTOM: #7b8194 1px solid; BACKGROUND-REPEAT: repeat-x; FONT-FAMILY: Tahoma; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #ffffff; TEXT-ALIGN: center; TEXT-DECORATION: none }") #define CUSTOM_CSS _T("INPUT[type='button'] { BORDER: none; PADDING-RIGHT: 4px; BACKGROUND-POSITION: left bottom; PADDING-LEFT: 4px; FONT-WEIGHT: bold; FONT-SIZE: 9pt! important; BACKGROUND-IMAGE: url(fngrnotif_btn_bkg.gif); PADDING-BOTTOM: 4px; MARGIN: 2px; VERTICAL-ALIGN: middle; COLOR: #000000! important; LINE-HEIGHT: 20px; PADDING-TOP: 4px; BACKGROUND-REPEAT: repeat-x; FONT-FAMILY: Tahoma; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #ffffff; TEXT-ALIGN: center; TEXT-DECORATION: none }") template <class T> class CNotifWindow : public CWindowImpl<T, CWindow, CControlWinTraits> { public: DECLARE_WND_CLASS(NULL) CNotifWindow () { } BOOL PreTranslateMessage(MSG* pMsg) { pMsg; return FALSE; } void SetScaleFactor(int value) { m_scaleFactor = value; } int GetScaleFactor() { return m_scaleFactor; } void Show() { ModifyShape(); StartAnimation(); } BOOL SetNotification(LPNOTIFICATIONINFO pData) { m_pInfo = pData; return TRUE; } void DoPaint(CBufferedPaintDC /*dc*/) { // must be implemented in a derived class ATLASSERT(FALSE); } BEGIN_MSG_MAP(CNotifWindow) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground) MESSAGE_HANDLER(WM_TIMER, OnTimer) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(UM_STARTANIM, OnStartAnim) //MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) //MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp) //MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown) FORWARD_NOTIFICATIONS() END_MSG_MAP() LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { ModifyTopShape(); if (m_fCaption != NULL) { LOGFONT lf; m_fCaption.GetLogFont(&lf); lf.lfHeight += 7 * m_scaleFactor; m_fCalendar.CreateFontIndirect(&lf); } return 0; } LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { return 0; } LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return 1; } LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { RECT rc; GetClientRect(&rc); CBufferedPaintDC dc(m_hWnd, 0); RECT rcHead; CopyRect(&rcHead, &rc); rcHead.bottom = m_imgHeader.GetHeight(); m_imgHeader.Draw(dc, rcHead); // draw title dc.SetBkMode(TRANSPARENT); dc.SetTextColor(m_clCaptionText); CFont oldFont = dc.SelectFont(m_fCaption); UINT uFormat = DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS; if (m_pInfo->grfFlagsOriginal & SHNF_TITLETIME) { WCHAR szTitle[256]; WCHAR szTime[50]; ::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL, NULL, szTime, 12); wsprintf(szTitle, L"%s | %s", szTime, m_pInfo->nd.pszTitle); rcHead.left += m_imgCalendar.GetWidth(); dc.DrawText(szTitle, -1, &rcHead, uFormat); // draw icon calendar WCHAR szMonth[50]; WCHAR szDay[50]; ::GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, L"MMM", szMonth, 50); ::GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, L"d", szDay, 50); m_imgCalendar.Draw(dc); RECT rcCal; SetRect(&rcCal, 0, 0, m_imgCalendar.GetWidth(), 10 * m_scaleFactor); CFont oldCalFont = dc.SelectFont(m_fCalendar); dc.DrawText(szMonth, -1, &rcCal, DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS); dc.SelectFont(oldCalFont); SetRect(&rcCal, 0, 0, m_imgCalendar.GetWidth(), m_imgCalendar.GetHeight() - 5 * m_scaleFactor); dc.SetTextColor(RGB(0,0,0)); dc.DrawText(szDay, -1, &rcCal, DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS); } else dc.DrawText(m_pInfo->nd.pszTitle, -1, &rcHead, uFormat); dc.SelectFont(oldFont); bHandled = FALSE; return 0; } LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { if (wParam == IDT_TIMER_MENU_ANIMATION) { m_iStep = m_iStep / 2; RECT animRect; CopyRect(&animRect, &m_animRect); animRect.top = animRect.top + m_iStep; MoveWindow(&animRect, TRUE); if (m_iStep == 0) { KillTimer(IDT_TIMER_MENU_ANIMATION); m_bAnimating = FALSE; m_iStep = 0; } bHandled = TRUE; return 0; } bHandled = FALSE; return 0; } LRESULT OnStartAnim(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { ModifyShape(); StartAnimation(); return 0; } void ModifyTopShape() { int nUsedRects = 3 * m_scaleFactor; m_heightHrgnTop = nUsedRects; if (m_hrgnTop != NULL) { DeleteObject(m_hrgnTop); m_hrgnTop = NULL; } RECT rcParent; GetParent().GetClientRect(&rcParent); int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor; RGNDATA *pRgnData; RECT *pRect; DWORD dwTemp = sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT); pRgnData = (RGNDATA*)malloc(dwTemp); pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER); pRgnData->rdh.iType = RDH_RECTANGLES; pRgnData->rdh.nCount = nUsedRects; pRgnData->rdh.nRgnSize = 0; pRgnData->rdh.rcBound.left = pRgnData->rdh.rcBound.top = 0; pRgnData->rdh.rcBound.right = iWidth; pRgnData->rdh.rcBound.bottom = nUsedRects; if (nUsedRects == 3) { // 1st pRect = &(((RECT *)&pRgnData->Buffer)[0]); pRect->top = 0; pRect->bottom = 1; pRect->left = 2; pRect->right = iWidth - 2; // 2nd pRect = &(((RECT *)&pRgnData->Buffer)[1]); pRect->top = 1; pRect->bottom = 2; pRect->left = 1; pRect->right = iWidth - 1; // 3rd pRect = &(((RECT *)&pRgnData->Buffer)[2]); pRect->top = 2; pRect->bottom = 3; pRect->left = 0; pRect->right = iWidth; } else if (nUsedRects == 6) { // 1st pRect = &(((RECT *)&pRgnData->Buffer)[0]); pRect->top = 0; pRect->bottom = 1; pRect->left = 5; pRect->right = iWidth - 5; // 2nd pRect = &(((RECT *)&pRgnData->Buffer)[1]); pRect->top = 1; pRect->bottom = 2; pRect->left = 3; pRect->right = iWidth - 3; // 3rd pRect = &(((RECT *)&pRgnData->Buffer)[2]); pRect->top = 2; pRect->bottom = 3; pRect->left = 2; pRect->right = iWidth - 2; // 4th pRect = &(((RECT *)&pRgnData->Buffer)[3]); pRect->top = 3; pRect->bottom = 4; pRect->left = 1; pRect->right = iWidth - 1; // 5th pRect = &(((RECT *)&pRgnData->Buffer)[4]); pRect->top = 4; pRect->bottom = 5; pRect->left = 1; pRect->right = iWidth - 1; // 6th pRect = &(((RECT *)&pRgnData->Buffer)[5]); pRect->top = 5; pRect->bottom = 6; pRect->left = 0; pRect->right = iWidth; } m_hrgnTop = ExtCreateRegion(NULL, dwTemp, pRgnData); free(pRgnData); } void AddStyle() { } void SubmitForm() { // must be implemented in a derived class ATLASSERT(FALSE); } public: RECT m_animRect; BOOL m_bAnimating; int m_iStep; int m_scaleFactor; int m_height; BOOL m_bMouseIsDown; HRGN m_hrgnTop; int m_heightHrgnTop; int m_iBodyHeight; NOTIFICATIONINFO* m_pInfo; COLORREF m_clCaptionText; CFontHandle m_fCaption; CFontHandle m_fCalendar; CxImage m_imgCalendar; CxImage m_imgHeader; BOOL m_bEnableAnimation; void ModifyShape() { m_height = m_iBodyHeight + m_imgHeader.GetHeight(); RECT rcParent; GetParent().GetClientRect(&rcParent); int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor; HRGN hrgnBottom = ::CreateRectRgn(0, 0, iWidth, m_height - m_heightHrgnTop); ::OffsetRgn(hrgnBottom, 0, m_heightHrgnTop); CombineRgn(hrgnBottom, m_hrgnTop, hrgnBottom, RGN_OR); SetWindowRgn(hrgnBottom, FALSE); } void StartAnimation() { int m_itemHeight = 5 * m_scaleFactor; // window position m_bAnimating = (m_bEnableAnimation) ? TRUE : FALSE; m_iStep = (m_bEnableAnimation) ? m_itemHeight / 3 : 0; RECT rcParent; GetParent().GetClientRect(&rcParent); m_animRect.left = BORDER_WIDTH * m_scaleFactor; m_animRect.right = rcParent.right - BORDER_WIDTH * m_scaleFactor; m_animRect.top = rcParent.bottom - m_height; m_animRect.bottom = rcParent.bottom; RECT animRect; CopyRect(&animRect, &m_animRect); animRect.top = animRect.top + m_iStep; MoveWindow(&animRect, TRUE); if (m_bEnableAnimation) SetTimer(IDT_TIMER_MENU_ANIMATION, TMR_MENU_ANIMATION); } }; class CHTMLNotifWindow : public CNotifWindow<CHTMLNotifWindow> { public: DECLARE_WND_CLASS(NULL) typedef CNotifWindow<CHTMLNotifWindow> Super; CHtmlCtrl m_html; BOOL SetNotification(LPNOTIFICATIONINFO pData) { Super::SetNotification(pData); m_html.Clear(); m_html.AddStyle(CUSTOM_CSS); RECT rcParent; GetParent().GetClientRect(&rcParent); int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor; m_html.ResizeClient(iWidth, 0); m_html.SendMessage(WM_SETTEXT, 0, (LPARAM)(LPCTSTR)_T("")); m_html.AddHTML(m_pInfo->nd.pszHTML); m_html.EndOfSource(); m_iBodyHeight = m_html.GetLayoutHeight() + 25 * m_scaleFactor; return TRUE; } void SubmitForm() { IDispatch* pDisp = NULL; m_html.GetDocumentDispatch(&pDisp); IPIEHTMLDocument *pHTMLDocument = NULL; HRESULT hr = pDisp->QueryInterface(IID_IPIEHTMLDocument, (void**)&pHTMLDocument); if (FAILED(hr)) { if (hr == E_NOINTERFACE) LOG(L"Interface doesn't exist\n"); if (hr == E_NOTIMPL) LOG(L"Queryinterface not implemented\n"); return; } IPIEHTMLElementCollection *pElementCollection = NULL; if ( pHTMLDocument->get_forms ( &pElementCollection ) == S_OK ) { if (pElementCollection != NULL) { long celem = 0; if ( pElementCollection->get_length( &celem ) == S_OK ) { for ( long i = 0; i < celem; i++ ) { VARIANT vtIndex; vtIndex.vt = VT_I4; vtIndex.lVal = i; IDispatch* pItem = NULL; if( pElementCollection->item( vtIndex, vtIndex, (IDispatch**)&pItem ) == S_OK ) { IPIEHTMLFormElement* form = NULL; if( pItem->QueryInterface(__uuidof(IPIEHTMLFormElement), (void**)&form ) == S_OK ) { form->put_method((BSTR)L"get"); hr = form->submit(); LOG(L"Tutto OK\n"); } } } } } } } BEGIN_MSG_MAP(CHTMLNotifWindow) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(UM_STARTANIM, OnStartAnim) CHAIN_MSG_MAP(Super) END_MSG_MAP() LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { // html control InitHTMLControl(ModuleHelper::GetModuleInstance()); m_html.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, IDC_HTMLVIEW); m_html.SetFocus(); m_html.SendMessage(WM_SETTEXT, 0, (LPARAM)(LPCTSTR)_T("")); bHandled = FALSE; return 0; } LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { RECT rc; GetClientRect(&rc); rc.top += m_imgHeader.GetHeight(); m_html.SetWindowPos(0, &rc, SWP_NOZORDER); bHandled = FALSE; return 0; } };
[ "jtxuee@gmail.com@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
jtxuee@gmail.com@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d
7e31d221bf054101cd2a1ff5662d5b75f2466a47
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/08_997_15.cpp
cf89f3794d2846834c0b96b05f849e13a04c7922
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
cpp
import java.io.*; import java.util.*; class A { public static void main (String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("A-small-attempt0.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out"))); int N = Integer.parseInt(f.readLine()); for(int kas=1; kas<=N; kas++){ StringTokenizer st = new StringTokenizer(f.readLine()); int P = Integer.parseInt(st.nextToken()); int K = Integer.parseInt(st.nextToken()); int L = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); int letter[] = new int[L]; for(int i=0; i<L; i++){ letter[i] = Integer.parseInt(st.nextToken()); //System.out.println(letter[i]); } Arrays.sort(letter); /* for(int i=0; i<L; i++){ System.out.print(letter[i]+" "); } System.out.println();*/ int nums[] = new int[K]; for(int j=0; j<K; j++){ nums[j] = 0; } int res=0; boolean fail = false; for(int i=L-1; i>=0; i--){ int min = P+1; int index=0; for(int j=0; j<K; j++){ if(min>nums[j]){ min = nums[j]; index = j; } } if(nums[index] < P){ nums[index]++; res += letter[i]*nums[index]; } else { fail = true; break; } //System.out.print(letter[i]+" "); } if(!fail) out.println("Case #"+kas+": "+res); else out.println("Case #"+kas+": Impossible"); } out.close(); System.exit(0); } }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
d78472a9baeed18ac284d4b6f5720fc58a164eb1
c0dd61d7b2a8bff0f57f6a89e10d9fe38cd15839
/a4/src/util/glviewer.cpp
be8a6b60b13bd23f824dd6ba7d752c6c65ffaf32
[]
no_license
janukobytsch/hpi-cg1
9a0367412b3583e11779df739b3020ce957b6d78
95bd4cd8c4309e1257e69812148f79cf75273ddd
refs/heads/master
2016-09-06T03:35:47.105022
2015-07-21T00:19:17
2015-07-21T00:19:17
34,412,343
2
0
null
null
null
null
ISO-8859-2
C++
false
false
1,561
cpp
// ====================================== // 3D Computergrafik // moodle.hpi3d.de // ====================================== // // Sommersemester 2015 - Aufgabenblatt 2 // - Aufgabe 6 // // Musterlösung // // ====================================== #include "glviewer.h" #include <iostream> #include <QKeyEvent> #include <QMatrix4x4> #include <QTimer> #include <QBoxLayout> #include "openglfunctions.h" #include "canvas.h" #include "abstractpainter.h" GLViewer::GLViewer(AbstractPainter *painter, QWidget *parent) : QWidget(parent) , m_painter(painter) , m_canvas(0) { setup(); } GLViewer::~GLViewer() { m_canvas->setPainter(0); delete m_painter; delete m_canvas; } void GLViewer::setup() { QSurfaceFormat format; format.setVersion(3, 2); format.setProfile(QSurfaceFormat::CoreProfile); format.setDepthBufferSize(16); m_canvas = new Canvas(format); m_canvas->setContinuousRepaint(true, 0); m_canvas->setSwapInterval(Canvas::VerticalSyncronization); m_canvas->setPainter(m_painter); QWidget *widget = QWidget::createWindowContainer(m_canvas); widget->setMinimumSize(1, 1); widget->setAutoFillBackground(false); // Important for overdraw, not occluding the scene. widget->setFocusPolicy(Qt::TabFocus); widget->setParent(this); QHBoxLayout *layout = new QHBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(widget); setLayout(layout); show(); }
[ "janusch.jacoby@student.hpi.uni-potsdam.de" ]
janusch.jacoby@student.hpi.uni-potsdam.de
0358f20275b68879557f4c2b29fb89155955d483
083100943aa21e05d2eb0ad745349331dd35239a
/aws-cpp-sdk-redshift/source/model/DescribeClusterParametersResult.cpp
ad1f960b641794181dd4a5e69b89dfd9cd84d073
[ "JSON", "MIT", "Apache-2.0" ]
permissive
bmildner/aws-sdk-cpp
d853faf39ab001b2878de57aa7ba132579d1dcd2
983be395fdff4ec944b3bcfcd6ead6b4510b2991
refs/heads/master
2021-01-15T16:52:31.496867
2015-09-10T06:57:18
2015-09-10T06:57:18
41,954,994
1
0
null
2015-09-05T08:57:22
2015-09-05T08:57:22
null
UTF-8
C++
false
false
2,206
cpp
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/redshift/model/DescribeClusterParametersResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <utility> using namespace Aws::Redshift::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws; DescribeClusterParametersResult::DescribeClusterParametersResult() { } DescribeClusterParametersResult::DescribeClusterParametersResult(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DescribeClusterParametersResult& DescribeClusterParametersResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode.FirstChild("DescribeClusterParametersResult"); if(!resultNode.IsNull()) { XmlNode parametersNode = resultNode.FirstChild("Parameters"); if(!parametersNode.IsNull()) { XmlNode parametersMember = parametersNode.FirstChild("Parameter"); while(!parametersMember.IsNull()) { m_parameters.push_back(parametersMember); parametersMember = parametersMember.NextNode("Parameter"); } } XmlNode markerNode = resultNode.FirstChild("Marker"); if(markerNode.IsNull()) { markerNode = resultNode; } if(!markerNode.IsNull()) { m_marker = StringUtils::Trim(markerNode.GetText().c_str()); } } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
d06cd247e4008602226d27064bb92dc1772161ad
fec12c24565931c5a2b9928e7428f58df80a415f
/ax_jpeg/bellerophon/bellerophon_functions.cpp
37afeb206a0a8e349b81d0042fea4adf7feda9f6
[]
no_license
nnkhoa/IIDEAA-Bench
d9342baffd905b0917e4b54ec8082c633ea2a9f1
06f00eea378907bf3fd1e09e2afe7b6b4efb7e1e
refs/heads/master
2021-08-19T03:17:34.202198
2018-09-13T11:03:38
2018-09-13T11:03:38
134,674,196
0
0
null
null
null
null
UTF-8
C++
false
false
4,200
cpp
#include <iostream> #include <string.h> #include <math.h> #include <stdio.h> #include <setjmp.h> #include "vpa.h" #include "jpeg.h" #include "rgbimage.h" extern "C" { #include "jpeglib.h" } // #include "jpegloader.h" struct JpegInfo{ char* buffer; int height; int width; }; struct ErrorManager { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; typedef struct ErrorManager * my_error_ptr; void errorHandler(j_common_ptr info) { my_error_ptr myerr = (my_error_ptr) info->err; (*info->err->output_message) (info); longjmp(myerr->setjmp_buffer, 1); } JpegInfo* loadJpeg(::std::string filename) { struct ErrorManager jerr; struct jpeg_decompress_struct info; FILE * infile; JSAMPARRAY buffer; int rowStride; if((infile = fopen(filename.c_str(), "rb")) == NULL) { ::std::cerr << "NULL file\n"; return NULL; } info.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = errorHandler; jpeg_create_decompress(&info); jpeg_stdio_src(&info, infile); jpeg_read_header(&info, TRUE); jpeg_start_decompress(&info); rowStride = info.output_width * info.output_components; int bufferSize = info.output_height * rowStride; unsigned char *imageBuffer = new unsigned char[bufferSize](); buffer = (*info.mem->alloc_sarray) ((j_common_ptr) &info, JPOOL_IMAGE, rowStride, 1); while (info.output_scanline < info.output_height) { jpeg_read_scanlines(&info, buffer, 1); memcpy(&imageBuffer[(info.output_scanline - 1) * rowStride], *buffer, rowStride); } jpeg_finish_decompress(&info); jpeg_destroy_decompress(&info); fclose(infile); JpegInfo *jpegInfo = new JpegInfo(); jpegInfo->buffer = (char*)imageBuffer; jpegInfo->width = info.output_width; jpegInfo->height = info.output_height; return jpegInfo; } //#include "fap.h" // bool vpa_n::VPA::UPCASTING = false; const char* inputPath = "/opt/ax_jpeg/test.data/input/10.rgb"; const char* axPath = "/opt/ax_jpeg/src/build/ax.jpg"; const char* oraclePath = "/opt/ax_jpeg/src/build/oracle.jpg"; //double calDistance(RgbPixel p, RgbPixel q) { // float r = 0.0; // // r = pow(p.r - q.r, 2) + pow(p.g - q.g, 2) + pow(p.b - q.b, 2); // // return sqrt(r); //} void doAxCompute() { ::std::cout << "Do Ax Compute\n"; if (jpegConversion(inputPath, axPath) != 0) { ::std::cerr << "Error Executing Approximate Version of the program\n"; exit(-1); } ::std::cout << inputPath << " " << axPath << "\n"; } void loadImageFile(const char* imagePath, JpegInfo **image) { ::std::string pathString = imagePath; *image = loadJpeg(pathString); // std::cout << *image->width << "x" << *image->height << std::endl; if (image == NULL){ ::std::cout << "Cannot open file!\n"; exit(-1); } } double calculateRMSE(JpegInfo *oracle, JpegInfo *ax){ int imageWidth = oracle->width; int imageHeight = oracle->height; double sumSquareError = 0; double MSE = 0; double diff = 0; for(int i = 0; i < imageWidth; i++) { for (int j = 0; j < imageHeight; j++) { diff = abs(oracle->buffer[i*imageWidth + j] - ax->buffer[i*imageWidth + j]); sumSquareError += pow(diff, 2); } } ::std::cout << imageHeight << " " << imageWidth << "\n"; return sqrt((double)sumSquareError/(imageWidth*imageHeight)); } extern "C" double BELLERO_getError() { //execute Ax computation doAxCompute(); JpegInfo *oracleImage = new JpegInfo(); JpegInfo *axImage = new JpegInfo(); //load image ::std::cout << "Opening Oracle Image file...\n"; loadImageFile(oraclePath, &oracleImage); ::std::cout << "Opening Ax Image file...\n"; loadImageFile(axPath, &axImage); //return MSE return calculateRMSE(oracleImage, axImage); } //extern fap::FloatPrecTy OP_0, OP_1, OP_2, OP_3, OP_4, OP_5; // //extern "C" double BELLERO_Reward() //{ // double rew = 0; // //// MantType mant; // int grade[6]; // // grade[0] = 23 - OP_0.mant_size; // grade[1] = 23 - OP_1.mant_size; // grade[2] = 23 - OP_2.mant_size; // grade[3] = 23 - OP_3.mant_size; // grade[4] = 23 - OP_4.mant_size; // grade[5] = 23 - OP_5.mant_size; // // rew = (double)2*grade[0] + 2*pow(grade[1],2) + 2*pow(grade[3],2) + 2*pow(grade[4],2) + 2*pow(grade[5],2); //// FloatPrecTy prec = OP_1.getPrec(); // //// cout << prec.mant_size; // // return rew; //}
[ "n.nhukhoa2209@gmail.com" ]
n.nhukhoa2209@gmail.com
c29a3578ee0899e599392dc1d940c9b6e9b94823
6ebd6c3064f618e57fd8cac3979b59a66586d4b8
/serverbase/stdConns.h
28c6902512efdca832accab218b60eee8c6244ca
[ "MIT" ]
permissive
jimfinnis/stumpy2
f322151b0e01df6e22ea1504527e0478e950aad3
4011e42b7082f847396816b1b5aee46d7ce93b2b
refs/heads/master
2021-01-17T01:08:21.980984
2020-06-11T13:48:52
2020-06-11T13:48:52
58,866,576
0
0
null
null
null
null
UTF-8
C++
false
false
2,282
h
/** * @file stdConns.h * @brief Standard connection types (flow,int,float) * */ #ifndef __STDCONNS_H #define __STDCONNS_H #include "model.h" #include "instances.h" /// register the standard connection types. void regStdCons(); class FlowCon : public ConnectionType { public: FlowCon() : ConnectionType(0,"flow",0x000000ff,FLOAT){} void getInput(ComponentInstance *ci,int in){ ci->getInput(in); } void setOutput(ComponentInstance *ci,int o){ ConnectionValue& v = ci->output(o); v.t = this; } }; extern FlowCon *tFlow; class FloatCon : public ConnectionType { public: FloatCon() : ConnectionType(1,"float",0x0000ffff,FLOAT){} void setOutput(ComponentInstance *ci,int o,float f){ ConnectionValue& v = ci->output(o); v.t = this; v.d.f = f; } float getInput(ComponentInstance *ci,int in){ ConnectionValue& v = ci->getInput(in); if(v.t == NULL)return 0; if(v.t != this)throw Exception(""). set("input %s:%d is %s, not %s",ci->component->type->name, in,v.t->name,name); return v.d.f; } }; extern FloatCon *tFloat; class IntCon : public ConnectionType { public: IntCon() : ConnectionType(2,"int",0x009000ff,INT){} void setOutput(ComponentInstance *ci,int o,int i){ ConnectionValue& v = ci->output(o); v.t = this; v.d.i = i; } int getInput(ComponentInstance *ci,int in){ ConnectionValue& v = ci->getInput(in); if(v.t == NULL)return 0; if(v.t != this)throw Exception(""). set("input %s:%d is %s, not %s",ci->component->type->name, in,v.t->name,name); return v.d.i; } }; extern IntCon *tInt; class AnyCon : public ConnectionType { public: // type ID==25 will not be checked in client for connection // type match. AnyCon() : ConnectionType(25,"any",0xa0a000ff,ANY){} void setOutput(ComponentInstance *ci,int o,ConnectionValue &v){ ConnectionValue& vv = ci->output(o); vv = v; } ConnectionValue& getInput(ComponentInstance *ci,int in){ ConnectionValue& v = ci->getInput(in); return v; } }; extern AnyCon *tAny; #endif /* __STDCONNS_H */
[ "jim.finnis@gmail.com" ]
jim.finnis@gmail.com
fabd28e5c967b550803e84178777d3fbec51cdf0
8448367b34b191f3fa9c100075775dc5a5883b9c
/25.09/матрица смежности - список ребер.cpp
a3f2a0fc27db78b983fc9797390f2e50cc4c8d43
[]
no_license
MargaritaArofikina/11class
84d5291b26b6f1e6b1a6a66df946a2b58c264fb3
be86d46614c48f0f202fddb2e9a8b6fc17b97c1f
refs/heads/master
2020-07-30T23:08:05.022440
2019-11-04T17:52:31
2019-11-04T17:52:31
210,391,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
//из матрицы смежности в список ребер #include <iostream> using namespace std; void Msm_to_Sreb(int** S, int** M, int n) { int p = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i < j) && M[i][j] == 1) { S[p][0] = i + 1; S[p][1] = j + 1; p++; } } } } int main() { int n, k; //количество вершин и ребер cin >> n >> k; int** Msm = new int*[n]; for (int i = 0; i < n; i++) { Msm[i] = new int[n]; for (int j = 0; j < n; j++) { cin >> Msm[i][j]; } } int** Sreb = new int*[k]; for (int i = 0; i < k; i++) { Sreb[i] = new int[2]; for (int j = 0; j < 2; j++) { Sreb[i][j] = 0; } } Msm_to_Sreb(Sreb, Msm, n); for (int i = 0; i < k; i++) { for (int j = 0; j < 2; j++) { cout << Sreb[i][j] << " "; } cout << endl; } return 0; }
[ "noreply@github.com" ]
MargaritaArofikina.noreply@github.com
bd884e7339a2ba21ef34572f76bb353a3093e871
a3e7088f055ba6630811109725eacf2c848beb74
/GameGuru IDE/Thread.h
01ca149188d0440916f2bc956b689029ea3a7fc7
[]
no_license
TheGameCreators/GameGuruRepo
36482fae506c248430028257b4c06680a9530e18
a1ea066e6b57c02b067bdaad4db22399095aa710
refs/heads/master
2023-07-08T03:17:06.712299
2023-06-19T11:45:06
2023-06-19T11:45:06
117,701,801
158
62
null
2023-06-29T05:57:55
2018-01-16T15:29:09
C++
UTF-8
C++
false
false
967
h
#ifndef THREAD_H #define THREAD_H #include <windows.h> #include <process.h> class Thread { private: //to avoid casting from MyThread* to void* to Thread* struct sThisStruct { Thread* pThis; }; HANDLE pThread; UINT iThreadID; static unsigned __stdcall EntryPoint( void *pParams ) { sThisStruct *pTS = (sThisStruct*) pParams; Thread* pThis = pTS->pThis; delete pTS; return pThis->Run(); } protected: virtual unsigned Run( ) = 0; public: Thread( ) { pThread = 0; iThreadID = 0; } virtual ~Thread( ) { CloseHandle( pThread ); } void Start( ) { sThisStruct *pTS = new sThisStruct(); pTS->pThis = this; pThread = (HANDLE)_beginthreadex( NULL, 0, EntryPoint, (void*) pTS, 0, &iThreadID ); } void Join( ) { WaitForSingleObject( pThread, INFINITE ); } void Terminate( ) { if ( pThread ) { TerminateThread( pThread, 0 ); CloseHandle( pThread ); } pThread = 0; iThreadID = 0; } }; #endif
[ "leebambertgc@gmail.com" ]
leebambertgc@gmail.com
0676b0f55afc54627515b785966a0488f8bd8551
88038a08a1ee13b1c63f10b281b6a47226b79d75
/MavViz/GLShader.h
dcb64d0cdfab15d84c2da932a8f990d0eb1f19cd
[]
no_license
jasonmeverett/MavViz
1d07761f84853c979fd97b8d5734d7163ef97f44
4270e31a1baecfa86eef6d8d27952192ba10a4d4
refs/heads/master
2022-03-22T16:34:53.890301
2018-09-28T20:23:44
2018-09-28T20:23:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
839
h
#pragma once #include "MVDataTypes.h" namespace MavViz { namespace Graphics { class Shader { public: GLchar* GetLog(); int Configure(int shaderType, GLchar* sourceFile); void Delete(); int GetID() { return ID; } protected: int shaderType; int ID; GLchar* source; GLchar* sourceFile; }; class ShaderProg { public: ShaderProg() {}; ShaderProg(GLchar * vertShaderSource, GLchar * fragShaderSource); int GetID() { return ID; } int Link(); int Link(Shader vertShader, Shader fragShader); int Link(GLchar * vertShaderSource, GLchar * fragShaderSource); void Use(); Shader* GetVertShader() { return &vertexShader; } Shader* GetFragShader() { return &fragmentShader; } protected: int ID; int success; Shader vertexShader; Shader fragmentShader; }; } }
[ "jme5297@psu.edu" ]
jme5297@psu.edu
d0498b117c9ce7c621369ae44c01804a5dcb72e9
6523e5bc579d46fe937b563e169e646e1eafb920
/My_Arduino_FSM.ino
db02751fee4e1a8c79e1124d4918fd9083fcab3d
[]
no_license
savannahmccoy/LED-FSM-with-Push-Button
cf21b09ecba6f8e7f35f13555c1074a0b77f0f27
8a75eb6a5838be36de219f5a2aba53e7d2cb0c4a
refs/heads/master
2021-05-07T09:39:09.062271
2017-11-09T21:52:56
2017-11-09T21:52:56
109,550,441
1
0
null
null
null
null
UTF-8
C++
false
false
1,645
ino
/* Modified FSM example code - Push Button */ const int buttonPin = 2; const int ledPin1 = 13; const int ledPin2 = 12; const int ledPin3 = 11; int buttonPushCounter = 0; // counter for the number of button presses int buttonState = 0; // current state of the button int lastButtonState = 0; // previous state of the button void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); Serial.begin(9600); } void loop() { buttonState = digitalRead(buttonPin); // read the pushbutton input pin: if (buttonState != lastButtonState) { // compare the buttonState to its previous state // if the state has changed, increment the counter if (buttonState == HIGH) { buttonPushCounter++; Serial.println("on"); Serial.print("number of button pushes: "); Serial.println(buttonPushCounter); } else { Serial.println("off"); } delay(50); // Delay a little bit to avoid bouncing } lastButtonState = buttonState; // save the current state as the last state, for next time through the loop if (buttonPushCounter == 1) { digitalWrite(ledPin1, HIGH); digitalWrite(ledPin2, LOW); digitalWrite(ledPin3, LOW); } else if (buttonPushCounter == 2) { digitalWrite(ledPin2, HIGH); digitalWrite(ledPin1, LOW); digitalWrite(ledPin3, LOW); } else if (buttonPushCounter == 3) { digitalWrite(ledPin3, HIGH); digitalWrite(ledPin2, LOW); digitalWrite(ledPin1, LOW); } else { buttonPushCounter = 1; } }
[ "noreply@github.com" ]
savannahmccoy.noreply@github.com
dc2c75ca2236697fb7f0f6669e4cb8b73e1a24e1
30773b649ebd89ffadd16d30fd62740b77ca7865
/SDK/BP_FishingFish_Islehopper_05_Colour_03_Raven_parameters.h
4012543874df06abbb5df3dd8f983a0f8e8e4835
[]
no_license
The-Jani/Sot-SDK
7f2772fb5df421e02b8fec237248af407cb2540b
2a158a461c697cca8db67aa28ffe3e43677dcf11
refs/heads/main
2023-07-09T07:17:56.972569
2021-08-18T23:45:06
2021-08-18T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
621
h
#pragma once // Name: S, Version: 2.2.1 #include "../SDK.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function BP_FishingFish_Islehopper_05_Colour_03_Raven.BP_FishingFish_Islehopper_05_Colour_03_Raven_C.UserConstructionScript struct ABP_FishingFish_Islehopper_05_Colour_03_Raven_C_UserConstructionScript_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "ploszjanos9844@gmail.com" ]
ploszjanos9844@gmail.com
1961d5464f7df42125d4a0810154d184e67281bd
3b5557bcc8f90e5e7b5f9f717237de1963972f98
/SignmeDynamic/Feature2.cpp
d84d7b967bf19b826d5a5091b70e2bdfa49924a0
[]
no_license
jurocha-ms/SymbolMe
283a8d6bdb940abc2ff4277e09b2530bcdc1cc51
7010c9b10d67828e3a76ccac79eb4e2a29334e5d
refs/heads/master
2023-01-25T01:40:59.485732
2020-12-04T05:25:16
2020-12-04T05:25:16
318,032,930
0
0
null
null
null
null
UTF-8
C++
false
false
106
cpp
#include "pch.h" #include "Feature2.h" namespace Symbols { int Feature2() { return 2; } }
[ "julio.rocha@microsoft.com" ]
julio.rocha@microsoft.com
e4d6cc2a17ef1673aa31a81243f25cff66c07677
1809fda2c0e984717e130ac266fa33b0c3edcce7
/base/Senser.h
088bd5911bde150457ed58850c10fdcba856776a
[]
no_license
WangRong3/cocos2dx_game_Classes
9f08adc9e441deec3ee5e71e9ef15087e1b1aa2a
dbdf1691a06215e122817fc5734548d871e6aa1a
refs/heads/master
2021-01-12T10:42:32.708326
2016-11-02T13:50:33
2016-11-02T13:50:33
null
0
0
null
null
null
null
GB18030
C++
false
false
697
h
#ifndef _SENSER_H_ #define _SENSER_H_ #include "KnowledgePool.h" class Senser { public: Senser(){} virtual ~Senser(){} virtual void execute(){} void SetSenserMode(int interval, int count) { m_interval = interval; m_count = count; } int m_interval; //时间间隔 int m_count; //执行次数 }; class SenserWorld:public Senser { public: SenserWorld(){} virtual ~SenserWorld(){} virtual void execute() { return ; } void GetNearestRole(Role* role) { } }; class SenserManager { public: SenserManager(){} virtual ~SenserManager(){} void RegisteSenser(Senser*) {} void UnRegistSenser(Senser*) {} void Update() {} std::vector<Senser*> m_SManager; }; #endif
[ "wr000023@163.com" ]
wr000023@163.com
c5adb31fff865eb22ea9eec18cf785cacf870f9e
b9eed0d5df4aada9a98da8332e7df05c03326778
/src/week_2/formulas.cpp
83f1bb3e90cae82a6ca614ebbd6878bf4959a356
[]
no_license
dballesteros7/Algolab-HS13
2210ba4b466a525f67c6f49603fed6581a7f07c3
6206bbbb9dfdad69e294cdc90e94ce45751f0666
refs/heads/master
2020-12-30T10:36:39.960057
2014-07-31T08:36:19
2014-07-31T08:36:19
13,175,500
5
2
null
null
null
null
UTF-8
C++
false
false
1,836
cpp
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; void merge(int *a, int p, int q, int r, int *count, int max_value){ //cout << "Merging... " << "P: " << p << " Q: " << q << " R: " << r << "\n"; int *L = new int[q - p + 1 + 1]; int *R = new int[r - q + 1]; int i, j, k; for(i = 0; i < q - p + 1; i++){ L[i] = a[p + i]; } L[q - p + 1] = max_value; for(i = 0; i < r - q; i++){ R[i] = a[q + 1 + i]; } R[r - q] = max_value; j = 0; k = 0; for(i = p; i <= r; i++){ if(L[j] <= R[k]){ a[i] = L[j]; j++; } else{ a[i] = R[k]; if(j < (q - p + 1)){ int to_swap = (q - p + 1) - j; //cout << to_swap << "\n"; (*count) += to_swap; (*count) = (*count) % 10000; } k++; } } } void merge_sort(int *a, int p, int r, int *count, int max_value){ if(p < r){ int q = floor((p + r)/2); //cout << "Q: " << q << " P: " << p << " R: " << r << "\n"; merge_sort(a, p, q, count, max_value); merge_sort(a, q + 1, r, count, max_value); merge(a, p, q, r, count, max_value); } } int main(){ int *numbers; int t; int N; int i, j; int tmp; int count; int *count_pointer; cin >> t; for(i = 0; i < t; i++){ cin >> N; numbers = new int[N]; count = 0; count_pointer = &count; for(j = 0; j < N; j++){ cin >> tmp; numbers[j] = tmp; } merge_sort(numbers, 0, N - 1, count_pointer, N + 1); //for(j = 0; j < N; j++){ // cout << numbers[j] << "\n"; //} cout << count << "\n"; } return 0; }
[ "diegob@student.ethz.ch" ]
diegob@student.ethz.ch
d9975e6ba620a5b18338b98f45b88aa57ef0511f
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Source/Contrib/UserInterface/src/Event/OSGChangeListener.h
c1bf449f4d8372899811201bf376268a0765a3ae
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,627
h
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox UserInterface * * * * * * * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGCHANGELISTENER_H_ #define _OSGCHANGELISTENER_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGContribUserInterfaceDef.h" #include "OSGEventListener.h" #include "OSGChangeEvent.h" OSG_BEGIN_NAMESPACE class OSG_CONTRIBUSERINTERFACE_DLLMAPPING ChangeListener : public EventListener { /*========================= PUBLIC ===============================*/ public: virtual void stateChanged(const ChangeEventUnrecPtr e) = 0; }; typedef ChangeListener* ChangeListenerPtr; OSG_END_NAMESPACE #endif /* _OSGCHANGELISTENER_H_ */
[ "djkabala@gmail.com" ]
djkabala@gmail.com
63d3d089303aa4fcb84d0ba5cb6badf471a9164c
88ae8695987ada722184307301e221e1ba3cc2fa
/content/public/browser/webui_config_map.h
19777632921fc6e90587c0f27f9a76e96c688478
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
2,451
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_BROWSER_WEBUI_CONFIG_MAP_H_ #define CONTENT_PUBLIC_BROWSER_WEBUI_CONFIG_MAP_H_ #include <map> #include <memory> #include "content/common/content_export.h" namespace url { class Origin; } namespace content { class BrowserContext; class WebUIControllerFactory; class WebUIConfig; // Class that holds all WebUIConfigs for the browser. // // Embedders wishing to register WebUIConfigs should use // AddWebUIConfig and AddUntrustedWebUIConfig. // // Underneath it uses a WebUIControllerFactory to hook into the rest of the // WebUI infra. class CONTENT_EXPORT WebUIConfigMap { public: static WebUIConfigMap& GetInstance(); WebUIConfigMap(); WebUIConfigMap(const WebUIConfigMap&) = delete; WebUIConfigMap& operator=(const WebUIConfigMap&) = delete; ~WebUIConfigMap(); // Adds a chrome:// WebUIConfig. CHECKs if the WebUIConfig is for a // chrome-untrusted:// WebUIConfig. void AddWebUIConfig(std::unique_ptr<WebUIConfig> config); // Adds a chrome-untrusted:// WebUIConfig. CHECKs if the WebUIConfig is // for a chrome:// WebUIConfig. // // Although the scheme is included as part of the WebUIConfig, having // two separate methods for chrome:// and chrome-untrusted:// helps // readers tell what type of WebUIConfig is being added. void AddUntrustedWebUIConfig(std::unique_ptr<WebUIConfig> config); // Returns the WebUIConfig for |origin| if it's registered and the WebUI is // enabled. (WebUIs can be disabled based on the profile or feature flags.) WebUIConfig* GetConfig(BrowserContext* browser_context, const url::Origin& origin); // Removes and returns the WebUIConfig with |origin|. Returns nullptr if // there is no WebUIConfig with |origin|. std::unique_ptr<WebUIConfig> RemoveConfig(const url::Origin& origin); // Returns the size of the map, i.e. how many WebUIConfigs are registered. size_t GetSizeForTesting() { return configs_map_.size(); } private: void AddWebUIConfigImpl(std::unique_ptr<WebUIConfig> config); using WebUIConfigMapImpl = std::map<url::Origin, std::unique_ptr<WebUIConfig>>; WebUIConfigMapImpl configs_map_; std::unique_ptr<WebUIControllerFactory> webui_controller_factory_; }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_WEBUI_CONFIG_MAP_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
3f50326f1193c92d707f2fd3488ba6ab830fedc4
d02fcc1342a7c5a52ae328095038e514959c8813
/rcl/test/rcl/test_remap.cpp
894c3597794d9b142f44442d7ab56c5317d1bc36
[ "Apache-2.0" ]
permissive
yihongyishui/rcl
3228b953a7239c1a5d491cb42af609e6ce4ceabe
d41c923927850274f63aee1bde565d3a8266a7bd
refs/heads/master
2020-03-08T02:13:27.983506
2018-03-30T17:56:42
2018-03-30T17:56:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,803
cpp
// Copyright 2018 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include "rcl/rcl.h" #include "rcl/remap.h" #include "rcl/error_handling.h" #include "./arg_macros.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif class CLASSNAME (TestRemapFixture, RMW_IMPLEMENTATION) : public ::testing::Test { public: void SetUp() { } void TearDown() { } }; TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), global_namespace_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "__ns:=/foo/bar"); char * output = NULL; ret = rcl_remap_node_namespace( NULL, &global_arguments, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), nodename_prefix_namespace_remap) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "Node1:__ns:=/foo/bar", "Node2:__ns:=/this_one", "Node3:__ns:=/bar/foo"); { char * output = NULL; ret = rcl_remap_node_namespace( NULL, &global_arguments, "Node1", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_node_namespace( NULL, &global_arguments, "Node2", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/this_one", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_node_namespace( NULL, &global_arguments, "Node3", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/bar/foo", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_namespace_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name"); char * output = NULL; ret = rcl_remap_node_namespace( NULL, &global_arguments, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), local_namespace_replacement_before_global) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "__ns:=/global_args"); rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name", "__ns:=/local_args"); char * output = NULL; ret = rcl_remap_node_namespace( &local_arguments, &global_arguments, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/local_args", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_use_global_namespace_replacement) { rcl_ret_t ret; rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name"); char * output = NULL; ret = rcl_remap_node_namespace( &local_arguments, NULL, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), other_rules_before_namespace_rule) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "/foobar:=/foo/bar", "__ns:=/namespace", "__node:=new_name"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_node_namespace(NULL, &global_arguments, "NodeName", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/namespace", output); allocator.deallocate(output, allocator.state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), global_topic_name_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "/bar/foo:=/foo/bar"); { char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); ASSERT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/foo/bar", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), relative_topic_name_remap) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "foo:=bar"); char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/ns/foo", "NodeName", "/ns", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); ASSERT_STREQ("/ns/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), nodename_prefix_topic_remap) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "Node1:/foo:=/foo/bar", "Node2:/foo:=/this_one", "Node3:/foo:=/bar/foo"); { char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/foo", "Node1", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/foo", "Node2", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/this_one", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/foo", "Node3", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/bar/foo", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_use_global_topic_name_replacement) { rcl_ret_t ret; rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name"); char * output = NULL; ret = rcl_remap_topic_name( &local_arguments, NULL, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_topic_name_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name"); char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), local_topic_replacement_before_global) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "/bar/foo:=/foo/global_args"); rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name", "/bar/foo:=/foo/local_args"); char * output = NULL; ret = rcl_remap_topic_name( &local_arguments, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/local_args", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), other_rules_before_topic_rule) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "__ns:=/namespace", "__node:=remap_name", "/foobar:=/foo/bar"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_topic_name( NULL, &global_arguments, "/foobar", "NodeName", "/", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); allocator.deallocate(output, allocator.state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), global_service_name_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "/bar/foo:=/foo/bar"); { char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); ASSERT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/foobar", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), relative_service_name_remap) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "foo:=bar"); char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/ns/foo", "NodeName", "/ns", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); ASSERT_STREQ("/ns/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), nodename_prefix_service_remap) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "Node1:/foo:=/foo/bar", "Node2:/foo:=/this_one", "Node3:/foo:=/bar/foo"); { char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/foo", "Node1", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/foo", "Node2", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/this_one", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } { char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/foo", "Node3", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/bar/foo", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_use_global_service_name_replacement) { rcl_ret_t ret; rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name"); char * output = NULL; ret = rcl_remap_service_name( &local_arguments, NULL, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_service_name_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name"); char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), local_service_replacement_before_global) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "/bar/foo:=/foo/global_args"); rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name", "/bar/foo:=/foo/local_args"); char * output = NULL; ret = rcl_remap_service_name( &local_arguments, &global_arguments, "/bar/foo", "NodeName", "/", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/local_args", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), other_rules_before_service_rule) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "__ns:=/namespace", "__node:=remap_name", "/foobar:=/foo/bar"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_service_name( NULL, &global_arguments, "/foobar", "NodeName", "/", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("/foo/bar", output); allocator.deallocate(output, allocator.state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), global_nodename_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "__node:=globalname"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_node_name(NULL, &global_arguments, "NodeName", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("globalname", output); allocator.deallocate(output, allocator.state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_nodename_replacement) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name"); char * output = NULL; ret = rcl_remap_node_name(NULL, &global_arguments, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), local_nodename_replacement_before_global) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "__node:=global_name"); rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name", "__node:=local_name"); char * output = NULL; ret = rcl_remap_node_name( &local_arguments, &global_arguments, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("local_name", output); rcl_get_default_allocator().deallocate(output, rcl_get_default_allocator().state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), no_use_global_nodename_replacement) { rcl_ret_t ret; rcl_arguments_t local_arguments; SCOPE_ARGS(local_arguments, "process_name"); char * output = NULL; ret = rcl_remap_node_name( &local_arguments, NULL, "NodeName", rcl_get_default_allocator(), &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_EQ(NULL, output); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), use_first_nodename_rule) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS(global_arguments, "process_name", "__node:=firstname", "__node:=secondname"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_node_name(NULL, &global_arguments, "NodeName", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("firstname", output); allocator.deallocate(output, allocator.state); } TEST_F(CLASSNAME(TestRemapFixture, RMW_IMPLEMENTATION), other_rules_before_nodename_rule) { rcl_ret_t ret; rcl_arguments_t global_arguments; SCOPE_ARGS( global_arguments, "process_name", "/foobar:=/foo", "__ns:=/namespace", "__node:=remap_name"); rcl_allocator_t allocator = rcl_get_default_allocator(); char * output = NULL; ret = rcl_remap_node_name(NULL, &global_arguments, "NodeName", allocator, &output); EXPECT_EQ(RCL_RET_OK, ret); EXPECT_STREQ("remap_name", output); allocator.deallocate(output, allocator.state); }
[ "noreply@github.com" ]
yihongyishui.noreply@github.com
63380dd6654987ac3843e596d9a206b1f81e7e4a
e5be84112444150c890ab90573042dc9ae42b9d9
/src/services/common/AnnotationBinding.cpp
204e900e5746ab3dd0e6d0c6d69b69b03d13cb34
[ "BSD-3-Clause" ]
permissive
DavidPoliakoff/caliper_coverage
2f858c327a4b54929d62d18da20b7ad0cac064a2
d9d1129d6e083663cbb9e6b293da7f10ea06755e
refs/heads/master
2021-05-11T03:00:17.186955
2018-01-17T23:00:34
2018-01-17T23:00:34
117,902,992
1
0
null
null
null
null
UTF-8
C++
false
false
5,291
cpp
// Copyright (c) 2015-2017, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // // This file is part of Caliper. // Written by David Boehme, boehme3@llnl.gov. // LLNL-CODE-678900 // All rights reserved. // // For details, see https://github.com/scalability-llnl/Caliper. // Please also see the LICENSE file for our additional BSD notice. // // 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 disclaimer below. // * Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the disclaimer (as noted below) in the documentation and/or other materials // provided with the distribution. // * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. /// \file AnnotationBinding.cpp /// \brief Base class for implementing Caliper-to-X annotation bindings #include "AnnotationBinding.h" #include "caliper/common/Node.h" #include "caliper/common/Log.h" #include "caliper/common/filters/RegexFilter.h" using namespace cali; // // --- Static data // const cali::ConfigSet::Entry AnnotationBinding::s_configdata[] = { { "regex_filter", CALI_TYPE_STRING, "", "Regular expression for matching annotations", "Regular expression for matching annotations" }, { "trigger_attributes", CALI_TYPE_STRING, "", "List of attributes that trigger the annotation binding", "List of attributes that trigger the annotation binding" }, { "", CALI_TYPE_BOOL, "true", "Whether the condition of the filter says what to include or what to exclude", "Whether the condition of the filter says what to include or what to exclude" }, cali::ConfigSet::Terminator }; // // --- Implementation // AnnotationBinding::~AnnotationBinding() { delete m_filter; } void AnnotationBinding::pre_create_attr_cb(Caliper* c, const std::string& name, cali_attr_type type, int* prop, Node** node) { if (*prop & CALI_ATTR_SKIP_EVENTS) return; if (m_trigger_attr_names.empty()) { // By default, enable binding only for class.nested attributes if (!(*prop & CALI_ATTR_NESTED)) return; } else { if (std::find(m_trigger_attr_names.begin(), m_trigger_attr_names.end(), name) == m_trigger_attr_names.end()) return; } // Add the binding marker for this attribute Variant v_true(true); *node = c->make_tree_entry(m_marker_attr, v_true, *node); // Invoke derived functions on_create_attribute(c, name, type, prop, node); Log(2).stream() << "Adding " << this->service_tag() << " bindings for attribute \"" << name << "\"" << std::endl; } void AnnotationBinding::begin_cb(Caliper* c, const Attribute& attr, const Variant& value) { if (attr.skip_events()) return; if (attr.get(m_marker_attr) != Variant(true)) return; if (m_filter && !m_filter->filter(attr, value)) return; this->on_begin(c, attr, value); } void AnnotationBinding::end_cb(Caliper* c, const Attribute& attr, const Variant& value) { if (attr.skip_events()) return; if (attr.get(m_marker_attr) != Variant(true)) return; if (m_filter && !m_filter->filter(attr, value)) return; this->on_end(c, attr, value); } void AnnotationBinding::pre_initialize(Caliper* c) { const char* tag = service_tag(); m_config = cali::RuntimeConfig::init(tag, s_configdata); if (m_config.get("regex").to_string().size() > 0) m_filter = new RegexFilter(tag, m_config); m_trigger_attr_names = m_config.get("trigger_attributes").to_stringlist(",:"); std::string marker_attr_name("cali.binding."); marker_attr_name.append(tag); m_marker_attr = c->create_attribute(marker_attr_name, CALI_TYPE_BOOL, CALI_ATTR_HIDDEN | CALI_ATTR_SKIP_EVENTS); }
[ "poliakoff1@llnl.gov" ]
poliakoff1@llnl.gov
967a84ca57736476932fdc8fe4ecd151fc5de70d
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-sso-admin/include/aws/sso-admin/model/ListCustomerManagedPolicyReferencesInPermissionSetRequest.h
c7c2b706a28273e5b8b543a29848976bd7decad7
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
8,208
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sso-admin/SSOAdmin_EXPORTS.h> #include <aws/sso-admin/SSOAdminRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace SSOAdmin { namespace Model { /** */ class AWS_SSOADMIN_API ListCustomerManagedPolicyReferencesInPermissionSetRequest : public SSOAdminRequest { public: ListCustomerManagedPolicyReferencesInPermissionSetRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListCustomerManagedPolicyReferencesInPermissionSet"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline const Aws::String& GetInstanceArn() const{ return m_instanceArn; } /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline bool InstanceArnHasBeenSet() const { return m_instanceArnHasBeenSet; } /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline void SetInstanceArn(const Aws::String& value) { m_instanceArnHasBeenSet = true; m_instanceArn = value; } /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline void SetInstanceArn(Aws::String&& value) { m_instanceArnHasBeenSet = true; m_instanceArn = std::move(value); } /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline void SetInstanceArn(const char* value) { m_instanceArnHasBeenSet = true; m_instanceArn.assign(value); } /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithInstanceArn(const Aws::String& value) { SetInstanceArn(value); return *this;} /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithInstanceArn(Aws::String&& value) { SetInstanceArn(std::move(value)); return *this;} /** * <p>The ARN of the Amazon Web Services SSO instance under which the operation * will be executed. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithInstanceArn(const char* value) { SetInstanceArn(value); return *this;} /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline const Aws::String& GetPermissionSetArn() const{ return m_permissionSetArn; } /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline bool PermissionSetArnHasBeenSet() const { return m_permissionSetArnHasBeenSet; } /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline void SetPermissionSetArn(const Aws::String& value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn = value; } /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline void SetPermissionSetArn(Aws::String&& value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn = std::move(value); } /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline void SetPermissionSetArn(const char* value) { m_permissionSetArnHasBeenSet = true; m_permissionSetArn.assign(value); } /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithPermissionSetArn(const Aws::String& value) { SetPermissionSetArn(value); return *this;} /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithPermissionSetArn(Aws::String&& value) { SetPermissionSetArn(std::move(value)); return *this;} /** * <p>The ARN of the <code>PermissionSet</code>. </p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithPermissionSetArn(const char* value) { SetPermissionSetArn(value); return *this;} /** * <p>The maximum number of results to display for the list call.</p> */ inline int GetMaxResults() const{ return m_maxResults; } /** * <p>The maximum number of results to display for the list call.</p> */ inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; } /** * <p>The maximum number of results to display for the list call.</p> */ inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; } /** * <p>The maximum number of results to display for the list call.</p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;} /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>The pagination token for the list API. Initially the value is null. Use the * output of previous API calls to make subsequent calls.</p> */ inline ListCustomerManagedPolicyReferencesInPermissionSetRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::String m_instanceArn; bool m_instanceArnHasBeenSet; Aws::String m_permissionSetArn; bool m_permissionSetArnHasBeenSet; int m_maxResults; bool m_maxResultsHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; }; } // namespace Model } // namespace SSOAdmin } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
52980259e51a05a8843a596861f560114c3ae35f
baf095d0aab37ee64fae9d00caf56c30002cb114
/Hamming Distance.cpp
a6214e0831b44094aac5d2909924192b9a1b7712
[]
no_license
nkwarrior84/LeetCode
885ec65b72fd1cdaf6831f6f947079ce6362c510
30a61f21c26c12afe40ad9f2c7584db792b74189
refs/heads/master
2022-12-14T12:06:43.430145
2020-09-12T15:23:43
2020-09-12T15:23:43
276,349,400
1
0
null
null
null
null
UTF-8
C++
false
false
2,217
cpp
/* The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. Solution 1: Without XOR Take the mod with two get the last/least significant bit. Compare each of the i-th bits, adding 1 to our answer when they are different. Divide both number by 2 remove the last/least significant bit. Repeat step 1-3 until any number > 0. class Solution { public int hammingDistance(int x, int y) { int hd = 0; while(x > 0 || y > 0) { hd += (x % 2 != y % 2) ? 1 : 0; x /= 2; y /= 2; } return hd; } } Solution 2: 1 Liner using Inbuilt Integer bitCount function As per hamming distance definition if bit different then 1 else 0 which is same as taking xor and count the number of set bits. class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } } Solution 3: If in interview not allowed to use Integer.bitCount(x) method. countOne / countSetBits in number n can be achieve in many ways. Using simple Math mod by 2 property used in Solution 1. Second using below Brian Kernigham Algorithm, fast approach to count set bits Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost bit. 10 in binary is 00001010 9 in binary is 00001001 8 in binary is 00001000 7 in binary is 00000111 class Solution { public int hammingDistance(int x, int y) { return bitCount( x ^ y); } private int bitCount(int n) { int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; } } */ class Solution { public: int hammingDistance(int x, int y) { int z=x^y; int distance = 0; while(z) { distance += z%2; z /= 2; } return distance; } };
[ "noreply@github.com" ]
nkwarrior84.noreply@github.com
454a218d09d383e920dab21b31f2388fbbd97a0b
3a5778e8ceebf86ac38ef97263729b4ca492e39b
/src/particle_filter.cpp
30452e4ac55e63f245068edcb152dea7a87f2ef1
[]
no_license
fvmassoli/CarND-Kidnapped-Vehicle-Project
54b77923d4e9a7748366fef60e9c3fff6865a339
5ecf37e554f9014e925b91fbf3788daaeb5db956
refs/heads/master
2021-01-21T05:21:34.205218
2017-08-30T19:26:40
2017-08-30T19:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,678
cpp
#include <random> #include <algorithm> #include <random> #include <iostream> #include <tuple> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using std::normal_distribution; using std::default_random_engine; using vector_t = std::vector<double>; default_random_engine gen; const vector_t CTRV_ModelFunc(double delta_t, const vector_t& x, const vector_t& u, const double std_pos[]) { static default_random_engine gen; normal_distribution<double> dist_x(0, std_pos[0]); normal_distribution<double> dist_y(0, std_pos[1]); normal_distribution<double> dist_yaw(0, std_pos[2]); //extract values for better readability double p_x = x[0]; double p_y = x[1]; double yaw = x[2]; double v = u[0]; double yawd = u[1]; //predicted state values double px_p, py_p; //avoid division by zero if (std::fabs(yawd) > 0.01) { px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw)); py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) ); } else { px_p = p_x + v*delta_t*cos(yaw); py_p = p_y + v*delta_t*sin(yaw); } // Yaw angle double pyaw_p = yaw + yawd*delta_t; // Add noise px_p = px_p + dist_x(gen); py_p = py_p + dist_y(gen); pyaw_p = pyaw_p + dist_yaw(gen); //return predicted state return {px_p, py_p, pyaw_p}; } using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // Add random Gaussian noise to each particle. normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); double sample_x, sample_y, sample_psi; num_particles = 200; weights.resize(num_particles, 1.0f); for(unsigned i=0; i<num_particles; i++) { Particle p; p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); p.id = i; p.weight = 1.0f; particles.push_back(p); } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { for(auto i=0; i<particles.size(); i++) { auto p = particles[i]; vector_t x_pred = CTRV_ModelFunc(delta_t, {p.x, p.y, p.theta}, {velocity, yaw_rate}, std_pos); particles[i].x = x_pred[0]; particles[i].y = x_pred[1]; particles[i].theta = x_pred[2]; } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { double min_distance, dist, dx, dy; int min_i; for(unsigned obs_i = 0; obs_i < observations.size(); obs_i++) { auto obs = observations[obs_i]; min_distance = INFINITY; min_i = -1; for(unsigned i = 0; i < predicted.size(); i++) { auto pred_lm = predicted[i]; dx = (pred_lm.x - obs.x); dy = (pred_lm.y - obs.y); dist = dx*dx + dy*dy; if(dist < min_distance) { min_distance = dist; min_i = i; } } observations[obs_i].id = min_i; } } const LandmarkObs local_to_global(const LandmarkObs& obs, const Particle& p) { LandmarkObs out; // First rotate the local coordinates to the right orientation out.x = p.x + obs.x * cos(p.theta) - obs.y * sin(p.theta); out.y = p.y + obs.x * sin(p.theta) + obs.y * cos(p.theta); out.id = obs.id; return out; } inline const double gaussian_2d(const LandmarkObs& obs, const LandmarkObs &lm, const double sigma[]) { auto cov_x = sigma[0]*sigma[0]; auto cov_y = sigma[1]*sigma[1]; auto normalizer = 2.0*M_PI*sigma[0]*sigma[1]; auto dx = (obs.x - lm.x); auto dy = (obs.y - lm.y); return exp(-(dx*dx/(2*cov_x) + dy*dy/(2*cov_y)))/normalizer; } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], std::vector<LandmarkObs> observations, Map map_landmarks) { double sigma_landmark [2] = {0.3, 0.3}; for(unsigned p_ctr=0; p_ctr < particles.size(); p_ctr++) { auto p = particles[p_ctr]; std::vector<LandmarkObs> predicted_landmarks; for(auto lm : map_landmarks.landmark_list) { LandmarkObs lm_pred; lm_pred.x = lm.x_f; lm_pred.y = lm.y_f; lm_pred.id = lm.id_i; auto dx = lm_pred.x - p.x; auto dy = lm_pred.y - p.y; // Add only if in range if(dx*dx + dy*dy <= sensor_range*sensor_range) predicted_landmarks.push_back(lm_pred); } std::vector<LandmarkObs> transformed_obs; double total_prob = 1.0f; // transform coordinates of all observations (for current particle) for(auto obs_lm : observations) { auto obs_global = local_to_global(obs_lm, p); transformed_obs.push_back(std::move(obs_global)); } // Stores index of associated landmark in the observation dataAssociation(predicted_landmarks, transformed_obs); for(unsigned i=0; i < transformed_obs.size(); i++) { auto obs = transformed_obs[i]; // Assume sorted by id and starting at 1 auto assoc_lm = predicted_landmarks[obs.id]; double pdf = gaussian_2d(obs, assoc_lm, sigma_landmark); total_prob *= pdf; } particles[p_ctr].weight = total_prob; weights[p_ctr] = total_prob; } std::cout<<std::endl; } void ParticleFilter::resample() { std::discrete_distribution<int> d(weights.begin(), weights.end()); std::vector<Particle> new_particles; for(unsigned i = 0; i < num_particles; i++) { auto ind = d(gen); new_particles.push_back(std::move(particles[ind])); } particles = std::move(new_particles); } Particle ParticleFilter::SetAssociations(Particle particle, std::vector<int> associations, std::vector<double> sense_x, std::vector<double> sense_y) { //Clear the previous associations particle.associations.clear(); particle.sense_x.clear(); particle.sense_y.clear(); particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; return particle; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; }
[ "fabiovaleriomassoli@gmail.com" ]
fabiovaleriomassoli@gmail.com
c70fdae1c85d45479b01a630120d07736ecbed57
55cca1cee89f88a8ad327f39685d116a81379b22
/src/qt/sendcoinsentry.cpp
d970d7a154fd476baced579b620b8cba6d6d9acd
[ "MIT" ]
permissive
winkchain/wink
8cb3265c97bdcb03d414bdbba1fad1b399157e5f
be8643ec8f85347544e62a05b23135bfa0b4cb04
refs/heads/master
2021-01-01T18:47:31.479058
2017-07-26T15:36:51
2017-07-26T15:36:51
98,439,022
2
0
null
null
null
null
UTF-8
C++
false
false
4,296
cpp
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a Winkcoin address (e.g. NaoikK1pALjkLwYTnJSJMu2VHUmP5nJWfR)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "you@example.com" ]
you@example.com
d16b27decf2b5bad345e596a4b7c30f7e6867893
5521a03064928d63cc199e8034e4ea76264f76da
/fboss/thrift_cow/nodes/ThriftMapNode-inl.h
5b8f5b6f8e0f65ecb8edcd065ec3f68089899480
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
facebook/fboss
df190fd304e0bf5bfe4b00af29f36b55fa00efad
81e02db57903b4369200eec7ef22d882da93c311
refs/heads/main
2023-09-01T18:21:22.565059
2023-09-01T15:53:39
2023-09-01T15:53:39
31,927,407
925
353
NOASSERTION
2023-09-14T05:44:49
2015-03-09T23:04:15
C++
UTF-8
C++
false
false
13,587
h
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <fatal/container/tuple.h> #include <folly/dynamic.h> #include <thrift/lib/cpp2/protocol/detail/protocol_methods.h> #include <thrift/lib/cpp2/reflection/folly_dynamic.h> #include <thrift/lib/cpp2/reflection/reflection.h> #include "fboss/agent/state/NodeBase-defs.h" #include "fboss/thrift_cow/nodes/Serializer.h" #include "fboss/thrift_cow/nodes/Types.h" #include "fboss/agent/state/MapDelta.h" namespace facebook::fboss::thrift_cow { namespace map_helpers { template <typename TC> struct ExtractTypeClass { using type = TC; }; template <typename KeyTypeClass, typename ValueTypeClass> struct ExtractTypeClass< apache::thrift::type_class::map<KeyTypeClass, ValueTypeClass>> { using key_type = KeyTypeClass; using value_type = ValueTypeClass; }; } // namespace map_helpers template <typename Traits> struct ThriftMapFields { using TypeClass = typename Traits::TC; using TType = typename Traits::Type; using Self = ThriftMapFields<Traits>; using CowType = FieldsType; using ThriftType = TType; using KeyTypeClass = typename map_helpers::ExtractTypeClass<TypeClass>::key_type; using ValueTypeClass = typename map_helpers::ExtractTypeClass<TypeClass>::value_type; using ValueTType = typename TType::mapped_type; using ValueTraits = typename Traits::template ConvertToNodeTraits<ValueTypeClass, ValueTType>; using key_type = typename TType::key_type; using value_type = typename ValueTraits::type; using StorageType = std::map<key_type, value_type, typename Traits::KeyCompare>; using iterator = typename StorageType::iterator; using const_iterator = typename StorageType::const_iterator; // whether the contained type is another Cow node, or a primitive node static constexpr bool HasChildNodes = ValueTraits::isChild::value; // constructors: // One takes a thrift type directly, one starts with empty vector ThriftMapFields() {} template < typename T, typename = std::enable_if_t<std::is_same<std::decay_t<T>, TType>::value>> explicit ThriftMapFields(T&& thrift) { fromThrift(std::forward<T>(thrift)); } /* implicit */ ThriftMapFields(StorageType storage) : storage_(std::move(storage)) {} // TODO(pshaikh): fix this redunant constructor ThriftMapFields(const ThriftMapFields&, StorageType storage) : storage_(std::move(storage)) {} TType toThrift() const { TType thrift; for (auto&& [key, elem] : storage_) { thrift.emplace(key, elem->toThrift()); } return thrift; } template < typename T, typename = std::enable_if_t<std::is_same<std::decay_t<T>, TType>::value>> void fromThrift(T&& thrift) { storage_.clear(); for (const auto& [key, elem] : thrift) { emplace(key, elem); } } #ifdef ENABLE_DYNAMIC_APIS folly::dynamic toDynamic() const { folly::dynamic out; apache::thrift::to_dynamic<TypeClass>( out, toThrift(), apache::thrift::dynamic_format::JSON_1); return out; } void fromDynamic(const folly::dynamic& value) { TType thrift; apache::thrift::from_dynamic<TypeClass>( thrift, value, apache::thrift::dynamic_format::JSON_1); fromThrift(thrift); } #endif folly::fbstring encode(fsdb::OperProtocol proto) const { return serialize<TypeClass>(proto, toThrift()); } void fromEncoded(fsdb::OperProtocol proto, const folly::fbstring& encoded) { fromThrift(deserialize<TypeClass, TType>(proto, encoded)); } value_type at(key_type key) const { return storage_.at(key); } value_type& operator[](key_type key) { return storage_[key]; } value_type& ref(key_type key) { return storage_.at(key); } const value_type& ref(key_type key) const { return storage_.at(key); } const value_type& cref(key_type key) const { return storage_.at(key); } std::pair<iterator, bool> insert(key_type key, value_type&& val) { return storage_.insert({key, val}); } template <typename... Args> std::pair<iterator, bool> emplace(key_type key, Args&&... args) { return storage_.emplace(key, childFactory(std::forward<Args>(args)...)); } template <typename... Args> std::pair<iterator, bool> try_emplace(key_type key, Args&&... args) { return storage_.try_emplace(key, childFactory(std::forward<Args>(args)...)); } bool remove(const std::string& token) { if constexpr (std::is_same_v< KeyTypeClass, apache::thrift::type_class::enumeration>) { // special handling for enum keyed maps key_type enumKey; if (fatal::enum_traits<key_type>::try_parse(enumKey, token)) { return remove(enumKey); } } else if constexpr (std::is_same_v< KeyTypeClass, apache::thrift::type_class::string>) { return storage_.erase(token); } auto key = folly::tryTo<key_type>(token); if (key.hasValue()) { return remove(key.value()); } return false; } template <typename T = Self> auto remove(const key_type& key) -> std::enable_if_t< !std::is_same_v< typename T::KeyTypeClass, apache::thrift::type_class::string>, bool> { return storage_.erase(key); } auto erase(iterator it) { return storage_.erase(it); } // iterators iterator begin() { return storage_.begin(); } const_iterator begin() const { return storage_.cbegin(); } iterator end() { return storage_.end(); } const_iterator end() const { return storage_.end(); } iterator find(const key_type& key) { return storage_.find(key); } const_iterator find(const key_type& key) const { return storage_.find(key); } const_iterator cbegin() const { return storage_.cbegin(); } const_iterator cend() const { return storage_.cend(); } std::size_t size() const { return storage_.size(); } template <typename Fn> void forEachChild(Fn fn) { if constexpr (HasChildNodes) { for (auto&& [key, value] : storage_) { fn(value.get()); } } } bool operator==(const Self& that) const { return storage_ == that.storage_; } bool operator!=(const Self& that) const { return !(*this == that); } void clear() { storage_.clear(); } private: template <typename... Args> value_type childFactory(Args&&... args) { if constexpr (HasChildNodes) { return std::make_shared<typename value_type::element_type>( std::forward<Args>(args)...); } else { return std::make_optional<typename value_type::value_type>( std::forward<Args>(args)...); } } StorageType storage_; }; template <typename Traits, typename Resolver = ThriftMapResolver<Traits>> class ThriftMapNode : public NodeBaseT<typename Resolver::type, ThriftMapFields<Traits>> { public: using TypeClass = typename Traits::TC; using TType = typename Traits::Type; using Self = ThriftMapNode<Traits, Resolver>; using Fields = ThriftMapFields<Traits>; using ThriftType = typename Fields::ThriftType; using Derived = typename Resolver::type; using BaseT = NodeBaseT<Derived, Fields>; using CowType = NodeType; using key_type = typename Fields::key_type; using value_type = typename Fields::value_type; using PathIter = typename std::vector<std::string>::const_iterator; using mapped_type = value_type; using const_iterator = typename Fields::const_iterator; using BaseT::BaseT; TType toThrift() const { return this->getFields()->toThrift(); } void fromThrift(const TType& thrift) { return this->writableFields()->fromThrift(thrift); } #ifdef ENABLE_DYNAMIC_APIS folly::dynamic toFollyDynamic() const override { return this->getFields()->toDynamic(); } void fromFollyDynamic(const folly::dynamic& value) { return this->writableFields()->fromDynamic(value); } #else folly::dynamic toFollyDynamic() const override { return {}; } #endif folly::fbstring encode(fsdb::OperProtocol proto) const { return this->getFields()->encode(proto); } void fromEncoded(fsdb::OperProtocol proto, const folly::fbstring& encoded) { return this->writableFields()->fromEncoded(proto, encoded); } value_type at(key_type key) const { return this->getFields()->at(key); } value_type& operator[](key_type key) { return this->writableFields()->operator[](key); } value_type& ref(key_type key) { return this->writableFields()->ref(key); } const value_type& ref(key_type key) const { return this->getFields()->ref(key); } const value_type& cref(key_type key) const { return this->getFields()->cref(key); } // prefer safe_ref/safe_cref for safe access auto safe_ref(key_type key) { return detail::ref(this->writableFields()->ref(key)); } auto safe_cref(key_type key) const { return detail::cref(this->getFields()->cref(key)); } std::pair<typename Fields::iterator, bool> insert( key_type key, value_type&& val) { return this->writableFields()->insert(key, std::move(val)); } template <typename... Args> typename std::pair<typename Fields::iterator, bool> emplace( key_type key, Args&&... args) { return this->writableFields()->emplace(key, std::forward<Args>(args)...); } template <typename... Args> typename std::pair<typename Fields::iterator, bool> try_emplace( key_type key, Args&&... args) { return this->writableFields()->try_emplace( key, std::forward<Args>(args)...); } bool remove(const std::string& token) { return this->writableFields()->remove(token); } template <typename T = Fields> auto remove(const key_type& key) -> std::enable_if_t< !std::is_same_v< typename T::KeyTypeClass, apache::thrift::type_class::string>, bool> { return this->writableFields()->remove(key); } auto erase(typename Fields::iterator it) { return this->writableFields()->erase(it); } // iterators typename Fields::iterator begin() { return this->writableFields()->begin(); } typename Fields::const_iterator begin() const { return this->getFields()->begin(); } typename Fields::iterator end() { return this->writableFields()->end(); } typename Fields::const_iterator end() const { return this->getFields()->end(); } typename Fields::const_iterator cbegin() const { return this->getFields()->cbegin(); } typename Fields::const_iterator cend() const { return this->getFields()->cend(); } typename Fields::iterator find(const key_type& key) { return this->writableFields()->find(key); } typename Fields::const_iterator find(const key_type& key) const { return this->getFields()->find(key); } std::size_t size() const { return this->getFields()->size(); } bool empty() const { return size() == 0; } void modify(const std::string& token) { if constexpr (std::is_same_v< typename Fields::KeyTypeClass, apache::thrift::type_class::enumeration>) { // special handling for enum keyed maps key_type enumKey; if (fatal::enum_traits<key_type>::try_parse(enumKey, token)) { modifyImpl(enumKey); return; } } auto key = folly::tryTo<key_type>(token); if (key.hasValue()) { modifyImpl(key.value()); return; } throw std::runtime_error(folly::to<std::string>("Invalid key: ", token)); } void modifyImpl(key_type key) { DCHECK(!this->isPublished()); if (auto it = this->find(key); it != this->end()) { if constexpr (Fields::HasChildNodes) { auto& child = it->second; if (child->isPublished()) { auto clonedChild = child->clone(); child.swap(clonedChild); } } } else { // create unpublished default constructed child if missing this->emplace(key); } } static void modify(std::shared_ptr<Self>* node, std::string token) { auto newNode = ((*node)->isPublished()) ? (*node)->clone() : *node; newNode->modify(token); node->swap(newNode); } /* * Visitors by string path */ template <typename Func> inline ThriftTraverseResult visitPath(PathIter begin, PathIter end, Func&& f) { return PathVisitor<TypeClass>::visit( *this, begin, end, PathVisitMode::LEAF, std::forward<Func>(f)); } template <typename Func> inline ThriftTraverseResult visitPath(PathIter begin, PathIter end, Func&& f) const { return PathVisitor<TypeClass>::visit( *this, begin, end, PathVisitMode::LEAF, std::forward<Func>(f)); } template <typename Func> inline ThriftTraverseResult cvisitPath(PathIter begin, PathIter end, Func&& f) const { return PathVisitor<TypeClass>::visit( *this, begin, end, PathVisitMode::LEAF, std::forward<Func>(f)); } bool operator==(const Self& that) const { return *this->getFields() == *that.getFields(); } bool operator!=(const Self& that) const { return !(*this == that); } void clear() { this->writableFields()->clear(); } private: friend class CloneAllocator; }; } // namespace facebook::fboss::thrift_cow
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
232e2523041aafbaa25aa6f9699240d9d73af590
c568ca508e4e4f96b933ddb823c1f09be0bfd6f9
/Researcher.hpp
9bf8a3daa5ab0c6b90c4577455870269ea23739c
[]
no_license
tomerklugman/pandemic-a-cpp
e5bab750545f5afabf3485c73b2e244e2f01a2bb
0ae8f82e7441229cbffcbe9326ed4e64060769c7
refs/heads/main
2023-05-28T08:17:30.648870
2021-05-05T16:15:09
2021-05-05T16:15:09
364,634,481
0
0
null
null
null
null
UTF-8
C++
false
false
221
hpp
#include "Player.hpp" namespace pandemic { class Researcher : public Player { public: Researcher(Board &board, City city) : Player(board, city){}; Player &discover_cure(Color color); }; }
[ "noreply@github.com" ]
tomerklugman.noreply@github.com
8be07842f819252297f261d45868fed3488d79b5
542518f17b7e2f47717e37d76ca54f304a065681
/CAD2/arx2015/inc/dbents.h
3b5b8ab848365bfb961302ac1baf6b8151b22377
[]
no_license
joshinils/cad2_ss19
a61f7151afdf353b662c492656e7620044019e88
509c768c7e02c927ef78ca7f7f0b84b457494e64
refs/heads/master
2020-05-07T22:47:48.713311
2019-06-28T09:36:25
2019-06-28T09:36:25
180,960,541
1
1
null
null
null
null
UTF-8
C++
false
false
50,288
h
#ifndef AD_DBENTS_H #define AD_DBENTS_H // ////////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // // DESCRIPTION: Exported pre-R13 Entity classes // // AcRxObject // AcDbObject // AcDbEntity // AcDbText // AcDbAttribute // AcDbAttributeDefinition // AcDbBlockBegin // AcDbBlockEnd // AcDbSequenceEnd // AcDbBlockReference // AcDbMInsertBlock // AcDbVertex // AcDb2dVertex // AcDb3dPolylineVertex // AcDbPolygonMeshVertex // AcDbPolyFaceMeshVertex // AcDbFaceRecord // AcDbCurve // AcDb2dPolyline // AcDb3dPolyline // AcDbArc // AcDbCircle // AcDbLine // AcDbPoint // AcDbFace // AcDbPolyFaceMesh // AcDbPolygonMesh // AcDbTrace // AcDbSolid // AcDbShape // AcDbViewport // #include "dbmain.h" #include "dbcurve.h" #include "gescl3d.h" #include "gepnt2d.h" #include "dbmtext.h" #include "dbbackground.h" #include "dbdim.h" #include "gept2dar.h" #include "gedblar.h" #include "dbsymtb.h" #include "gemat3d.h" #include "acdbxref.h" #include "acgi.h" #include "acgiviewport.h" #include "acgivisualstyle.h" #pragma pack(push, 8) class AcDbAttribute; class AcDbSequenceEnd; class AcDb3dPolylineVertex; class AcDb2dVertex; class AcDbMText; class AcDbAnnotationScale; namespace Atil { class Image; // for Atil::Image } class AcDbText: public AcDbEntity { public: AcDbText(); AcDbText( const AcGePoint3d& position, const ACHAR* text, AcDbObjectId style = AcDbObjectId::kNull, double height = 0, double rotation = 0); ~AcDbText(); ACDB_DECLARE_MEMBERS(AcDbText); AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); AcGePoint3d alignmentPoint() const; Acad::ErrorStatus setAlignmentPoint(const AcGePoint3d&); Adesk::Boolean isDefaultAlignment() const; AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); virtual Adesk::Boolean isPlanar() const override { return Adesk::kTrue; } virtual Acad::ErrorStatus getPlane(AcGePlane&, AcDb::Planarity&) const override; double thickness() const; Acad::ErrorStatus setThickness(double); double oblique() const; Acad::ErrorStatus setOblique(double); double rotation() const; Acad::ErrorStatus setRotation(double); double height() const; Acad::ErrorStatus setHeight(double); double widthFactor() const; Acad::ErrorStatus setWidthFactor(double); ACHAR* textString() const; const ACHAR* textStringConst() const; Acad::ErrorStatus setTextString(const ACHAR*); AcDbObjectId textStyle() const; Acad::ErrorStatus setTextStyle(AcDbObjectId); Adesk::Boolean isMirroredInX() const; Acad::ErrorStatus mirrorInX(Adesk::Boolean); Adesk::Boolean isMirroredInY() const; Acad::ErrorStatus mirrorInY(Adesk::Boolean); AcDb::TextHorzMode horizontalMode() const; Acad::ErrorStatus setHorizontalMode(AcDb::TextHorzMode); AcDb::TextVertMode verticalMode() const; Acad::ErrorStatus setVerticalMode(AcDb::TextVertMode); int correctSpelling(); virtual Acad::ErrorStatus adjustAlignment( const AcDbDatabase* pDb = nullptr); Acad::ErrorStatus setField(const ACHAR* pszPropName, AcDbField* pField, AcDbObjectId& fieldId); Acad::ErrorStatus removeField(AcDbObjectId fieldId); Acad::ErrorStatus removeField(const ACHAR* pszPropName, AcDbObjectId& returnId); Acad::ErrorStatus removeField(const ACHAR* pszPropName); Acad::ErrorStatus convertFieldToText(); enum AcTextAlignment { kTextAlignmentLeft = 0, kTextAlignmentCenter = ( kTextAlignmentLeft + 1 ) , kTextAlignmentRight = ( kTextAlignmentCenter + 1 ) , kTextAlignmentAligned = ( kTextAlignmentRight + 1 ) , kTextAlignmentMiddle = ( kTextAlignmentAligned + 1 ) , kTextAlignmentFit = ( kTextAlignmentMiddle + 1 ) , kTextAlignmentTopLeft = ( kTextAlignmentFit + 1 ) , kTextAlignmentTopCenter = ( kTextAlignmentTopLeft + 1 ) , kTextAlignmentTopRight = ( kTextAlignmentTopCenter + 1 ) , kTextAlignmentMiddleLeft = ( kTextAlignmentTopRight + 1 ) , kTextAlignmentMiddleCenter = ( kTextAlignmentMiddleLeft + 1 ) , kTextAlignmentMiddleRight = ( kTextAlignmentMiddleCenter + 1 ) , kTextAlignmentBottomLeft = ( kTextAlignmentMiddleRight + 1 ) , kTextAlignmentBottomCenter = ( kTextAlignmentBottomLeft + 1 ) , kTextAlignmentBottomRight = ( kTextAlignmentBottomCenter + 1 ) }; ACDB_PORT AcTextAlignment justification() const; ACDB_PORT Acad::ErrorStatus setJustification(AcTextAlignment); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbAttributeDefinition: public AcDbText { public: AcDbAttributeDefinition(); AcDbAttributeDefinition( const AcGePoint3d& position, const ACHAR* text, const ACHAR* tag, const ACHAR* prompt, AcDbObjectId style = AcDbObjectId::kNull); ~AcDbAttributeDefinition(); ACDB_DECLARE_MEMBERS(AcDbAttributeDefinition); ACHAR* prompt() const; const ACHAR* promptConst() const; Acad::ErrorStatus setPrompt(const ACHAR*); ACHAR* tag() const; const ACHAR* tagConst() const; Acad::ErrorStatus setTag(const ACHAR*); Adesk::Boolean isInvisible() const; Acad::ErrorStatus setInvisible(Adesk::Boolean); Adesk::Boolean isConstant() const; Acad::ErrorStatus setConstant(Adesk::Boolean); Adesk::Boolean isVerifiable() const; Acad::ErrorStatus setVerifiable(Adesk::Boolean); Adesk::Boolean isPreset() const; Acad::ErrorStatus setPreset(Adesk::Boolean); Adesk::UInt16 fieldLength() const; Acad::ErrorStatus setFieldLength(Adesk::UInt16); virtual Acad::ErrorStatus adjustAlignment( const AcDbDatabase* pDb = nullptr) override; bool lockPositionInBlock() const; Acad::ErrorStatus setLockPositionInBlock(bool bValue); // multiline attribute definition support bool isMTextAttributeDefinition () const; AcDbMText * getMTextAttributeDefinition () const; const AcDbMText * getMTextAttributeDefinitionConst () const; Acad::ErrorStatus setMTextAttributeDefinition (AcDbMText*); ACDB_PORT Acad::ErrorStatus setMTextAttributeDefinitionConst(const AcDbMText*); Acad::ErrorStatus convertIntoMTextAttributeDefinition (Adesk::Boolean val = Adesk::kTrue); Acad::ErrorStatus updateMTextAttributeDefinition (); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbAttribute: public AcDbText { public: AcDbAttribute(); AcDbAttribute( const AcGePoint3d& position, const ACHAR* text, const ACHAR* tag, AcDbObjectId style = AcDbObjectId::kNull); ~AcDbAttribute(); ACDB_DECLARE_MEMBERS(AcDbAttribute); ACHAR* tag() const; const ACHAR* tagConst() const; Acad::ErrorStatus setTag(const ACHAR* newTag); Adesk::Boolean isInvisible() const; Acad::ErrorStatus setInvisible(Adesk::Boolean); Adesk::Boolean isConstant() const; Adesk::Boolean isVerifiable() const; Adesk::Boolean isPreset() const; Adesk::UInt16 fieldLength() const; Acad::ErrorStatus setFieldLength(Adesk::UInt16); Acad::ErrorStatus setAttributeFromBlock(const AcGeMatrix3d& blkXform); Acad::ErrorStatus setAttributeFromBlock( const AcDbAttributeDefinition *pAttdef, const AcGeMatrix3d& blkXform); bool lockPositionInBlock() const; Acad::ErrorStatus setLockPositionInBlock(bool bValue); // multiline attribute support bool isMTextAttribute () const; AcDbMText * getMTextAttribute () const; const AcDbMText * getMTextAttributeConst () const; Acad::ErrorStatus setMTextAttribute (AcDbMText *); ACDB_PORT Acad::ErrorStatus setMTextAttributeConst(const AcDbMText *); Acad::ErrorStatus convertIntoMTextAttribute (Adesk::Boolean val = Adesk::kTrue); Acad::ErrorStatus updateMTextAttribute (); bool isReallyLocked () const; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbBlockReference: public AcDbEntity { public: AcDbBlockReference(); AcDbBlockReference(const AcGePoint3d& position, AcDbObjectId blockTableRec); ~AcDbBlockReference(); ACDB_DECLARE_MEMBERS(AcDbBlockReference); AcDbObjectId blockTableRecord() const; virtual Acad::ErrorStatus setBlockTableRecord(AcDbObjectId); virtual AcGePoint3d position() const; virtual Acad::ErrorStatus setPosition(const AcGePoint3d&); AcGeScale3d scaleFactors() const; AcGeScale3d nonAnnotationScaleFactors() const; virtual Acad::ErrorStatus setScaleFactors(const AcGeScale3d& scale); double rotation() const; virtual Acad::ErrorStatus setRotation(double newVal); AcGeVector3d normal() const; virtual Acad::ErrorStatus setNormal(const AcGeVector3d& newVal); virtual Adesk::Boolean isPlanar() const { return Adesk::kTrue; } virtual Acad::ErrorStatus getPlane(AcGePlane&, AcDb::Planarity&) const; AcGeMatrix3d blockTransform() const; AcGeMatrix3d nonAnnotationBlockTransform() const; virtual Acad::ErrorStatus setBlockTransform(const AcGeMatrix3d&); Acad::ErrorStatus appendAttribute(AcDbAttribute*); Acad::ErrorStatus appendAttribute(AcDbObjectId&, AcDbAttribute*); Acad::ErrorStatus openAttribute(AcDbAttribute*&, AcDbObjectId, AcDb::OpenMode, bool openErasedOne = false); Acad::ErrorStatus openSequenceEnd(AcDbSequenceEnd*&, AcDb::OpenMode); AcDbObjectIterator* attributeIterator() const; virtual Adesk::Boolean treatAsAcDbBlockRefForExplode() const; Acad::ErrorStatus geomExtentsBestFit( AcDbExtents& extents, const AcGeMatrix3d& parentXform = AcGeMatrix3d::kIdentity) const; virtual Acad::ErrorStatus explodeToOwnerSpace() const; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbMInsertBlock: public AcDbBlockReference { public: AcDbMInsertBlock(); AcDbMInsertBlock( const AcGePoint3d& position, AcDbObjectId blockTableRec, Adesk::UInt16 columns, Adesk::UInt16 rows, double colSpacing, double rowSpacing); ~AcDbMInsertBlock(); ACDB_DECLARE_MEMBERS(AcDbMInsertBlock); Adesk::UInt16 columns() const; Acad::ErrorStatus setColumns(Adesk::UInt16); Adesk::UInt16 rows() const; Acad::ErrorStatus setRows(Adesk::UInt16); double columnSpacing() const; Acad::ErrorStatus setColumnSpacing(double); double rowSpacing() const; Acad::ErrorStatus setRowSpacing(double); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbBlockBegin: public AcDbEntity { public: AcDbBlockBegin(); ~AcDbBlockBegin(); ACDB_DECLARE_MEMBERS(AcDbBlockBegin); }; class AcDbBlockEnd: public AcDbEntity { public: AcDbBlockEnd(); ~AcDbBlockEnd(); ACDB_DECLARE_MEMBERS(AcDbBlockEnd); }; class AcDbSequenceEnd: public AcDbEntity { public: AcDbSequenceEnd(); ~AcDbSequenceEnd(); ACDB_DECLARE_MEMBERS(AcDbSequenceEnd); }; class AcDbVertex: public AcDbEntity { public: AcDbVertex(); ~AcDbVertex(); ACDB_DECLARE_MEMBERS(AcDbVertex); }; // Inline for performance, because derived classes' dtors // call this explicitly. // inline AcDbVertex::~AcDbVertex() { } class AcDb2dVertex: public AcDbVertex { public: AcDb2dVertex(); ~AcDb2dVertex(); ACDB_DECLARE_MEMBERS(AcDb2dVertex); AcDb2dVertex( const AcGePoint3d& position, double bulge = 0, double startWidth = 0, double endWidth = 0, double tangent = 0, Adesk::Int32 vertexIdentifier = 0); AcDb::Vertex2dType vertexType() const; // This method accesses the position in ECS. See AcDb2dPolyline for WCS. // AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); double startWidth() const; Acad::ErrorStatus setStartWidth(double newVal); double endWidth() const; Acad::ErrorStatus setEndWidth(double newVal); double bulge() const; Acad::ErrorStatus setBulge(double newVal); Adesk::Boolean isTangentUsed() const; Acad::ErrorStatus useTangent(); Acad::ErrorStatus ignoreTangent(); ACDB_PORT Acad::ErrorStatus setTangentUsed(Adesk::Boolean); double tangent() const; Acad::ErrorStatus setTangent(double newVal); Acad::ErrorStatus setVertexIdentifier(Adesk::Int32 suggestedValue); int vertexIdentifier() const; }; class AcDb3dPolylineVertex: public AcDbVertex { public: AcDb3dPolylineVertex(); ~AcDb3dPolylineVertex(); ACDB_DECLARE_MEMBERS(AcDb3dPolylineVertex); AcDb3dPolylineVertex(const AcGePoint3d&); AcDb::Vertex3dType vertexType() const; AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); }; class AcDbPolygonMeshVertex: public AcDbVertex { public: AcDbPolygonMeshVertex(); AcDbPolygonMeshVertex(const AcGePoint3d& position); ~AcDbPolygonMeshVertex(); ACDB_DECLARE_MEMBERS(AcDbPolygonMeshVertex); AcDb::Vertex3dType vertexType() const; AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); }; class AcDbPolyFaceMeshVertex: public AcDbVertex { public: AcDbPolyFaceMeshVertex(); AcDbPolyFaceMeshVertex(const AcGePoint3d& position); ~AcDbPolyFaceMeshVertex(); ACDB_DECLARE_MEMBERS(AcDbPolyFaceMeshVertex); AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); }; class AcDbFaceRecord: public AcDbVertex { public: AcDbFaceRecord(); // Use negative values to indicate invisible faces AcDbFaceRecord(Adesk::Int16 vtx0, Adesk::Int16 vtx1, Adesk::Int16 vtx2, Adesk::Int16 vtx3); ~AcDbFaceRecord(); ACDB_DECLARE_MEMBERS(AcDbFaceRecord); // Input index must be 0-3. // Acad::ErrorStatus getVertexAt(Adesk::UInt16 faceIdx, Adesk::Int16& vtxIdx) const; Acad::ErrorStatus setVertexAt(Adesk::UInt16 faceIdx, Adesk::Int16 vtxIdx); Acad::ErrorStatus isEdgeVisibleAt(Adesk::UInt16 faceIndex, Adesk::Boolean& visible) const; Acad::ErrorStatus makeEdgeVisibleAt(Adesk::UInt16 faceIndex); Acad::ErrorStatus makeEdgeInvisibleAt(Adesk::UInt16 faceIndex); }; class AcDb2dPolyline: public AcDbCurve { public: AcDb2dPolyline(); ~AcDb2dPolyline(); ACDB_DECLARE_MEMBERS(AcDb2dPolyline); AcDb2dPolyline ( AcDb::Poly2dType type, AcGePoint3dArray& vertices, double elevation = 0, Adesk::Boolean closed = Adesk::kFalse, double defStartWidth = 0, double defEndWidth = 0, AcGeDoubleArray* bulges = nullptr, AcArray<Adesk::Int32>* vertexIdentifiers = nullptr ); DBCURVE_METHODS AcDb::Poly2dType polyType() const; Acad::ErrorStatus setPolyType(AcDb::Poly2dType); Acad::ErrorStatus convertToPolyType(AcDb::Poly2dType newVal); Acad::ErrorStatus makeClosed(); Acad::ErrorStatus makeOpen(); ACDB_PORT Acad::ErrorStatus setClosed(Adesk::Boolean); ACDB_PORT Acad::ErrorStatus constantWidth(double&) const; ACDB_PORT Acad::ErrorStatus setConstantWidth(double); ACDB_PORT Acad::ErrorStatus length(double &) const; double defaultStartWidth() const; Acad::ErrorStatus setDefaultStartWidth(double); double defaultEndWidth() const; Acad::ErrorStatus setDefaultEndWidth(double); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); double elevation() const; Acad::ErrorStatus setElevation(double); Adesk::Boolean isLinetypeGenerationOn() const; Acad::ErrorStatus setLinetypeGenerationOn(); Acad::ErrorStatus setLinetypeGenerationOff(); Acad::ErrorStatus ACDB_PORT setLinetypeGenerationOn(Adesk::Boolean bOn); Acad::ErrorStatus straighten(); Acad::ErrorStatus splineFit(); Acad::ErrorStatus splineFit(AcDb::Poly2dType splineType, Adesk::Int16 splineSegs); Acad::ErrorStatus curveFit(); // Vertex access // Acad::ErrorStatus appendVertex(AcDb2dVertex*); Acad::ErrorStatus appendVertex(AcDbObjectId& objId, AcDb2dVertex*); Acad::ErrorStatus insertVertexAt(const AcDb2dVertex* pIndexVert, AcDb2dVertex* pNewVertex); Acad::ErrorStatus insertVertexAt(AcDbObjectId& newVertId, const AcDbObjectId& indexVertId, AcDb2dVertex* pNewVertex); Acad::ErrorStatus openVertex(AcDb2dVertex*&, AcDbObjectId vertId, AcDb::OpenMode, bool openErasedOne = false) const; Acad::ErrorStatus openSequenceEnd(AcDbSequenceEnd*&, AcDb::OpenMode); AcDbObjectIterator* vertexIterator() const; // Vertex position in WCS // AcGePoint3d vertexPosition(const AcDb2dVertex& vert) const; // Does nothing and returns Acad::eOk if already closed or the start and end // vertices do not coincide // ACDB_PORT Acad::ErrorStatus makeClosedIfStartAndEndVertexCoincide(double distTol); protected: // AcDbEntity overrides virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; inline Adesk::Boolean AcDb2dPolyline::isPeriodic() const { return Adesk::kFalse; } inline Adesk::Boolean AcDb2dPolyline::isPlanar() const { return Adesk::kTrue; } inline Acad::ErrorStatus AcDb2dPolyline::getStartParam(double& param) const { param = 0.0; return Acad::eOk; } inline Acad::ErrorStatus AcDb2dPolyline::extend (double param) { param; // avoid unreferenced formal parameter warning return Acad::eNotApplicable; } class AcDb3dPolyline: public AcDbCurve { public: AcDb3dPolyline(); ~AcDb3dPolyline(); ACDB_DECLARE_MEMBERS(AcDb3dPolyline); AcDb3dPolyline(AcDb::Poly3dType, AcGePoint3dArray& vertices, Adesk::Boolean closed = Adesk::kFalse); DBCURVE_METHODS ACDB_PORT Acad::ErrorStatus length(double &) const; ACDB_PORT Acad::ErrorStatus setClosed(Adesk::Boolean); Acad::ErrorStatus makeClosed(); Acad::ErrorStatus makeOpen(); AcDb::Poly3dType polyType() const; Acad::ErrorStatus setPolyType(AcDb::Poly3dType); Acad::ErrorStatus convertToPolyType(AcDb::Poly3dType newVal); Acad::ErrorStatus straighten(); Acad::ErrorStatus splineFit(); Acad::ErrorStatus splineFit(AcDb::Poly3dType splineType, Adesk::Int16 splineSegs); // Vertex access // Acad::ErrorStatus appendVertex(AcDb3dPolylineVertex*); Acad::ErrorStatus appendVertex(AcDbObjectId& objId, AcDb3dPolylineVertex*); Acad::ErrorStatus insertVertexAt(const AcDb3dPolylineVertex* pIndexVert, AcDb3dPolylineVertex* pNewVertex); Acad::ErrorStatus insertVertexAt(AcDbObjectId& newVertId, const AcDbObjectId& indexVertId, AcDb3dPolylineVertex* pNewVertex); Acad::ErrorStatus openVertex(AcDb3dPolylineVertex*&, AcDbObjectId vertId, AcDb::OpenMode, bool openErasedOne = false); Acad::ErrorStatus openSequenceEnd(AcDbSequenceEnd*&, AcDb::OpenMode); AcDbObjectIterator* vertexIterator() const; protected: // AcDbEntity overrides virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; inline Adesk::Boolean AcDb3dPolyline::isPeriodic () const { return Adesk::kFalse; } inline Acad::ErrorStatus AcDb3dPolyline::getStartParam(double& param) const { param = 0.0; return Acad::eOk; } inline Acad::ErrorStatus AcDb3dPolyline::extend(double newparam) { newparam; // avoid unreferenced formal parameter warning // extending a pline based on a parameter is not supported. return Acad::eNotApplicable; } class AcDbArc: public AcDbCurve { public: AcDbArc(); AcDbArc(const AcGePoint3d& center, double radius, double startAngle, double endAngle); AcDbArc(const AcGePoint3d& center, const AcGeVector3d& normal, double radius, double startAngle, double endAngle); ~AcDbArc(); ACDB_DECLARE_MEMBERS(AcDbArc); DBCURVE_METHODS AcGePoint3d center() const; Acad::ErrorStatus setCenter(const AcGePoint3d&); double radius() const; Acad::ErrorStatus setRadius(double); double startAngle() const; Acad::ErrorStatus setStartAngle(double); double endAngle() const; Acad::ErrorStatus setEndAngle(double); ACDB_PORT double totalAngle() const; ACDB_PORT double length() const; double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; inline Adesk::Boolean AcDbArc::isClosed() const { return Adesk::kFalse; } inline Adesk::Boolean AcDbArc::isPeriodic() const { return Adesk::kFalse; } inline Adesk::Boolean AcDbArc::isPlanar() const { return Adesk::kTrue; } class AcDbCircle: public AcDbCurve { public: AcDbCircle(); AcDbCircle(const AcGePoint3d& cntr, const AcGeVector3d& nrm, double radius); ~AcDbCircle(); ACDB_DECLARE_MEMBERS(AcDbCircle); DBCURVE_METHODS AcGePoint3d center() const; Acad::ErrorStatus setCenter(const AcGePoint3d&); double radius() const; Acad::ErrorStatus setRadius(double); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); double circumference() const; Acad::ErrorStatus setCircumference(double); double diameter() const; Acad::ErrorStatus setDiameter(double); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; inline Adesk::Boolean AcDbCircle::isClosed() const { return Adesk::kTrue; } inline Adesk::Boolean AcDbCircle::isPeriodic() const { return Adesk::kTrue; } inline Adesk::Boolean AcDbCircle::isPlanar () const { return Adesk::kTrue; } inline Acad::ErrorStatus AcDbCircle::getStartParam(double& p) const { p = 0.0; return Acad::eOk; } inline Acad::ErrorStatus AcDbCircle::extend(double) { return Acad::eNotApplicable; } inline Acad::ErrorStatus AcDbCircle::extend(Adesk::Boolean, const AcGePoint3d&) { return Acad::eNotApplicable; } class AcDbLine: public AcDbCurve { public: AcDbLine(); AcDbLine(const AcGePoint3d& start, const AcGePoint3d& end); ~AcDbLine(); ACDB_DECLARE_MEMBERS(AcDbLine); DBCURVE_METHODS Acad::ErrorStatus getOffsetCurvesGivenPlaneNormal( const AcGeVector3d& normal, double offsetDist, AcDbVoidPtrArray& offsetCurves) const; AcGePoint3d startPoint() const; Acad::ErrorStatus setStartPoint(const AcGePoint3d&); AcGePoint3d endPoint() const; Acad::ErrorStatus setEndPoint(const AcGePoint3d&); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; inline Adesk::Boolean AcDbLine::isClosed() const { return Adesk::kFalse; } inline Adesk::Boolean AcDbLine::isPeriodic() const { return Adesk::kFalse; } inline Adesk::Boolean AcDbLine::isPlanar() const { return Adesk::kTrue; } inline Acad::ErrorStatus AcDbLine::getStartParam(double& v1) const { v1 = 0.0; return Acad::eOk; } class AcDbPoint: public AcDbEntity { public: AcDbPoint(); AcDbPoint(const AcGePoint3d& position); ~AcDbPoint(); ACDB_DECLARE_MEMBERS(AcDbPoint); AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); double ecsRotation() const; Acad::ErrorStatus setEcsRotation(double); // AcDbEntity overrides virtual Adesk::Boolean isPlanar() const override { return Adesk::kTrue; } virtual Acad::ErrorStatus getPlane(AcGePlane&, AcDb::Planarity&) const override; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbFace: public AcDbEntity { public: AcDbFace(); AcDbFace(const AcGePoint3d& pt0, const AcGePoint3d& pt1, const AcGePoint3d& pt2, const AcGePoint3d& pt3, Adesk::Boolean e0vis = Adesk::kTrue, Adesk::Boolean e1vis = Adesk::kTrue, Adesk::Boolean e2vis = Adesk::kTrue, Adesk::Boolean e3vis = Adesk::kTrue); AcDbFace(const AcGePoint3d& pt0, const AcGePoint3d& pt1, const AcGePoint3d& pt2, Adesk::Boolean e0vis = Adesk::kTrue, Adesk::Boolean e1vis = Adesk::kTrue, Adesk::Boolean e2vis = Adesk::kTrue, Adesk::Boolean e3vis = Adesk::kTrue); ~AcDbFace(); ACDB_DECLARE_MEMBERS(AcDbFace); Acad::ErrorStatus getVertexAt(Adesk::UInt16, AcGePoint3d&) const; Acad::ErrorStatus setVertexAt(Adesk::UInt16, const AcGePoint3d&); Acad::ErrorStatus isEdgeVisibleAt(Adesk::UInt16, Adesk::Boolean&) const; Acad::ErrorStatus makeEdgeVisibleAt(Adesk::UInt16); Acad::ErrorStatus makeEdgeInvisibleAt(Adesk::UInt16); ACDB_PORT virtual Adesk::Boolean isPlanar() const override; ACDB_PORT virtual Acad::ErrorStatus getPlane(AcGePlane& plane, AcDb::Planarity& planarity) const override; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbPolyFaceMesh: public AcDbEntity { public: AcDbPolyFaceMesh(); ~AcDbPolyFaceMesh(); ACDB_DECLARE_MEMBERS(AcDbPolyFaceMesh); Adesk::Int16 numVertices() const; Adesk::Int16 numFaces() const; Acad::ErrorStatus appendVertex(AcDbPolyFaceMeshVertex*); Acad::ErrorStatus appendVertex(AcDbObjectId& objId, AcDbPolyFaceMeshVertex*); Acad::ErrorStatus appendFaceRecord(AcDbFaceRecord*); Acad::ErrorStatus appendFaceRecord(AcDbObjectId&, AcDbFaceRecord*); Acad::ErrorStatus openVertex(AcDbVertex*&, AcDbObjectId subObjId, AcDb::OpenMode, bool openErasedOne = false); Acad::ErrorStatus openSequenceEnd(AcDbSequenceEnd*&, AcDb::OpenMode); AcDbObjectIterator* vertexIterator() const; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbPolygonMesh: public AcDbEntity { public: AcDbPolygonMesh(); AcDbPolygonMesh(AcDb::PolyMeshType pType, Adesk::Int16 mSize, Adesk::Int16 nSize, const AcGePoint3dArray& vertices, Adesk::Boolean mClosed = Adesk::kTrue, Adesk::Boolean nClosed = Adesk::kTrue); ~AcDbPolygonMesh(); ACDB_DECLARE_MEMBERS(AcDbPolygonMesh); AcDb::PolyMeshType polyMeshType() const; Acad::ErrorStatus setPolyMeshType(AcDb::PolyMeshType); Acad::ErrorStatus convertToPolyMeshType(AcDb::PolyMeshType newVal); Adesk::Int16 mSize() const; Acad::ErrorStatus setMSize(Adesk::Int16); Adesk::Int16 nSize() const; Acad::ErrorStatus setNSize(Adesk::Int16); Adesk::Boolean isMClosed() const; Acad::ErrorStatus makeMClosed(); Acad::ErrorStatus makeMOpen(); Adesk::Boolean isNClosed() const; Acad::ErrorStatus makeNClosed(); Acad::ErrorStatus makeNOpen(); Adesk::Int16 mSurfaceDensity() const; Acad::ErrorStatus setMSurfaceDensity(Adesk::Int16); Adesk::Int16 nSurfaceDensity() const; Acad::ErrorStatus setNSurfaceDensity(Adesk::Int16); Acad::ErrorStatus straighten(); Acad::ErrorStatus surfaceFit(); Acad::ErrorStatus surfaceFit(AcDb::PolyMeshType surfType, Adesk::Int16 surfu, Adesk::Int16 surfv); // Vertex access // Acad::ErrorStatus appendVertex(AcDbPolygonMeshVertex*); Acad::ErrorStatus appendVertex(AcDbObjectId& objId, AcDbPolygonMeshVertex*); Acad::ErrorStatus openVertex(AcDbPolygonMeshVertex*&, AcDbObjectId vertId, AcDb::OpenMode, bool openErasedOne = false); Acad::ErrorStatus openSequenceEnd(AcDbSequenceEnd*&, AcDb::OpenMode); AcDbObjectIterator* vertexIterator() const; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbSolid: public AcDbEntity { public: AcDbSolid(); AcDbSolid(const AcGePoint3d& pt0, const AcGePoint3d& pt1, const AcGePoint3d& pt2, const AcGePoint3d& pt3); AcDbSolid(const AcGePoint3d& pt0, const AcGePoint3d& pt1, const AcGePoint3d& pt2); ~AcDbSolid(); ACDB_DECLARE_MEMBERS(AcDbSolid); Acad::ErrorStatus getPointAt(Adesk::UInt16 idx, AcGePoint3d& pntRes) const; Acad::ErrorStatus setPointAt(Adesk::UInt16 idx, const AcGePoint3d&); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); double elevation() const; void setElevation(double); protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbTrace: public AcDbEntity { public: AcDbTrace(); AcDbTrace(const AcGePoint3d& pt0, const AcGePoint3d& pt1, const AcGePoint3d& pt2, const AcGePoint3d& pt3); ~AcDbTrace(); ACDB_DECLARE_MEMBERS(AcDbTrace); // returns eInvalidIndex if index is out of range Acad::ErrorStatus getPointAt(Adesk::UInt16 idx, AcGePoint3d& PntRes) const; Acad::ErrorStatus setPointAt(Adesk::UInt16 idx, const AcGePoint3d&); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); double elevation() const; void setElevation(double); virtual Adesk::Boolean isPlanar() const override { return Adesk::kTrue; } virtual Acad::ErrorStatus getPlane(AcGePlane&, AcDb::Planarity&) const override; protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbShape: public AcDbEntity { public: AcDbShape(); AcDbShape(const AcGePoint3d& position, double size, double rotation = 0, double widthFactor = 0); ~AcDbShape(); ACDB_DECLARE_MEMBERS(AcDbShape); AcGePoint3d position() const; Acad::ErrorStatus setPosition(const AcGePoint3d&); double size() const; Acad::ErrorStatus setSize(double); ACHAR* name() const; Acad::ErrorStatus setName(const ACHAR*); double rotation() const; Acad::ErrorStatus setRotation(double); double widthFactor() const; Acad::ErrorStatus setWidthFactor(double); double oblique() const; Acad::ErrorStatus setOblique(double); double thickness() const; Acad::ErrorStatus setThickness(double); AcGeVector3d normal() const; Acad::ErrorStatus setNormal(const AcGeVector3d&); virtual Adesk::Boolean isPlanar() const override { return Adesk::kTrue; } virtual Acad::ErrorStatus getPlane(AcGePlane&, AcDb::Planarity&) const override; Adesk::Int16 shapeNumber() const; Acad::ErrorStatus setShapeNumber(Adesk::Int16); AcDbObjectId styleId() const; Acad::ErrorStatus setStyleId(AcDbObjectId id); // Obsolete names for the "shape style id" get/set methods: AcDbObjectId shapeIndex() const { return this->styleId(); } Acad::ErrorStatus setShapeIndex(AcDbObjectId id) { return this->setStyleId(id); } protected: virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; class AcDbViewport: public AcDbEntity { public: AcDbViewport(); ~AcDbViewport(); ACDB_DECLARE_MEMBERS(AcDbViewport); // view association Acad::ErrorStatus setModelView (const AcDbXrefObjectId &xrefObjId); Acad::ErrorStatus getModelView (AcDbXrefObjectId &xrefObjId) const; Acad::ErrorStatus removeModelView (void); Acad::ErrorStatus setSheetView (AcDbObjectId objId); Acad::ErrorStatus getSheetView (AcDbObjectId &objId)const; Acad::ErrorStatus removeSheetView (void); Acad::ErrorStatus setLabelBlock (AcDbObjectId objId); Acad::ErrorStatus getLabelBlock (AcDbObjectId &objId)const; Acad::ErrorStatus removeLabelBlock (void); Acad::ErrorStatus syncModelView (void); // Thumbnails #ifdef _WINDOWS_ /// <summary> /// This function provides BITMAP thumbnail of viewport as output /// </summary> /// <param name="thumbnail"> A reference to a pointer of Bitmap thumbnail, containing header and pixels </param> /// <returns> This will return Acad::eOk if thumbnail is successfully retrieved. It returns error status otherwise </returns> /// Acad::ErrorStatus getThumbnail (BITMAPINFO*& thumbnail) const; /// <summary> /// This function sets BITMAP thumbnail into viewport /// </summary> /// <param name="thumbnail"> A pointer of Bitmap thumbnail to be set into viewport </param> /// <returns> This will return Acad::eOk if thumbnail is successfully set. It returns error status otherwise </returns> /// Acad::ErrorStatus setThumbnail(const BITMAPINFO * thumbnail); /// <summary> /// This function provides Atil::Image thumbnail of viewport as output /// </summary> /// <param name="pPreviewImage"> A reference to the pointer of Atil::Image thumbnail </param> /// <returns> This will return Acad::eOk if thumbnail is successfully retrieved. It returns error status otherwise </returns> /// <remarks> Internal use only </remarks> /// Acad::ErrorStatus getPreviewImage(Atil::Image*& pPreviewImage) const; /// <summary> /// This functions sets Atil::Image thumbnail into viewport /// </summary> /// <param name="pPreviewImage"> A pointer of Atil::Image thumbnail to be set into viewport </param> /// <returns> This will return Acad::eOk if thumbnail is successfully set. It returns error status otherwise </returns> /// <remarks> Internal use only </remarks> /// Acad::ErrorStatus setPreviewImage (const Atil::Image * pPreviewImage); #endif // Set methods will return eCannotChangeActiveViewport if called // when the Viewport is currently active. double height() const; Acad::ErrorStatus setHeight(double); double width() const; Acad::ErrorStatus setWidth(double); AcGePoint3d centerPoint() const; Acad::ErrorStatus setCenterPoint(const AcGePoint3d&); Adesk::Int16 number() const; bool isOn() const; Acad::ErrorStatus setOn(); Acad::ErrorStatus setOff(); ACDB_PORT Acad::ErrorStatus setIsOn(bool bOn); AcGePoint3d viewTarget() const; Acad::ErrorStatus setViewTarget(const AcGePoint3d&); AcGeVector3d viewDirection() const; Acad::ErrorStatus setViewDirection(const AcGeVector3d&); // Model Space height, and center in Display coordinates // double viewHeight() const; Acad::ErrorStatus setViewHeight(double ht); AcGePoint2d viewCenter() const; Acad::ErrorStatus setViewCenter(const AcGePoint2d& pt); double twistAngle() const; Acad::ErrorStatus setTwistAngle(double); double lensLength() const; Acad::ErrorStatus setLensLength(double); bool isFrontClipOn() const; Acad::ErrorStatus setFrontClipOn(); Acad::ErrorStatus setFrontClipOff(); ACDB_PORT Acad::ErrorStatus setFrontClipOn(bool bOn); bool isBackClipOn() const; Acad::ErrorStatus setBackClipOn(); Acad::ErrorStatus setBackClipOff(); ACDB_PORT Acad::ErrorStatus setBackClipOn(bool bOn); bool isFrontClipAtEyeOn() const; Acad::ErrorStatus setFrontClipAtEyeOn(); Acad::ErrorStatus setFrontClipAtEyeOff(); ACDB_PORT Acad::ErrorStatus setFrontClipAtEyeOn(bool bOn); // FrontZ double frontClipDistance() const; Acad::ErrorStatus setFrontClipDistance(double newVal); // BackZ double backClipDistance() const; Acad::ErrorStatus setBackClipDistance(double newVal); bool isPerspectiveOn() const; Acad::ErrorStatus setPerspectiveOn(); Acad::ErrorStatus setPerspectiveOff(); ACDB_PORT Acad::ErrorStatus setPerspectiveOn(bool bOn); bool isUcsFollowModeOn() const; Acad::ErrorStatus setUcsFollowModeOn(); Acad::ErrorStatus setUcsFollowModeOff(); ACDB_PORT Acad::ErrorStatus setUcsFollowModeOn(bool bOn); bool isUcsIconVisible() const; Acad::ErrorStatus setUcsIconVisible(); Acad::ErrorStatus setUcsIconInvisible(); ACDB_PORT Acad::ErrorStatus setUcsIconVisible(bool ); bool isUcsIconAtOrigin() const; Acad::ErrorStatus setUcsIconAtOrigin(); Acad::ErrorStatus setUcsIconAtCorner(); ACDB_PORT Acad::ErrorStatus setUcsIconAtOrigin(bool ); bool isFastZoomOn() const { return true; } Acad::ErrorStatus setFastZoomOn() { return Acad::eOk; } Acad::ErrorStatus setFastZoomOff() { return Acad::eOk; } ACDB_PORT Acad::ErrorStatus setFastZoomOn(bool ); Adesk::UInt16 circleSides() const; Acad::ErrorStatus setCircleSides(Adesk::UInt16); bool isSnapOn() const; Acad::ErrorStatus setSnapOn(); Acad::ErrorStatus setSnapOff(); ACDB_PORT Acad::ErrorStatus setSnapOn(bool ); bool isSnapIsometric() const; Acad::ErrorStatus setSnapIsometric(); Acad::ErrorStatus setSnapStandard(); ACDB_PORT Acad::ErrorStatus setSnapIsometric(bool ); double snapAngle() const; Acad::ErrorStatus setSnapAngle(double); AcGePoint2d snapBasePoint() const; Acad::ErrorStatus setSnapBasePoint(const AcGePoint2d&); AcGeVector2d snapIncrement() const; Acad::ErrorStatus setSnapIncrement(const AcGeVector2d&); Adesk::UInt16 snapIsoPair() const; Acad::ErrorStatus setSnapIsoPair(Adesk::UInt16); bool isGridOn() const; Acad::ErrorStatus setGridOn(); Acad::ErrorStatus setGridOff(); ACDB_PORT Acad::ErrorStatus setGridOn(bool ); bool isGridBoundToLimits() const; Acad::ErrorStatus setGridBoundToLimits(bool bNewVal); bool isGridAdaptive() const; Acad::ErrorStatus setGridAdaptive(bool bNewVal); bool isGridSubdivisionRestricted() const; Acad::ErrorStatus setGridSubdivisionRestricted(bool bNewVal); bool isGridFollow() const; Acad::ErrorStatus setGridFollow(bool bNewVal); Adesk::UInt16 gridMajor() const; Acad::ErrorStatus setGridMajor(Adesk::UInt16); AcGeVector2d gridIncrement() const; Acad::ErrorStatus setGridIncrement(const AcGeVector2d&); bool hiddenLinesRemoved() const; Acad::ErrorStatus showHiddenLines(); Acad::ErrorStatus removeHiddenLines(); ACDB_PORT Acad::ErrorStatus removeHiddenLines(bool ); Acad::ErrorStatus freezeLayersInViewport(const AcDbObjectIdArray&); Acad::ErrorStatus thawLayersInViewport(const AcDbObjectIdArray&); Acad::ErrorStatus thawAllLayersInViewport(); bool isLayerFrozenInViewport(const AcDbObjectId& layerId) const; Acad::ErrorStatus getFrozenLayerList(AcDbObjectIdArray& ids) const; Acad::ErrorStatus updateDisplay() const; AcDbObjectId background() const; Acad::ErrorStatus setBackground(AcDbObjectId backgroundId); AcDbObjectId previousBackground(AcGiDrawable::DrawableType type = AcGiDrawable::kGeometry) const; Acad::ErrorStatus setPreviousBackground(AcDbObjectId backgroundId, AcGiDrawable::DrawableType type = AcGiDrawable::kGeometry); Acad::ErrorStatus setPreviousBackground(AcDbObjectId backgroundId, AcGiDrawable::DrawableType type, bool bForcedSwitch); bool previousBackgroundForcedSwitch (void) const; // Visual Styles AcDbObjectId visualStyle() const; Acad::ErrorStatus setVisualStyle(const AcDbObjectId oidVisualStyle); // Viewport Lighting // bool isDefaultLightingOn() const; Acad::ErrorStatus setDefaultLightingOn(bool on); AcGiViewportTraits::DefaultLightingType defaultLightingType() const; Acad::ErrorStatus setDefaultLightingType(AcGiViewportTraits::DefaultLightingType typ); // Brightness controls the relative intensity of lights. double brightness() const; Acad::ErrorStatus setBrightness(double); // Contrast controls intensity of ambient light, relative to other lights. double contrast() const; Acad::ErrorStatus setContrast(double); AcCmColor ambientLightColor() const; Acad::ErrorStatus setAmbientLightColor(const AcCmColor& clr); // A single sun (distant light) can be associated with each viewport. AcDbObjectId sunId() const; Acad::ErrorStatus setSun(AcDbObjectId &retId, AcDbObject *pSun); Acad::ErrorStatus setSun(AcDbObjectId &retId, AcDbObject *pSun, bool eraseOldSun); bool isLocked() const; Acad::ErrorStatus setLocked(); Acad::ErrorStatus setUnlocked(); ACDB_PORT Acad::ErrorStatus setLocked(bool ); Acad::ErrorStatus setAnnotationScale(const AcDbAnnotationScale *pScaleObj); // get current annotation scale, return a pointer to AcDbAnnotationScale, // caller is responsible for releasing the memory later AcDbAnnotationScale* annotationScale() const; bool isTransparent() const; Acad::ErrorStatus setTransparent(); Acad::ErrorStatus setOpaque(); ACDB_PORT Acad::ErrorStatus setTransparent(bool ); enum StandardScaleType { kScaleToFit, // Scaled to Fit kCustomScale, // Scale is not a standard scale k1_1, // 1:1 k1_2, // 1:2 k1_4, // 1:4 k1_5, // 1:5 k1_8, // 1:8 k1_10, // 1:10 k1_16, // 1:16 k1_20, // 1:20 k1_30, // 1:30 k1_40, // 1:40 k1_50, // 1:50 k1_100, // 1:100 k2_1, // 2:1 k4_1, // 4:1 k8_1, // 8:1 k10_1, // 10:1 k100_1, // 100:1 k1_128in_1ft, // 1/128"= 1' k1_64in_1ft, // 1/64"= 1' k1_32in_1ft, // 1/32"= 1' k1_16in_1ft, // 1/16"= 1' k3_32in_1ft, // 3/32"= 1' k1_8in_1ft, // 1/8" = 1' k3_16in_1ft, // 3/16"= 1' k1_4in_1ft, // 1/4" = 1' k3_8in_1ft, // 3/8" = 1' k1_2in_1ft, // 1/2" = 1' k3_4in_1ft, // 3/4" = 1' k1in_1ft, // 1"= 1' k1and1_2in_1ft, // 1 1/2"= 1' k3in_1ft, // 3"= 1' k6in_1ft, // 6"= 1' k1ft_1ft // 1'= 1' }; double customScale() const; Acad::ErrorStatus setCustomScale(double); StandardScaleType standardScale() const; Acad::ErrorStatus setStandardScale(const StandardScaleType); Acad::ErrorStatus plotStyleSheet(ACHAR *&) const; Acad::ErrorStatus plotStyleSheet(const ACHAR *&) const; Acad::ErrorStatus effectivePlotStyleSheet(const ACHAR *&); Acad::ErrorStatus setPlotStyleSheet(const ACHAR *); bool isNonRectClipOn() const; Acad::ErrorStatus setNonRectClipOn(); Acad::ErrorStatus setNonRectClipOff(); ACDB_PORT Acad::ErrorStatus setNonRectClipOn(bool bOn); AcDbObjectId nonRectClipEntityId() const; Acad::ErrorStatus setNonRectClipEntityId(AcDbObjectId); virtual void erased(const AcDbObject* , Adesk::Boolean) override; virtual void modified(const AcDbObject *) override; virtual void copied(const AcDbObject* pDbObj,const AcDbObject* pNewObj) override; virtual void subObjModified(const AcDbObject* pDbObj, const AcDbObject* pSubObj) override; // UCS query methods. // Acad::ErrorStatus getUcs (AcGePoint3d& origin, AcGeVector3d& xAxis, AcGeVector3d& yAxis ) const; bool isUcsOrthographic(AcDb::OrthographicView& view) const; AcDbObjectId ucsName () const; double elevation () const; // UCS set methods. // Acad::ErrorStatus setUcs(const AcGePoint3d& origin, const AcGeVector3d& xAxis, const AcGeVector3d& yAxis); Acad::ErrorStatus setUcs(AcDb::OrthographicView view); Acad::ErrorStatus setUcs(const AcDbObjectId& ucsId); Acad::ErrorStatus setUcsToWorld(); Acad::ErrorStatus setElevation(double elev ); // Orthographic view methods. // bool isViewOrthographic(AcDb::OrthographicView& view ) const; Acad::ErrorStatus setViewDirection(AcDb::OrthographicView view ); // Methods to get/set UCSVP for viewport. // bool isUcsSavedWithViewport () const; void setUcsPerViewport ( bool ucsvp ); // ShadePlot enum and get/set methods enum ShadePlotType { kAsDisplayed = 0, kWireframe = 1, kHidden = 2, kRendered = 3, kVisualStyle = 4, kRenderPreset = 5 }; ShadePlotType shadePlot() const; Acad::ErrorStatus setShadePlot(const ShadePlotType); AcDbObjectId shadePlotId() const; Acad::ErrorStatus setShadePlot(const ShadePlotType type, const AcDbObjectId shadePlotId); bool plotWireframe() const; bool plotAsRaster() const; Acad::ErrorStatus toneOperatorParameters(AcGiToneOperatorParameters& params) const; Acad::ErrorStatus setToneOperatorParameters(const AcGiToneOperatorParameters& params); protected: // AcDbEntity overrides // virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const override; }; #pragma pack(pop) #endif
[ "joshua.laskowski@web.de" ]
joshua.laskowski@web.de
f436d6daaef5db12bcab103b908e25efe516a431
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtbase/src/concurrent/doc/snippets/code/src_concurrent_qtconcurrentfilter.cpp
77233bdbf79571c98aa2cf4cdc42545aee627c2a
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-commercial-license", "LGPL-2.0-or-later", "LGPL-2.1-only", "GFDL-1.3-only", "LicenseRef-scancode-qt-commercial-1.1", "LGPL-3.0-only", "LicenseRef-scancode-qt-company-exception-lgpl-2.1", "GPL-1.0-or-later", "GPL-3.0-only", "BSD-3-Clause", "LGPL-2.1-or-later", "GPL-2.0-only", "Qt-LGPL-exception-1.1", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-generic-exception" ]
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
5,330
cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] bool function(const T &t); //! [0] //! [1] bool allLowerCase(const QString &string) { return string.lowered() == string; } QStringList strings = ...; QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings, allLowerCase); //! [1] //! [2] QStringList strings = ...; QFuture<void> future = QtConcurrent::filter(strings, allLowerCase); //! [2] //! [3] V function(T &result, const U &intermediate) //! [3] //! [4] void addToDictionary(QSet<QString> &dictionary, const QString &string) { dictionary.insert(string); } QStringList strings = ...; QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings, allLowerCase, addToDictionary); //! [4] //! [5] QStringList strings = ...; QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings.constBegin(), strings.constEnd(), allLowerCase); // filter in-place only works on non-const iterators QFuture<void> future = QtConcurrent::filter(strings.begin(), strings.end(), allLowerCase); QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings.constBegin(), strings.constEnd(), allLowerCase, addToDictionary); //! [5] //! [6] QStringList strings = ...; // each call blocks until the entire operation is finished QStringList lowerCaseStrings = QtConcurrent::blockingFiltered(strings, allLowerCase); QtConcurrent::blockingFilter(strings, allLowerCase); QSet<QString> dictionary = QtConcurrent::blockingFilteredReduced(strings, allLowerCase, addToDictionary); //! [6] //! [7] // keep only images with an alpha channel QList<QImage> images = ...; QFuture<void> alphaImages = QtConcurrent::filter(images, &QImage::hasAlphaChannel); // retrieve gray scale images QList<QImage> images = ...; QFuture<QImage> grayscaleImages = QtConcurrent::filtered(images, &QImage::isGrayscale); // create a set of all printable characters QList<QChar> characters = ...; QFuture<QSet<QChar> > set = QtConcurrent::filteredReduced(characters, &QChar::isPrint, &QSet<QChar>::insert); //! [7] //! [8] // can mix normal functions and member functions with QtConcurrent::filteredReduced() // create a dictionary of all lower cased strings extern bool allLowerCase(const QString &string); QStringList strings = ...; QFuture<QSet<int> > averageWordLength = QtConcurrent::filteredReduced(strings, allLowerCase, QSet<QString>::insert); // create a collage of all gray scale images extern void addToCollage(QImage &collage, const QImage &grayscaleImage); QList<QImage> images = ...; QFuture<QImage> collage = QtConcurrent::filteredReduced(images, &QImage::isGrayscale, addToCollage); //! [8] //! [9] bool QString::contains(const QRegExp &regexp) const; //! [9] //! [10] std::bind(&QString::contains, QRegExp("^\\S+$")); // matches strings without whitespace //! [10] //! [11] bool contains(const QString &string) //! [11] //! [12] QStringList strings = ...; std::bind(static_cast<bool(QString::*)(const QRegExp&)>( &QString::contains ), QRegExp("..." )); //! [12] //! [13] struct StartsWith { StartsWith(const QString &string) : m_string(string) { } typedef bool result_type; bool operator()(const QString &testString) { return testString.startsWith(m_string); } QString m_string; }; QList<QString> strings = ...; QFuture<QString> fooString = QtConcurrent::filtered(images, StartsWith(QLatin1String("Foo"))); //! [13]
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
0f318a143734590c6049243aeb764498daa035cc
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/071/118/CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B.cpp
e4569c47c5b2ea7a8ac7e29b6984f071fa6297e5
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,645
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml Template File: sources-sink-83_goodG2B.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator * GoodSource: Allocate enough memory for a string and the NULL terminator * Sinks: memcpy * BadSink : Copy string to data using memcpy() * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83.h" namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83 { CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B::CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B(wchar_t * dataCopy) { data = dataCopy; /* FIX: Allocate space for a null terminator */ data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); } CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B::~CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memcpy_83_goodG2B() { { wchar_t source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ memcpy(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); printWLine(data); free(data); } } } #endif /* OMITGOOD */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
c504079d910c65f2967025dfc25c662a18354b78
312075c55cce98714f83aa8e3cc291905c36d7de
/00_精通QT視窗介面程式設計/code/chapter15/schema/MsgHandler.h
401597a44b13c3c106b945bdb9c2a3724419184e
[]
no_license
jash-git/Qt_BOOK_20210504
cc356a8db08db749795b46c0c02f85375fff77b9
eb47dde3dba3e3751acaecd32e2cf8f88dc7a259
refs/heads/master
2023-04-21T05:54:08.748068
2021-05-04T08:17:19
2021-05-04T08:17:19
364,186,010
1
0
null
null
null
null
BIG5
C++
false
false
1,949
h
//----------------------------------*-C++-*------------------------------------ // 版權所有 (C) 作者獨立享有版權。 // 保留所有版權,未經授權,任何單位和個人不得擅自複製、使用本成果。 //----------------------------------------------------------------------------- // 版本號 0.01 //----------------------------------------------------------------------------- // 文件名: MsgHandler.h 類名:MsgHandler //----------------------------------------------------------------------------- // 編制說明 : //----------------------------------------------------------------------------- // 開發組:無名 // 創建人 創建時間 // 李立夏 2010-8-29 //----------------------------------------------------------------------------- // 開發組:無名 // // 修改人員 修改日期 修改內容 // // //----------------------------------------------------------------------------- #ifndef MSGHANDLER_H_ #define MSGHANDLER_H_ #include <QAbstractMessageHandler> class MsgHandler : public QAbstractMessageHandler { public: MsgHandler() : QAbstractMessageHandler(0) { } QString statusMessage() const { return m_description; } int line() const { return m_sourceLocation.line(); } int column() const { return m_sourceLocation.column(); } protected: virtual void handleMessage(QtMsgType type, const QString &description, const QUrl &identifier, const QSourceLocation &sourceLocation) { Q_UNUSED(type); Q_UNUSED(identifier); m_description = description; m_sourceLocation = sourceLocation; } private: QString m_description; QSourceLocation m_sourceLocation; }; #endif /* MSGHANDLER_H_ */
[ "gitea@fake.local" ]
gitea@fake.local
c7c38d0ceb1216472ff1e0730537876ebbda833e
cf28facb7ad9cc7eeeed780a9173ca8f98289ef5
/empery_center/src/singletons/blood_display_map.cpp
7783f8bf67ef45a467a30fe045435d3a30ee3313
[]
no_license
kspine/referance_solution
aafa5204f3ef840d281e814aa0eeb210ffcf7633
d667f7402cf951ce4784a19aa5619de80245e5f3
refs/heads/master
2021-01-22T05:16:26.760739
2017-02-10T06:41:54
2017-02-10T06:41:54
81,633,340
0
0
null
null
null
null
UTF-8
C++
false
false
2,998
cpp
#include "../precompiled.hpp" #include "blood_display_map.hpp" #include <poseidon/multi_index_map.hpp> namespace EmperyCenter { namespace { struct BloodDisplayElement { AccountUuid account_uuid; AccountUuid enemy_account_uuid; std::pair<AccountUuid,AccountUuid> fight_sides; std::uint64_t last_attack_time; std::uint64_t last_finish_display_blood_time; BloodDisplayElement(AccountUuid account_uuid,AccountUuid enemy_account_uuid, std::uint64_t last_attack_time,std::uint64_t last_finish_display_blood_time) : account_uuid(account_uuid) , enemy_account_uuid(enemy_account_uuid) , fight_sides(std::make_pair(account_uuid,enemy_account_uuid)) , last_attack_time(last_attack_time) , last_finish_display_blood_time(last_finish_display_blood_time) { } }; MULTI_INDEX_MAP(BloodDisplayInfosContainer, BloodDisplayElement, MULTI_MEMBER_INDEX(account_uuid) MULTI_MEMBER_INDEX(enemy_account_uuid) UNIQUE_MEMBER_INDEX(fight_sides) MULTI_MEMBER_INDEX(last_finish_display_blood_time) ) boost::weak_ptr<BloodDisplayInfosContainer> g_blood_display_info_map; MODULE_RAII_PRIORITY(handles, 5000){ const auto blood_display_info_map = boost::make_shared<BloodDisplayInfosContainer>(); g_blood_display_info_map = blood_display_info_map; handles.push(blood_display_info_map); } } void BloodDisplayMap::get_display_blood_time(AccountUuid account_uuid,AccountUuid enemy_uuid,std::uint64_t& last_attack_time,std::uint64_t& last_display_time){ PROFILE_ME; const auto blood_display_info_map = g_blood_display_info_map.lock(); const auto it = blood_display_info_map->find<2>(std::make_pair(account_uuid,enemy_uuid)); if(it != blood_display_info_map->end<2>()){ last_attack_time = it->last_attack_time; last_display_time = it->last_finish_display_blood_time; } } void BloodDisplayMap::update_attack_info(AccountUuid account_uuid,AccountUuid enemy_uuid,std::uint64_t last_atatack,std::uint64_t last_finish_display_blood){ PROFILE_ME; const auto blood_display_info_map = g_blood_display_info_map.lock(); if(!blood_display_info_map){ LOG_EMPERY_CENTER_WARNING("no base fight info now."); DEBUG_THROW(Exception, sslit("no base fight info now.")); } const auto utc_now = Poseidon::get_utc_time(); blood_display_info_map->erase<3>(blood_display_info_map->begin<3>(), blood_display_info_map->upper_bound<3>(utc_now)); const auto it = blood_display_info_map->find<2>(std::make_pair(account_uuid,enemy_uuid)); if(it == blood_display_info_map->end<2>()){ blood_display_info_map->insert(BloodDisplayElement(account_uuid,enemy_uuid,last_atatack,last_finish_display_blood)); }else{ std::uint64_t last_finish_time; if(0 != last_finish_display_blood){ last_finish_time = last_finish_display_blood; }else{ last_finish_time = it->last_finish_display_blood_time; } blood_display_info_map->replace<2>(it,BloodDisplayElement(account_uuid,enemy_uuid,last_atatack,last_finish_time)); } } }
[ "debian@debian" ]
debian@debian
e460cb5e99e96a0de72a8e664d63d895a4368116
4426d65ee98de1deb6e73bf23ddef29b25c1426d
/ICPC/ukiepc2020problems/familyfares/submissions/accepted/timon.cpp
bc778f6c3d129ef794f513d52c4e3b809a421d13
[]
no_license
Juantamayo26/Train
0c50f985a70bc922dddb9b13a94c8f0bf8406a96
cdf46c99db13a0ddfe55323e3a895e105dd87452
refs/heads/main
2023-06-29T13:07:25.629555
2021-08-06T21:54:41
2021-08-06T21:54:41
285,504,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,967
cpp
#include <algorithm> #include <tuple> #include <unordered_map> #include <unordered_set> #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <map> #include <set> #include <vector> #include <queue> #include <bitset> using namespace std; /* Note: this solution also works when shortest paths are not unique. */ using ll = long long; using vi = vector<ll>; using vvi = vector<vi>; struct E { int v; ll c; bool operator<(const E& o) const { return c > o.c; } }; vi dijkstra(int s, vector<vector<E>>& edges) { vi dist(edges.size(), -1); priority_queue<E> pq; pq.push({s, dist[s] = 0}); while(!pq.empty()) { int u = pq.top().v; ll d = pq.top().c; pq.pop(); if(dist[u] != d) continue; for(const auto& e : edges[u]) if(dist[e.v] == -1 || dist[e.v] > dist[u] + e.c) pq.push({e.v, dist[e.v] = dist[u] + e.c}); } return dist; } void dfs(int u, vector<vector<E>>& edges, const vvi& s, vector<bitset<100>>& pass) { for(int i : s[u]) pass[u].set(i, 1); for(const auto& e : edges[u]) dfs(e.v, edges, s, pass), pass[u] |= pass[e.v]; edges[u].clear(); } int main() { int n, m, p, g; cin >> n >> m >> p >> g; vvi s(n); for(int i = 0, vi; i < p; ++i) cin >> vi, s[vi - 1].push_back(i); vector<vector<E>> edges(n); for(int a, b, c, j = 0; j < m; ++j) cin >> a >> b >> c, --a, --b, edges[a].push_back({b, (ll)c}), edges[b].push_back({a, (ll)c}); vi dist = dijkstra(0, edges); for(int u = 0; u < n; ++u) { size_t last = 0; for(size_t i = 0; i < edges[u].size(); ++i) { E& e = edges[u][i]; if(dist[u] + e.c == dist[e.v]) swap(edges[u][i], edges[u][last]), ++last; } edges[u].erase(edges[u].begin() + last, edges[u].end()); } ll base = 0LL; for(int u = 0; u < n; ++u) base += dist[u] * s[u].size(); vector<bitset<100>> pass(n); dfs(0, edges, s, pass); ll ans = base; for(int u = 0; u < n; ++u) ans = min(ans, base + (g - dist[u]) * (ll)pass[u].count()); cout << ans << endl; }
[ "juancyepest@gmail.com" ]
juancyepest@gmail.com
6f8c951ced8e9778e9df306b8a4f999034753f46
b46b316d141587f0dd6e6e4bd2f220e085673835
/libcor/include/cor/services/mailer.hpp
9a1029c2ce9a671551617cfd02365ad0ee323e43
[]
no_license
amspina/placor-hpx
884b6dab6c814a2c3415a4b8287e8ea284090413
53aed7af6112aaf57d5a2d8bed9a40cd2822b24e
refs/heads/main
2023-03-17T21:49:21.758475
2021-03-04T16:53:20
2021-03-04T16:53:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,186
hpp
// #ifndef COR_MAILER_HPP // #define COR_MAILER_HPP // #include <thread> // #include <map> // #include <deque> // #include <queue> // #include <mutex> // #include <condition_variable> // #include "cor/utils/utils.hpp" // #include "cor/system/macros.hpp" // #include "cor/message.hpp" // namespace cor { // class Mailer // { // friend class ResourceManager; // public: // explicit Mailer(std::string const& id, std::string const& app_group); // ~Mailer(); // void SendMessage(idp_t idp, idp_t dest, Message& msg); // void SendMessage(idp_t idp, std::vector<idp_t> const& dests, Message& msg); // Message ReceiveMessage(idp_t idp); // Message ReceiveMessage(idp_t idp, idp_t source); // // Mailer(Mailer const&) = delete; // // Mailer& operator=(Mailer const&) = delete; // // Mailer(Mailer&&) = delete; // // Mailer& operator=(Mailer&&) = delete; // protected: // // accessed by ResourceManager // void CreateMailbox(idp_t idp); // void DeleteMailbox(idp_t idp); // private: // void HandleRead(); // void HandleWrite(); // void JoinGroup(std::string const& group); // void LeaveGroup(std::string const& group); // void JoinMessageGroup(idp_t idp); // void LeaveMessageGroup(idp_t idp); // std::string GetMessageGroup(idp_t idp); // idp_t GetIdpFromMessageGroup(std::string const& group); // enum class MsgType: std::int16_t // { // Message // }; // constexpr typename std::underlying_type<MsgType>::type underlying_cast(MsgType t) const noexcept // { // return static_cast<typename std::underlying_type<MsgType>::type>(t); // } // std::string _app_group; // // resources mailboxes // std::map<idp_t, std::deque<Message>> _mailboxes; // std::map<idp_t, std::condition_variable> _rwq; // std::mutex _mtx; // struct Out // { // bool ongoingWrite = false; // std::queue<std::pair<std::vector<std::string>, std::string>> q; // }; // utils::Monitor<Out> _out_queue; // // Hold the currently outgoing message // std::vector<std::string> _outgoing_groups; // std::string _outgoing_msg; // }; // } // #endif
[ "tiago.fg@outlook.com" ]
tiago.fg@outlook.com
e9a6e41e5974240093c47c07b9a715c9ae061d36
0cf2a122ab077ca8c08b48bd7416907856d73ecc
/Breeder/OSIG/TurboMachinery/ercoftacConicalDiffuser/cases/Case2.2/0_orig/U
a3aac0f4fd6830efd3c980a5459c4090d2b4bd14
[]
no_license
martinep/foam-extend-svn
f8385e9fdb30a4ebe55e64fef7dea886dac15b7b
8ab5b07166202f17acf810ef9bc7935485a5e6aa
refs/heads/master
2019-01-19T12:15:58.295577
2014-01-28T10:13:07
2014-01-28T10:13:07
16,308,391
0
1
null
null
null
null
UTF-8
C++
false
false
1,665
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 1.4.1 | | \\ / A nd | Web: http://www.openfoam.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; root ""; case ""; instance ""; local ""; class volVectorField; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField uniform (0 0 11.6); boundaryField { inlet { type fixedValue; value uniform (0 0 11.6); } outlet { type zeroGradient; } wallProlongation { type fixedValue; value uniform (0 0 0); } wallDiffuser { type fixedValue; value uniform (0 0 0); } statSwirlWall { type fixedValue; value uniform (0 0 0); } wallDump { type fixedValue; value uniform (0 0 0); } rotSwirlWall { type fixedValue; value uniform (0 0 0); } } // ************************************************************************* //
[ "Pedro" ]
Pedro
44067092edfed0bebd2e2b8323b9ca24607639d5
4cb59bab0083dfc2021865d50f608aacc70c77c5
/include/pinyin.h
43034b5a6167996daa6d6c9fa34b17ac2982b870
[ "LicenseRef-scancode-mulanpsl-1.0-en", "MulanPSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
netmankind/qucsdk
73b75b1f64ca66625ba2d4240f54d482689a4f86
54be06bc9054b4a615deda1dc40436593b5803a4
refs/heads/master
2020-08-07T16:22:10.763797
2019-10-07T13:40:30
2019-10-07T13:40:30
213,523,204
5
3
null
2019-10-08T01:39:38
2019-10-08T01:39:37
null
UTF-8
C++
false
false
1,969
h
#ifndef PINYIN_H #define PINYIN_H /** * 简体转繁体+汉字转拼音带音标类 作者:feiyangqingyun(QQ:517216493) 2019-2-16 * 1:简体繁体互相转换 * 2:汉字转拼音带音标 */ #include <QObject> #include <QStringList> #include <QMap> #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT PinYin : public QObject #else class PinYin : public QObject #endif { Q_OBJECT public: enum Format { Format_None = 0, Format_Tone = 1, Format_Number = 2 }; static PinYin *Instance(); explicit PinYin(QObject *parent = 0); private: static QScopedPointer<PinYin> self; //分别存储单个汉字的拼音,多音字的拼音,繁体与简体对照表 QMap<QString, QString> map_one, map_group, map_fanti; //从文本文件读取汉字与拼音对照表 QMap<QString, QString> getDict(const QString &fileName); public slots: //初始化 void initPath(const QString &path); void initDict(const QString &pinyin_one = "pinyin_one.txt", const QString &pinyin_group = "pinyin_group.txt", const QString &pinyin_fanti = "pinyin_fanti.txt"); //简体转繁体 QChar getFanTi(const QChar &letter); QString getFanTi(const QString &str); //繁体转简体 QChar getJianTi(const QChar &letter); QString getJianTi(const QString &str); //判断字符是否是汉字 bool isChinese(const QChar &letter); //格式化拼音显示 QStringList formatPinyin(const QString &str, const Format &format); //将单个汉字转换为相应格式的拼音 QStringList getPinYin(const QChar &letter, const Format &format); //将字符串转换成相应格式的拼音 QString getPinYin(const QString &str, const QString &separator, const Format &format); }; #endif // PINYIN_H
[ "feiyangqingyun@163.com" ]
feiyangqingyun@163.com
9f3d4454a87a89b69c680eb232c77e8be5d3579e
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/ClickHouse/2018/8/ReadBufferAIO.cpp
1b06f7e7e27c08390ed5338aa88906ab3b9b770f
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
8,934
cpp
#if defined(__linux__) #include <IO/ReadBufferAIO.h> #include <IO/AIOContextPool.h> #include <Common/ProfileEvents.h> #include <Common/Stopwatch.h> #include <Core/Defines.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <optional> namespace ProfileEvents { extern const Event FileOpen; extern const Event FileOpenFailed; extern const Event ReadBufferAIORead; extern const Event ReadBufferAIOReadBytes; } namespace CurrentMetrics { extern const Metric Read; } namespace DB { namespace ErrorCodes { extern const int FILE_DOESNT_EXIST; extern const int CANNOT_OPEN_FILE; extern const int LOGICAL_ERROR; extern const int ARGUMENT_OUT_OF_BOUND; extern const int AIO_READ_ERROR; } /// Note: an additional page is allocated that will contain the data that /// does not fit into the main buffer. ReadBufferAIO::ReadBufferAIO(const std::string & filename_, size_t buffer_size_, int flags_, char * existing_memory_) : ReadBufferFromFileBase(buffer_size_ + DEFAULT_AIO_FILE_BLOCK_SIZE, existing_memory_, DEFAULT_AIO_FILE_BLOCK_SIZE), fill_buffer(BufferWithOwnMemory<ReadBuffer>(internalBuffer().size(), nullptr, DEFAULT_AIO_FILE_BLOCK_SIZE)), filename(filename_) { ProfileEvents::increment(ProfileEvents::FileOpen); int open_flags = (flags_ == -1) ? O_RDONLY : flags_; open_flags |= O_DIRECT; fd = ::open(filename.c_str(), open_flags); if (fd == -1) { ProfileEvents::increment(ProfileEvents::FileOpenFailed); auto error_code = (errno == ENOENT) ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE; throwFromErrno("Cannot open file " + filename, error_code); } } ReadBufferAIO::~ReadBufferAIO() { if (!aio_failed) { try { (void) waitForAIOCompletion(); } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } if (fd != -1) ::close(fd); } void ReadBufferAIO::setMaxBytes(size_t max_bytes_read_) { if (is_started) throw Exception("Illegal attempt to set the maximum number of bytes to read from file " + filename, ErrorCodes::LOGICAL_ERROR); max_bytes_read = max_bytes_read_; } bool ReadBufferAIO::nextImpl() { /// If the end of the file has already been reached by calling this function, /// then the current call is wrong. if (is_eof) return false; std::optional<Stopwatch> watch; if (profile_callback) watch.emplace(clock_type); if (!is_aio) { synchronousRead(); is_aio = true; } else receive(); if (profile_callback) { ProfileInfo info; info.bytes_requested = requested_byte_count; info.bytes_read = bytes_read; info.nanoseconds = watch->elapsed(); profile_callback(info); } is_started = true; /// If the end of the file is just reached, do nothing else. if (is_eof) return true; /// Create an asynchronous request. prepare(); request.aio_lio_opcode = IOCB_CMD_PREAD; request.aio_fildes = fd; request.aio_buf = reinterpret_cast<UInt64>(buffer_begin); request.aio_nbytes = region_aligned_size; request.aio_offset = region_aligned_begin; /// Send the request. try { future_bytes_read = AIOContextPool::instance().post(request); } catch (...) { aio_failed = true; throw; } is_pending_read = true; return true; } off_t ReadBufferAIO::doSeek(off_t off, int whence) { off_t new_pos_in_file; if (whence == SEEK_SET) { if (off < 0) throw Exception("SEEK_SET underflow", ErrorCodes::ARGUMENT_OUT_OF_BOUND); new_pos_in_file = off; } else if (whence == SEEK_CUR) { if (off >= 0) { if (off > (std::numeric_limits<off_t>::max() - getPositionInFile())) throw Exception("SEEK_CUR overflow", ErrorCodes::ARGUMENT_OUT_OF_BOUND); } else if (off < -getPositionInFile()) throw Exception("SEEK_CUR underflow", ErrorCodes::ARGUMENT_OUT_OF_BOUND); new_pos_in_file = getPositionInFile() + off; } else throw Exception("ReadBufferAIO::seek expects SEEK_SET or SEEK_CUR as whence", ErrorCodes::ARGUMENT_OUT_OF_BOUND); if (new_pos_in_file != getPositionInFile()) { off_t first_read_pos_in_file = first_unread_pos_in_file - static_cast<off_t>(working_buffer.size()); if (hasPendingData() && (new_pos_in_file >= first_read_pos_in_file) && (new_pos_in_file <= first_unread_pos_in_file)) { /// Moved, but remained within the buffer. pos = working_buffer.begin() + (new_pos_in_file - first_read_pos_in_file); } else { /// Moved past the buffer. pos = working_buffer.end(); first_unread_pos_in_file = new_pos_in_file; /// We can not use the result of the current asynchronous request. skip(); } } return new_pos_in_file; } void ReadBufferAIO::synchronousRead() { CurrentMetrics::Increment metric_increment{CurrentMetrics::Read}; prepare(); bytes_read = ::pread(fd, buffer_begin, region_aligned_size, region_aligned_begin); ProfileEvents::increment(ProfileEvents::ReadBufferAIORead); ProfileEvents::increment(ProfileEvents::ReadBufferAIOReadBytes, bytes_read); finalize(); } void ReadBufferAIO::receive() { if (!waitForAIOCompletion()) return; finalize(); } void ReadBufferAIO::skip() { if (!waitForAIOCompletion()) return; is_aio = false; /// @todo I presume this assignment is redundant since waitForAIOCompletion() performs a similar one // bytes_read = future_bytes_read.get(); if ((bytes_read < 0) || (static_cast<size_t>(bytes_read) < region_left_padding)) throw Exception("Asynchronous read error on file " + filename, ErrorCodes::AIO_READ_ERROR); } bool ReadBufferAIO::waitForAIOCompletion() { if (is_eof || !is_pending_read) return false; CurrentMetrics::Increment metric_increment{CurrentMetrics::Read}; bytes_read = future_bytes_read.get(); is_pending_read = false; ProfileEvents::increment(ProfileEvents::ReadBufferAIORead); ProfileEvents::increment(ProfileEvents::ReadBufferAIOReadBytes, bytes_read); return true; } void ReadBufferAIO::prepare() { requested_byte_count = std::min(fill_buffer.internalBuffer().size() - DEFAULT_AIO_FILE_BLOCK_SIZE, max_bytes_read); /// Region of the disk from which we want to read data. const off_t region_begin = first_unread_pos_in_file; if ((requested_byte_count > std::numeric_limits<off_t>::max()) || (first_unread_pos_in_file > (std::numeric_limits<off_t>::max() - static_cast<off_t>(requested_byte_count)))) throw Exception("An overflow occurred during file operation", ErrorCodes::LOGICAL_ERROR); const off_t region_end = first_unread_pos_in_file + requested_byte_count; /// The aligned region of the disk from which we will read the data. region_left_padding = region_begin % DEFAULT_AIO_FILE_BLOCK_SIZE; const size_t region_right_padding = (DEFAULT_AIO_FILE_BLOCK_SIZE - (region_end % DEFAULT_AIO_FILE_BLOCK_SIZE)) % DEFAULT_AIO_FILE_BLOCK_SIZE; region_aligned_begin = region_begin - region_left_padding; if (region_end > (std::numeric_limits<off_t>::max() - static_cast<off_t>(region_right_padding))) throw Exception("An overflow occurred during file operation", ErrorCodes::LOGICAL_ERROR); const off_t region_aligned_end = region_end + region_right_padding; region_aligned_size = region_aligned_end - region_aligned_begin; buffer_begin = fill_buffer.internalBuffer().begin(); } void ReadBufferAIO::finalize() { if ((bytes_read < 0) || (static_cast<size_t>(bytes_read) < region_left_padding)) throw Exception("Asynchronous read error on file " + filename, ErrorCodes::AIO_READ_ERROR); /// Ignore redundant bytes on the left. bytes_read -= region_left_padding; /// Ignore redundant bytes on the right. bytes_read = std::min(static_cast<off_t>(bytes_read), static_cast<off_t>(requested_byte_count)); if (bytes_read > 0) fill_buffer.buffer().resize(region_left_padding + bytes_read); if (static_cast<size_t>(bytes_read) < requested_byte_count) is_eof = true; if (first_unread_pos_in_file > (std::numeric_limits<off_t>::max() - bytes_read)) throw Exception("An overflow occurred during file operation", ErrorCodes::LOGICAL_ERROR); first_unread_pos_in_file += bytes_read; total_bytes_read += bytes_read; working_buffer_offset = region_left_padding; if (total_bytes_read == max_bytes_read) is_eof = true; /// Swap the main and duplicate buffers. swap(fill_buffer); } } #endif
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
49794b6fb74d77575d5cceb44341631d691e46b7
7fb63e0c17170acc21f93958eeb55bf4296d371f
/AtCoder/abc035_b.cpp
d7bd65a264e048dbdc586683eddd563ba42d5c0f
[]
no_license
yysskk/Training
4fafa2aafaaf63bf2feadf61a946369ce73392a6
37d2bb144459530d408c0404587cba6c1afe32a8
refs/heads/master
2021-07-10T08:12:17.263522
2020-07-29T05:47:08
2020-07-29T05:47:08
177,987,943
0
0
null
null
null
null
UTF-8
C++
false
false
2,003
cpp
// SeeAlso: #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef pair<int,int> pii; typedef pair<ll,ll> pll; #define MAX 100000 #define NIL -1 #define MOD 1000000007 typedef int _loop_int; #define rep(i,n) for(int i = 0; i < n; i++) #define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i) #define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i) #define debug(x) cout<<#x<<": "<<x<<endl #define debig_vec(v) cout<<#v<<":";rep(i,v.size())cout<<" "<<v[i];cout<<endl #define ALL(a) (a).begin(),(a).end() // 最大公約数 inline constexpr ll gcd(ll a,ll b){if(!a||!b)return 0;while(b){ll c=b;b=a%b;a=c;}return a;} // 最小公倍数 inline constexpr ll lcm(ll a,ll b){if(!a||!b)return 0;return a*b/gcd(a,b);} #define print2D(h, w, arr) rep(i, h) { rep(j, w) cout << arr[i][j] << " "; cout << endl; } template<class T> inline void print(const T& x){cout << setprecision(12) << x << endl;} template<class T, class... A> inline void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } const long long INF = 1LL<<60; int main() { string s; int t; cin >> s; cin >> t; ll x =0; ll y = 0; ll q = 0; rep(i, s.size()) { if (s[i]=='?') { q++; continue; } if(s[i]=='L') { x--; } else if(s[i]=='R') { x++; } else if(s[i]=='U') { y++; } else if(s[i]=='D') { y--; } } ll ans = 0; if(t==1) { ans = abs(x) + abs(y) + q; print(ans); } else if(t==2) { ll t1 = s.size()%2; ll t2 = abs(x)+abs(y)-q; ans = max(t1, t2); print(ans); } return 0; }
[ "yusuke.0213@gmail.com" ]
yusuke.0213@gmail.com
28937a35ccf3bf7d5bc1b9514c54faef7fea727e
0b910d84dd7ba5fe7e2679a146f26013682dabd2
/semester-2/14/src/rbtree.hpp
16f4873ebc5a3d50ecdfa0e34f3143cb9879e7fa
[]
no_license
diwww/algorithms-hse
82168c04a08db2c5b31785c2f7d793824d80a637
49b0e3d33e3aae19eeeb6b832cbe8dc6ca10d473
refs/heads/master
2020-12-03T02:32:02.588560
2017-07-01T08:52:12
2017-07-01T08:52:12
95,952,491
2
1
null
null
null
null
UTF-8
C++
false
false
9,793
hpp
//////////////////////////////////////////////////////////////////////////////// /// \file /// \brief Реализация классов красно-черного дерева /// \author Sergey Shershakov /// \version 0.1.0 /// \date 01.05.2017 /// This is a part of the course "Algorithms and Data Structures" /// provided by the School of Software Engineering of the Faculty /// of Computer Science at the Higher School of Economics. /// /// "Реализация" (шаблонов) методов, описанных в файле rbtree.h /// //////////////////////////////////////////////////////////////////////////////// #include <stdexcept> namespace xi { //============================================================================== // class RBTree::node //============================================================================== template<typename Element, typename Compar> RBTree<Element, Compar>::Node::~Node() { if (_left) delete _left; if (_right) delete _right; } template<typename Element, typename Compar> typename RBTree<Element, Compar>::Node* RBTree<Element, Compar>::Node::setLeft(Node* lf) { // предупреждаем повторное присвоение if (_left == lf) return nullptr; // если новый левый — действительный элемент if (lf) { // если у него был родитель if (lf->_parent) { // ищем у родителя, кем был этот элемент, и вместо него ставим бублик if (lf->_parent->_left == lf) lf->_parent->_left = nullptr; else // доп. не проверяем, что он был правым, иначе нарушение целостности lf->_parent->_right = nullptr; } // задаем нового родителя lf->_parent = this; } // если у текущего уже был один левый — отменяем его родительскую связь и вернем его Node* prevLeft = _left; _left = lf; if (prevLeft) prevLeft->_parent = nullptr; return prevLeft; } template<typename Element, typename Compar> typename RBTree<Element, Compar>::Node* RBTree<Element, Compar>::Node::setRight(Node* rg) { // предупреждаем повторное присвоение if (_right == rg) return nullptr; // если новый правый — действительный элемент if (rg) { // если у него был родитель if (rg->_parent) { // ищем у родителя, кем был этот элемент, и вместо него ставим бублик if (rg->_parent->_left == rg) rg->_parent->_left = nullptr; else // доп. не проверяем, что он был правым, иначе нарушение целостности rg->_parent->_right = nullptr; } // задаем нового родителя rg->_parent = this; } // если у текущего уже был один левый — отменяем его родительскую связь и вернем его Node* prevRight = _right; _right = rg; if (prevRight) prevRight->_parent = nullptr; return prevRight; } //============================================================================== // class RBTree //============================================================================== template<typename Element, typename Compar> RBTree<Element, Compar>::RBTree() { _root = nullptr; _dumper = nullptr; } template<typename Element, typename Compar> RBTree<Element, Compar>::~RBTree() { // грохаем пока что всех через корень if (_root) delete _root; } template<typename Element, typename Compar> void RBTree<Element, Compar>::deleteNode(Node* nd) { // если переданный узел не существует, просто ничего не делаем, т.к. в вызывающем проверок нет if (nd == nullptr) return; // потомков убьет в деструкторе delete nd; } template<typename Element, typename Compar> void RBTree<Element, Compar>::insert(const Element& key) { // этот метод можно оставить студентам целиком Node* newNode = insertNewBstEl(key); // отладочное событие if (_dumper) _dumper->rbTreeEvent(IRBTreeDumper<Element, Compar>::DE_AFTER_BST_INS, this, newNode); rebalance(newNode); // отладочное событие if (_dumper) _dumper->rbTreeEvent(IRBTreeDumper<Element, Compar>::DE_AFTER_INSERT, this, newNode); } template<typename Element, typename Compar> const typename RBTree<Element, Compar>::Node* RBTree<Element, Compar>::find(const Element& key) { Node* temp = _root; while (temp) { if (key < temp->_key) temp = temp->_left; else if (key > temp->_key) temp = temp->_right; else return temp; } return nullptr; } template<typename Element, typename Compar> typename RBTree<Element, Compar>::Node* RBTree<Element, Compar>::insertNewBstEl(const Element& key) { Node* toInsert = new Node(key); // Node to insert Node* temp = _root; // Start traversing from root Node* tempParent = nullptr; // Parent of temp (to remember previous node before NIL) while (temp) { tempParent = temp; if (toInsert->_key < temp->_key) temp = temp->_left; else if (toInsert->_key > temp->_key) temp = temp->_right; else throw std::invalid_argument("Equal keys."); } toInsert->_parent = tempParent; if (!tempParent) // If tree is empty _root = toInsert; else if (toInsert->_key < tempParent->_key) tempParent->_left = toInsert; else tempParent->_right = toInsert; toInsert->_color = RED; return toInsert; } template<typename Element, typename Compar> typename RBTree<Element, Compar>::Node* RBTree<Element, Compar>::rebalanceDUG(Node* nd) { // TODO: этот метод студенты могут оставить и реализовать при декомпозиции балансировки дерева } template<typename Element, typename Compar> void RBTree<Element, Compar>::rebalance(Node* nd) { Node* y = nullptr; // Uncle while (nd->_parent && nd->_parent->_color == RED) { if (nd->_parent->isLeftChild()) { y = nd->_parent->_parent->_right; if (y && y->_color == RED) { nd->_parent->_color = BLACK; y->_color = BLACK; nd->_parent->_parent->_color = RED; nd = nd->_parent->_parent; } else { if (nd->isRightChild()) { nd = nd->_parent; rotLeft(nd); } nd->_parent->_color = BLACK; nd->_parent->_parent->_color = RED; rotRight(nd->_parent->_parent); } } else if (nd->_parent->isRightChild()) { y = nd->_parent->_parent->_left; if (y && y->_color == RED) { y->_color = BLACK; nd->_parent->_color = BLACK; nd->_parent->_parent->_color = RED; nd = nd->_parent->_parent; } else { if (nd->isLeftChild()) { nd = nd->_parent; rotRight(nd); } nd->_parent->_color = BLACK; nd->_parent->_parent->_color = RED; rotLeft(nd->_parent->_parent); } } } _root->_color = BLACK; } template<typename Element, typename Compar> void RBTree<Element, Compar>::rotLeft(typename RBTree<Element, Compar>::Node* nd) { // Right child Node* y = nd->_right; if (!y) throw std::invalid_argument("Can't rotate left since the right child is nil"); if (nd->isLeftChild()) nd->_parent->setLeft(y); else if (nd->isRightChild()) nd->_parent->setRight(y); else _root = y; nd->setRight(y->_left); y->setLeft(nd); if (_dumper) _dumper->rbTreeEvent(IRBTreeDumper<Element, Compar>::DE_AFTER_LROT, this, nd); } template<typename Element, typename Compar> void RBTree<Element, Compar>::rotRight(typename RBTree<Element, Compar>::Node* nd) { Node* y = nd->_left; if (!y) throw std::invalid_argument("Can't rotate right since the left child is nil"); if (nd->isLeftChild()) nd->_parent->setLeft(y); else if (nd->isRightChild()) nd->_parent->setRight(y); else _root = y; nd->setLeft(y->_right); y->setRight(nd); if (_dumper) _dumper->rbTreeEvent(IRBTreeDumper<Element, Compar>::DE_AFTER_RROT, this, nd); } } // namespace xi
[ "realitybelieves@gmail.com" ]
realitybelieves@gmail.com
4a4d45a5a2a09cee83a0216477962b847ddad266
8476389f906d9661b9beee3594c52f34d21b380a
/HW1/VirtualFunction/AnimalClient.cpp
cab81c115abb8ea0777e2a87cc2ef9dc32dff6fc
[]
no_license
azodi002/CS542-Design-Patterns-Object-Oriented-Analysis
f38df9a7667098199297112643de77f4cfa26cf6
e6d659534826e2e6ae0847f2c3aa91a5dd3bab48
refs/heads/master
2020-05-23T10:08:11.632741
2017-05-19T07:00:15
2017-05-19T07:00:15
80,390,658
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
/******************************************* Name: Omid Azodi Class: CS542 Date: 02/06/2017 Professor: Dr. Ye File Name: AnimalClient.cpp *******************************************/ #include "Cat.h" #include "Dog.h" //animalID enumeration used for index of static array of Animal Pointers enum animalID { firstAnimal, secondAnimal, thirdAnimal }; int main(int argc, char* argv[]) { const int MAX_ANIMAL = 3; //Array of size 3, consisting of Animal* Animal* animalList[MAX_ANIMAL]; animalList[firstAnimal] = new Dog; animalList[secondAnimal] = new Cat; animalList[thirdAnimal] = new Dog; //Go through each element in Animal* array and call Speak & Jump methods for (int animalIterator = 0; animalIterator < MAX_ANIMAL; ++animalIterator) { cout << endl; animalList[animalIterator]->Speak(); animalList[animalIterator]->Jump(); } return 0; }
[ "noreply@github.com" ]
azodi002.noreply@github.com
dcaf745ce2bf38bade44edbc50723bcd7cdddc2d
f00687b9f8671496f417672aaf8ddffc2fa8060a
/csacademy/round-40/move-the-bishop.cpp
f1addaf1695bbfd66731e476d4f0212677e9a127
[]
no_license
kazi-nayeem/Programming-Problems-Solutions
29c338085f1025b2545ff66bdb0476ec4d7773c2
7ee29a4e06e9841388389be5566db34fbdda8f7c
refs/heads/master
2023-02-05T15:06:50.355903
2020-12-30T10:19:54
2020-12-30T10:19:54
279,388,214
2
2
null
null
null
null
UTF-8
C++
false
false
5,173
cpp
#include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> //#include <bits/stdc++.h> using namespace std; #define HI printf("HI\n") #define sf scanf #define pf printf #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define sf4(a,b,c,d) scanf("%d %d %d %d",&a,&b,&c,&d) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define sf4ll(a,b,c,d) scanf("%lld %lld %lld %lld",&a,&b,&c,&d) #define forln(i,a,n) for(int i=a ; i<n ; i++) #define foren(i,a,n) for(int i=a ; i<=n ; i++) #define forg0(i,a,n) for(int i=a ; i>n ; i--) #define fore0(i,a,n) for(int i=a ; i>=n ; i--) #define pb push_back #define ppb pop_back #define ppf push_front #define popf pop_front #define ll long long int #define ui unsigned int #define ull unsigned long long #define fs first #define sc second #define clr( a, b ) memset((a),b,sizeof(a)) #define jora pair<int, int> #define jora_d pair<double, double> #define jora_ll pair<long long int, long long int> #define mp make_pair #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define PI acos(0.0) #define wait system("pause") #define ps pf("PASS\n") #define popc(a) (__builtin_popcount(a)) template<class T1> void deb(T1 e1) { cout<<e1<<endl; } template<class T1,class T2> void deb(T1 e1,T2 e2) { cout<<e1<<" "<<e2<<endl; } template<class T1,class T2,class T3> void deb(T1 e1,T2 e2,T3 e3) { cout<<e1<<" "<<e2<<" "<<e3<<endl; } template<class T1,class T2,class T3,class T4> void deb(T1 e1,T2 e2,T3 e3,T4 e4) { cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<endl; } template<class T1,class T2,class T3,class T4,class T5> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5) { cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<endl; } template<class T1,class T2,class T3,class T4,class T5,class T6> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5,T6 e6) { cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<" "<<e6<<endl; } /// <--------------------------- For Bitmasking --------------------------------> int on( int n, int pos ){ return n = n|( 1<<pos ); } bool check( int n, int pos ){ return (bool)( n&( 1<<pos ) ); } //int off( int n, int pos ){ // return n = n&~( 1<<pos ); //} //int toggle( int n, int pos ){ // return n = n^(1<<pos); //} //int count_bit( int n ){ // return __builtin_popcount( n ); //} /// <--------------------------- End of Bitmasking --------------------------------> /// <--------------------------- For B - Base Number System -----------------------------------> //int base; //int pw[10]; //void calPow(int b){ // base = b; // pw[0] = 1; // for( int i = 1; i<10; i++ ){ // pw[i] = pw[i-1]*base; // } //} //int getV(int mask, int pos){ // mask /= pw[pos]; // return ( mask%base ); //} //int setV(int mask, int v, int pos){ // int rem = mask%pw[pos]; // mask /= pw[pos+1]; // mask = ( mask*base ) + v; // mask = ( mask*pw[pos] ) + rem; // return mask; //} /// <--------------------------- End B - Base Number System -----------------------------------> // moves //int dx[]= {0,0,1,-1};/*4 side move*/ //int dy[]= {-1,1,0,0};/*4 side move*/ //int dx[]= {1,1,0,-1,-1,-1,0,1};/*8 side move*/ //int dy[]= {0,1,1,1,0,-1,-1,-1};/*8 side move*/ //int dx[]={1,1,2,2,-1,-1,-2,-2};/*night move*/ //int dy[]={2,-2,1,-1,2,-2,1,-1};/*night move*/ //double Expo(double n, int p) { // if (p == 0)return 1; // double x = Expo(n, p >> 1); // x = (x * x); // return ((p & 1) ? (x * n) : x); //} //ll bigmod(ll a,ll b,ll m){if(b == 0) return 1%m;ll x = bigmod(a,b/2,m);x = (x * x) % m;if(b % 2 == 1) x = (x * a) % m;return x;} //ll BigMod(ll B,ll P,ll M){ ll R=1%M; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;} /// (B^P)%M typedef pair<int,int> pii; typedef pair<ll,ll> pll; #define MXN 50 #define MXE #define MXQ #define SZE #define MOD #define EPS #define INF 100000000 #define MX 100005 #define inf 100000000 int main() { // freopen("input.txt", "r", stdin); int r1, c1, r2, c2; scanf("%d %d %d %d", &r1, &c1, &r2, &c2); int ans = 2; if(r1 == r2 && c1 == c2) { ans = 0; } else if(abs(r1-r2) == abs(c1-c2)) { ans = 1; }else if(abs(r1-r2)%2 != abs(c1-c2)%2) { ans = -1; } printf("%d\n", ans); return 0;; }
[ "masum.nayeem@gmail.com" ]
masum.nayeem@gmail.com
d0aa73f05578ee28c9d1cebfc62b62549300d60c
e140c1c7087d6a4e130ebde2ce7962c40ee7fd0c
/codeforces/455/A.cpp
e629717a7d7a109a5bbcb698605e4ebbcfd7d923
[]
no_license
diptayan2k/CP-Submissions
543ccf94b4d43b6f040f975ccce834e883a5efc7
dc32f1dd474cf250f71795f991132f3d52cc1771
refs/heads/master
2023-02-05T15:26:51.480986
2018-07-03T14:25:00
2020-12-21T10:20:15
323,290,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,162
cpp
#include <iostream> #include<bits/stdc++.h> #define ll long long int #define lld long double #define F first #define S second #define f(i,a,b) for(int i=a;i<=b;i++) #define g(i,a,b) for(int i=a;i>=b;i--) #define mp make_pair #define pb push_back #define mh make_heap #define ph push_heap #define pq priority_queue #define bits(x) __builtin_popcountll(x) #define op(x) cout<<"Case #"<<x<<": " #define op1(x) cout<<"Scenario #"<<x<<": " using namespace std; const ll mod = 1000000007; const ll INF = 1e18; const int N = 21; ll a[100001]; ll n; ll m[100001] = {0}; ll dp[100001] = {0}; void solve(int t) { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; m[a[i]]++; } for (int i = 1; i <= 100000; i++) { if (m[i] > 0) { dp[i] = max(dp[i - 1], (m[i] * i + ((i > 2) ? dp[i - 2] : 0))); } else { dp[i] = dp[i - 1]; } //cout << dp[i] << " "; } cout << dp[100000]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t = 1; //cin >> t; for (int i = 1; i <= t; i++) { solve(i); } }
[ "diptayan2k@gmail.com" ]
diptayan2k@gmail.com
2aa342bda086ec089d5d725266fd8270e7856d72
658723dce4a7671115f05d2c5ec3bc167f5c78c2
/netalarm.cpp
6914c71d9e1a02a6e313acbd1b5c63edcf8ee5ac
[]
no_license
hdo/netalarm
6498845650a48803ed9c69378ca6b18ce39361c5
4363658141a7791c08473e1579c41dfa4538c0c3
refs/heads/master
2021-01-20T00:33:38.563495
2017-04-23T14:54:38
2017-04-23T14:54:38
89,149,777
3
0
null
null
null
null
UTF-8
C++
false
false
4,184
cpp
//============================================================================ // Name : main.cpp // Author : Huy Do (huydo1@gmail.com) // Version : 2017-04-22 // Description : Net Alarm Test for DAHUA NVR //============================================================================ #include <iostream> #include <unistd.h> // for sleep #include <string> #include "dhnetsdk.h" using namespace std; LLONG m_lLoginHandle; void CALLBACK DisConnectFunc(LLONG lLoginID, char *pchDVRIP, LONG nDVRPort, LDWORD dwUser) { cout << "Callback DisConnect" << endl; return; } void init() { cout << "init" << endl; bool success = CLIENT_Init(DisConnectFunc, (LDWORD) 0); if (success) { cout << "init ok" << endl; } else { cout << "init failed" << endl; } } bool login(string destip, long port, string username, string password) { cout << "login" << endl; int error = 0; NET_DEVICEINFO deviceInfo = {0}; m_lLoginHandle = CLIENT_Login(destip.c_str(), port, username.c_str(), password.c_str(), &deviceInfo, &error); if(m_lLoginHandle == 0) { if(error != 255) { cout << "login failed with code " << error << endl; } else { cout << "login also failed" << endl; } return false; } else { cout << "login ok" << endl; return true; } } void logout() { cout << "logout" << endl; bool success = CLIENT_Logout(m_lLoginHandle); if(success) { cout << "logout ok" << endl; } else { cout << "logout failed" << endl; } } void triggerAlarm(int alarmIndex, int action) { if (action > 1) { cout << "invalid action" << endl; return; } cout << "trigger alarm: " << alarmIndex << " -> " << action << endl; if(0 != m_lLoginHandle) { ALARMCTRL_PARAM alarmParam = {0}; alarmParam.dwSize = sizeof(ALARMCTRL_PARAM); alarmParam.nAlarmNo = alarmIndex; alarmParam.nAction = action; BOOL bSuccess = CLIENT_ControlDevice(m_lLoginHandle, DH_TRIGGER_ALARM_IN, &alarmParam); if(bSuccess) { cout << "ok" << endl; } else { cout << "failed" << endl; } } else { cout << "invalid login" << endl; } } void alarmInStart(int alarmIndex) { cout << "alarm start" << endl; if(0 != m_lLoginHandle) { ALARMCTRL_PARAM alarmParam = {0}; alarmParam.dwSize = sizeof(ALARMCTRL_PARAM); alarmParam.nAction = 1; alarmParam.nAlarmNo = alarmIndex; BOOL bSuccess = CLIENT_ControlDevice(m_lLoginHandle, DH_TRIGGER_ALARM_IN, &alarmParam); if(bSuccess) { cout << "ok" << endl; } else { cout << "failed" << endl; } } else { cout << "invalid login" << endl; } } void alarmInStop() { cout << "alarm stop" << endl; if(0 != m_lLoginHandle) { ALARMCTRL_PARAM alarmParam = {0}; alarmParam.dwSize = sizeof(ALARMCTRL_PARAM); alarmParam.nAction = 0; alarmParam.nAlarmNo = 0; BOOL bSuccess = CLIENT_ControlDevice(m_lLoginHandle, DH_TRIGGER_ALARM_IN, &alarmParam); if(bSuccess) { cout << "ok" << endl; } else { cout << "failed" << endl; } } else { cout << "invalid login" << endl; } } int main(int argc, char* argv[]) { cout << "Dahua Net Alarm Test" << endl; if (argc != 6) { cout << "Usage: netalarm <host ip> <port> <username> <password> <alarm channel>" << endl; return 1; } init(); bool log_ok = login(argv[1], std::stol(argv[2]), argv[3], argv[4]); if (!log_ok) { return 2; } int alarmIndex = std::stoi(argv[5]); triggerAlarm(alarmIndex, 1); sleep(2); triggerAlarm(alarmIndex, 0); logout(); return 0; }
[ "huydo1@gmail.com" ]
huydo1@gmail.com
ddd51155fdb7363a44a8609939d2bce65d771fff
cc638087906ce8a621fe671ef7b808a383d46a8b
/ribllvmedaq/TVMELink.h
b3afe1451b4ca16d03090880e123ce7307710763
[]
no_license
shuxianghuafu/ribll
8f388777a9b8e8f6f0ad7a5f609e3497841ae8cf
6f8f45e77b8d819255ce48628b5f15ba34a93ce0
refs/heads/master
2021-06-22T05:36:00.650449
2017-06-20T02:07:30
2017-06-20T02:07:30
93,241,611
0
0
null
null
null
null
UTF-8
C++
false
false
2,006
h
////////////////////////////////////////////////////////// // TVMELink.h include file interfaces // TVME class interface: V2718 manager // These classes define the DAQ hardware configuration // E.d.F (08/2007) test version v.07 // (Modified by Han jianlong 07/2012) // caen lib wrapper not yet implemented ///////////////////////////////////////////////////////// // The Caen bridge V2718 class #ifndef TVMELink_H #define TVMELink_H #include <map> #include "caenacq.h" #include "CAENVMEtypes.h" using namespace std; class TVMELink { protected: int fHandle; // V2718 handle char fHwrel[32]; // V2718 hardware release number char fSwrel[32]; // V2718 software release number CVErrorCodes fStatus; // V2718 error codes CVBoardTypes fControlBoardType; // V2718 board type short fPCILinkNum; // V2718 PCI device short fVMEControlBoardNum; // V2718 VME-PCI link int fCrate; // virtual crate number associated with V2718 public: static map<int, int> flookup_ind; //map crate-handle corrispondence public: TVMELink(CVBoardTypes ControlBoardType=cvV2718, short PCILinkNum=0, short VMEControlBoardNum=0, int crate=1); TVMELink(TVMELink const &source); virtual ~TVMELink(); void SetCrateNum(int crate) {fCrate=crate;} long GetHandle() {return fHandle;} int GetCrateNum() {return fCrate;} short GetDevice() {return fPCILinkNum;} short GetLink() {return fVMEControlBoardNum;} char *GetHWRel() {return fHwrel;} char *GetSWRel() {return fSwrel;} int Init(); CVErrorCodes EndVMEHandle(); void copy(TVMELink const &source); CVErrorCodes InitIOPort(CVOutputSelect, CVIOPolarity, CVLEDPolarity); CVErrorCodes SetIOPort(CVOutputRegisterBits cvbit); //level up CVErrorCodes ClearIOPort(CVOutputRegisterBits cvbit); //level down CVErrorCodes PulseOutput(CVOutputRegisterBits cvbit); //generate a pulse }; #endif //#ifndef TVMELink_H
[ "xiaohaijin@outlook.com" ]
xiaohaijin@outlook.com
c8737328d01dcb92ecfa2653c60e99dfbd5aa765
1a76cdf3b8776c238f0fecaca9c9491145106ec6
/SDK/FN_OptionsMenuSlider_Light_functions.cpp
0b0365285708f67d55d18938f09765b3f68dc9de
[]
no_license
JimmyJones97/aasd
9af6e9c83eec4d1b4c76c601c2ccba814ce8a1c0
1961458db5ef577e6f013ca9ea744dcd48f2b4ad
refs/heads/master
2022-02-19T11:47:42.191429
2017-10-27T11:59:07
2017-10-27T11:59:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,158
cpp
// Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.Center on Widget // (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent) void UOptionsMenuSlider_Light_C::Center_on_Widget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x990f29f9); UOptionsMenuSlider_Light_C_Center_on_Widget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.Update Slider // (FUNC_Public, FUNC_HasDefaults, FUNC_BlueprintCallable, FUNC_BlueprintEvent) // Parameters: // struct FText Slider_Text (CPF_Parm) // float Slider_Value (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) // struct FText Hover_Text (CPF_Parm) // class UCommonTextBlock* Tooltip_Text_Block (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) void UOptionsMenuSlider_Light_C::Update_Slider(const struct FText& Slider_Text, float Slider_Value, const struct FText& Hover_Text, class UCommonTextBlock* Tooltip_Text_Block) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0xadd23397); UOptionsMenuSlider_Light_C_Update_Slider_Params params; params.Slider_Text = Slider_Text; params.Slider_Value = Slider_Value; params.Hover_Text = Hover_Text; params.Tooltip_Text_Block = Tooltip_Text_Block; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.Construct // (FUNC_BlueprintCosmetic, FUNC_Event, FUNC_Public, FUNC_BlueprintEvent) void UOptionsMenuSlider_Light_C::Construct() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0xa4a5cb52); UOptionsMenuSlider_Light_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.OnMouseLeave // (FUNC_BlueprintCosmetic, FUNC_Event, FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintEvent) // Parameters: // struct FPointerEvent* MouseEvent (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm) void UOptionsMenuSlider_Light_C::OnMouseLeave(struct FPointerEvent* MouseEvent) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0xe74f6816); UOptionsMenuSlider_Light_C_OnMouseLeave_Params params; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.OnMouseEnter // (FUNC_BlueprintCosmetic, FUNC_Event, FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (CPF_Parm, CPF_IsPlainOldData) // struct FPointerEvent* MouseEvent (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm) void UOptionsMenuSlider_Light_C::OnMouseEnter(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x7ca3a589); UOptionsMenuSlider_Light_C_OnMouseEnter_Params params; params.MyGeometry = MyGeometry; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.BndEvt__MenuSlider_K2Node_ComponentBoundEvent_86_OnMouseCaptureEndEvent__DelegateSignature // (FUNC_BlueprintEvent) void UOptionsMenuSlider_Light_C::BndEvt__MenuSlider_K2Node_ComponentBoundEvent_86_OnMouseCaptureEndEvent__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x4120db0a); UOptionsMenuSlider_Light_C_BndEvt__MenuSlider_K2Node_ComponentBoundEvent_86_OnMouseCaptureEndEvent__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.BndEvt__MenuSlider_K2Node_ComponentBoundEvent_107_OnControllerCaptureEndEvent__DelegateSignature // (FUNC_BlueprintEvent) void UOptionsMenuSlider_Light_C::BndEvt__MenuSlider_K2Node_ComponentBoundEvent_107_OnControllerCaptureEndEvent__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0xa179fc03); UOptionsMenuSlider_Light_C_BndEvt__MenuSlider_K2Node_ComponentBoundEvent_107_OnControllerCaptureEndEvent__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.BndEvt__MenuSlider_K2Node_ComponentBoundEvent_124_OnFloatValueChangedEvent__DelegateSignature // (FUNC_BlueprintEvent) // Parameters: // float Value (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) void UOptionsMenuSlider_Light_C::BndEvt__MenuSlider_K2Node_ComponentBoundEvent_124_OnFloatValueChangedEvent__DelegateSignature(float Value) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0xd733f56e); UOptionsMenuSlider_Light_C_BndEvt__MenuSlider_K2Node_ComponentBoundEvent_124_OnFloatValueChangedEvent__DelegateSignature_Params params; params.Value = Value; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.BndEvt__MenuSlider_K2Node_ComponentBoundEvent_9_OnFloatValueChangedEvent__DelegateSignature // (FUNC_BlueprintEvent) // Parameters: // float Value (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) void UOptionsMenuSlider_Light_C::BndEvt__MenuSlider_K2Node_ComponentBoundEvent_9_OnFloatValueChangedEvent__DelegateSignature(float Value) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x1a6965c); UOptionsMenuSlider_Light_C_BndEvt__MenuSlider_K2Node_ComponentBoundEvent_9_OnFloatValueChangedEvent__DelegateSignature_Params params; params.Value = Value; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.ExecuteUbergraph_OptionsMenuSlider_Light // (FUNC_HasDefaults) // Parameters: // int EntryPoint (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) void UOptionsMenuSlider_Light_C::ExecuteUbergraph_OptionsMenuSlider_Light(int EntryPoint) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x5973e4a0); UOptionsMenuSlider_Light_C_ExecuteUbergraph_OptionsMenuSlider_Light_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OptionsMenuSlider_Light.OptionsMenuSlider_Light_C.SliderChanged__DelegateSignature // (FUNC_Public, FUNC_Delegate, FUNC_BlueprintCallable, FUNC_BlueprintEvent) // Parameters: // float Slider_Value (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) void UOptionsMenuSlider_Light_C::SliderChanged__DelegateSignature(float Slider_Value) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>(0x2afee187); UOptionsMenuSlider_Light_C_SliderChanged__DelegateSignature_Params params; params.Slider_Value = Slider_Value; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "joker@slaughter-gaming.de" ]
joker@slaughter-gaming.de
2379b1067a8ebb2bda8e4c60bbca4b3d97876efd
43192accb4e0d9e0ff48a1935275845398a110d4
/code/vpp/include/vppBarriers.hpp
d50c96a0654f85ab87e7a7cc935d0541f8892e15
[ "BSD-2-Clause" ]
permissive
maikebing/vpp
3593b24820257bbf56ec4568c342a85c15f7bdba
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
refs/heads/master
2023-01-21T14:03:49.557239
2019-04-01T10:00:08
2019-04-01T10:00:08
316,381,624
0
0
null
null
null
null
UTF-8
C++
false
false
13,689
hpp
/* Copyright 2016-2019 SOFT-ERG, Przemek Kuczmierczyk (www.softerg.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED 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. */ #ifndef INC_VPPBARRIERS_HPP #define INC_VPPBARRIERS_HPP // ----------------------------------------------------------------------------- #ifndef INC_VPPTYPES_HPP #include "vppTypes.hpp" #endif // ----------------------------------------------------------------------------- namespace vpp { // ----------------------------------------------------------------------------- class Bar { public: enum EStage { NONE = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, INDIRECT = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VTXIN = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VSHADER = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VERTEX = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, TCSHADER = VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, TESHADER = VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, GSHADER = VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, GEOMETRY = VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, FSHADER = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, FRAGMENT = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, EDEPTH = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, LDEPTH = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, CLROUT = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, CSHADER = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, COMPUTE = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, TRANSFER = VK_PIPELINE_STAGE_TRANSFER_BIT, HOST = VK_PIPELINE_STAGE_HOST_BIT }; }; // ----------------------------------------------------------------------------- class Barriers : public Bar { public: Barriers(); Barriers ( const Barriers& rhs ); void setBarriers ( const std::vector< VkMemoryBarrier >& bar ); void setBarriers ( const std::vector< VkBufferMemoryBarrier >& bar ); void setBarriers ( const std::vector< VkImageMemoryBarrier >& bar ); void setBarriers ( const VkMemoryBarrier& bar ); void setBarriers ( const VkBufferMemoryBarrier& bar ); void setBarriers ( const VkImageMemoryBarrier bar ); template< typename BarriersA > Barriers ( const BarriersA& ba ); template< typename BarriersA, typename BarriersB > Barriers ( const BarriersA& ba, const BarriersB& bb ); template< typename BarriersA, typename BarriersB, typename BarriersC > Barriers ( const BarriersA& ba, const BarriersB& bb, const BarriersC& bc ); public: std::uint32_t d_memoryBarrierCount; const VkMemoryBarrier* d_pMemoryBarriers; std::uint32_t d_bufferMemoryBarrierCount; const VkBufferMemoryBarrier* d_pBufferMemoryBarriers; std::uint32_t d_imageMemoryBarrierCount; const VkImageMemoryBarrier* d_pImageMemoryBarriers; }; // ----------------------------------------------------------------------------- VPP_INLINE Barriers :: Barriers() : d_memoryBarrierCount ( 0 ), d_pMemoryBarriers ( 0 ), d_bufferMemoryBarrierCount ( 0 ), d_pBufferMemoryBarriers ( 0 ), d_imageMemoryBarrierCount ( 0 ), d_pImageMemoryBarriers ( 0 ) { } // ----------------------------------------------------------------------------- VPP_INLINE Barriers :: Barriers ( const Barriers& rhs ) : d_memoryBarrierCount ( rhs.d_memoryBarrierCount ), d_pMemoryBarriers ( rhs.d_pMemoryBarriers ), d_bufferMemoryBarrierCount ( rhs.d_bufferMemoryBarrierCount ), d_pBufferMemoryBarriers ( rhs.d_pBufferMemoryBarriers ), d_imageMemoryBarrierCount ( rhs.d_imageMemoryBarrierCount ), d_pImageMemoryBarriers ( rhs.d_pImageMemoryBarriers ) { } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const std::vector< VkMemoryBarrier >& bar ) { d_pMemoryBarriers = & bar [ 0 ]; d_memoryBarrierCount = static_cast< std::uint32_t >( bar.size() ); } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const std::vector< VkBufferMemoryBarrier >& bar ) { d_pBufferMemoryBarriers = & bar [ 0 ]; d_bufferMemoryBarrierCount = static_cast< std::uint32_t >( bar.size() ); } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const std::vector< VkImageMemoryBarrier >& bar ) { d_pImageMemoryBarriers = & bar [ 0 ]; d_imageMemoryBarrierCount = static_cast< std::uint32_t >( bar.size() ); } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const VkMemoryBarrier& bar ) { d_pMemoryBarriers = & bar; d_memoryBarrierCount = 1; } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const VkBufferMemoryBarrier& bar ) { d_pBufferMemoryBarriers = & bar; d_bufferMemoryBarrierCount = 1; } // ----------------------------------------------------------------------------- VPP_INLINE void Barriers :: setBarriers ( const VkImageMemoryBarrier bar ) { d_pImageMemoryBarriers = & bar; d_imageMemoryBarrierCount = 1; } // ----------------------------------------------------------------------------- template< typename BarriersA > VPP_INLINE Barriers :: Barriers ( const BarriersA& ba ) : Barriers() { setBarriers ( ba ); } // ----------------------------------------------------------------------------- template< typename BarriersA, typename BarriersB > VPP_INLINE Barriers :: Barriers ( const BarriersA& ba, const BarriersB& bb ) : Barriers() { setBarriers ( ba ); setBarriers ( bb ); } // ----------------------------------------------------------------------------- template< typename BarriersA, typename BarriersB, typename BarriersC > VPP_INLINE Barriers :: Barriers ( const BarriersA& ba, const BarriersB& bb, const BarriersC& bc ) : Barriers() { setBarriers ( ba ); setBarriers ( bb ); setBarriers ( bc ); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- class MemoryBarrier : public VkMemoryBarrier, public Barriers { MemoryBarrier ( VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask ); }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- class BufferMemoryBarrier : public VkBufferMemoryBarrier, public Barriers { BufferMemoryBarrier ( VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask, const Buf& buffer, VkDeviceSize offset = 0, VkDeviceSize size = VK_WHOLE_SIZE, uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED ); }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- class ImageMemoryBarrier : public VkImageMemoryBarrier, public Barriers { ImageMemoryBarrier ( VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask, VkImageLayout oldLayout, VkImageLayout newLayout, const Img& image, std::uint32_t baseArrayLayer = 0, std::uint32_t layerCount = VK_REMAINING_ARRAY_LAYERS, std::uint32_t baseMipLevel = 0, std::uint32_t levelCount = VK_REMAINING_MIP_LEVELS, VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED ); }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- class BarrierList : public Barriers { public: BarrierList ( VkPipelineStageFlags sourceStage, VkPipelineStageFlags targetStage ); BarrierList ( BarrierList&& rhs ); VPP_DLLAPI void addBarrier ( const Img& hImg ); VPP_DLLAPI void addBarrier ( const Buf& hBuf ); VPP_DLLAPI void createBarriers ( const Img& hImg, const std::vector< VkImageSubresourceRange >& regions ); template< typename SingleT > void collectBarriers ( SingleT&& single ) { addBarrier ( single ); } template< typename FirstT, typename... ArgTypes > void collectBarriers ( FirstT&& first, ArgTypes&& ... args ) { collectBarriers ( first ); collectBarriers ( args... ); } private: static VkAccessFlags getBarrierAccessMaskHintForSource ( VkFlags stageBit, const Img& resImg ); static VkAccessFlags getBarrierAccessMaskHintForSource ( VkFlags stageBit, const Buf& resBuf ); static VkAccessFlags getBarrierAccessMaskHintForTarget ( VkFlags stageBit, const Img& resImg ); static VkAccessFlags getBarrierAccessMaskHintForTarget ( VkFlags stageBit, const Buf& resBuf ); static VkAccessFlags errorMissingUsage ( const Img& resImg, unsigned int u ); static VkAccessFlags errorMissingUsage ( const Buf& resBuf, unsigned int u ); static VkAccessFlags errorInvalidStageMask ( const Img& resImg, unsigned int m ); static VkAccessFlags errorInvalidStageMask ( const Buf& resBuf, unsigned int m ); static VkImageLayout getBarrierLayoutHintForSource ( VkFlags stageBit, const Img& resImg ); static VkImageLayout getBarrierLayoutHintForTarget ( VkFlags stageBit, const Img& resImg ); public: VkPipelineStageFlags d_sourceStage; VkPipelineStageFlags d_targetStage; std::vector< VkBufferMemoryBarrier > d_bufferBarriers; std::vector< VkImageMemoryBarrier > d_imageBarriers; std::vector< VkMemoryBarrier > d_memoryBarriers; }; // ----------------------------------------------------------------------------- VPP_INLINE BarrierList :: BarrierList ( VkPipelineStageFlags sourceStage, VkPipelineStageFlags targetStage ) : d_sourceStage ( sourceStage ), d_targetStage ( targetStage ) { } // ----------------------------------------------------------------------------- VPP_INLINE BarrierList :: BarrierList ( BarrierList&& rhs ) : Barriers ( static_cast< const Barriers& >( rhs ) ) { d_sourceStage = rhs.d_sourceStage; d_targetStage = rhs.d_targetStage; d_bufferBarriers.swap ( rhs.d_bufferBarriers ); d_imageBarriers.swap ( rhs.d_imageBarriers ); d_memoryBarriers.swap ( rhs.d_memoryBarriers ); } // ----------------------------------------------------------------------------- template< typename ... Args > VPP_INLINE BarrierList barriers ( VkPipelineStageFlags sourceStage, VkPipelineStageFlags targetStage, Args&& ... args ) { BarrierList result ( sourceStage, targetStage ); result.collectBarriers ( args... ); if ( ! result.d_bufferBarriers.empty() ) result.setBarriers ( result.d_bufferBarriers ); if ( ! result.d_imageBarriers.empty() ) result.setBarriers ( result.d_imageBarriers ); return result; } // ----------------------------------------------------------------------------- VPP_INLINE BarrierList barriers ( const Img& hImage, const std::vector< VkImageSubresourceRange >& regions, VkPipelineStageFlags sourceStage, VkPipelineStageFlags targetStage ) { BarrierList result ( sourceStage, targetStage ); result.createBarriers ( hImage, regions ); if ( ! result.d_bufferBarriers.empty() ) result.setBarriers ( result.d_bufferBarriers ); if ( ! result.d_imageBarriers.empty() ) result.setBarriers ( result.d_imageBarriers ); return result; } // ----------------------------------------------------------------------------- } // namespace vpp // ----------------------------------------------------------------------------- #endif // INC_VPPBARRIERS_HPP
[ "softerg@fc0145be-4d46-4df3-883e-5264cf7f6dad" ]
softerg@fc0145be-4d46-4df3-883e-5264cf7f6dad
c1ab8b39cf854796fa4a63ef794e79eef9797f61
31b33fd6d6500964b2f4aa29186451c3db30ea1b
/Userland/Libraries/LibCrypto/PK/Code/EMSA_PKCS1_V1_5.h
1de4d73b99f3316094085691aa5aefd49882e130
[ "BSD-2-Clause" ]
permissive
jcs/serenity
4ca6f6eebdf952154d50d74516cf5c17dbccd418
0f1f92553213c6c2c7268078c9d39b813c24bb49
refs/heads/master
2022-11-27T13:12:11.214253
2022-11-21T17:01:22
2022-11-22T20:13:35
229,094,839
10
2
BSD-2-Clause
2019-12-19T16:25:40
2019-12-19T16:25:39
null
UTF-8
C++
false
false
4,747
h
/* * Copyright (c) 2022, Michiel Visser <opensource@webmichiel.nl> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibCrypto/Hash/HashManager.h> #include <LibCrypto/Hash/MD5.h> #include <LibCrypto/Hash/SHA1.h> #include <LibCrypto/Hash/SHA2.h> #include <LibCrypto/PK/Code/Code.h> namespace Crypto { namespace PK { template<typename HashFunction> class EMSA_PKCS1_V1_5 : public Code<HashFunction> { public: template<typename... Args> EMSA_PKCS1_V1_5(Args... args) : Code<HashFunction>(args...) { } virtual void encode(ReadonlyBytes in, ByteBuffer& out, size_t em_bits) override { auto& hash_fn = this->hasher(); hash_fn.update(in); auto message_digest = hash_fn.digest(); auto message_digest_size = message_digest.bytes().size(); auto digest_info = hash_function_digest_info(); auto encoded_message_length = digest_info.size() + message_digest_size; auto em_bytes = (em_bits + 7) / 8; // RFC8017 section 9.2: 3. If emLen < tLen + 11, output "intended encoded message length too short" and stop. if (em_bytes < encoded_message_length + 11) { dbgln("EMSA-PKCS1-V1_5-ENCODE: intended encoded message length too short"); return; } auto offset = 0; // Build the padding 0x0001ffff..ff00 out[offset++] = 0x00; out[offset++] = 0x01; for (size_t i = 0; i < em_bytes - encoded_message_length - 3; i++) out[offset++] = 0xff; out[offset++] = 0x00; // Add the digest info and message digest out.overwrite(offset, digest_info.data(), digest_info.size()); offset += digest_info.size(); out.overwrite(offset, message_digest.immutable_data(), message_digest.data_length()); } virtual VerificationConsistency verify(ReadonlyBytes msg, ReadonlyBytes emsg, size_t em_bits) override { auto em_bytes = (em_bits + 7) / 8; auto buffer_result = ByteBuffer::create_uninitialized(em_bytes); if (buffer_result.is_error()) { dbgln("EMSA-PKCS1-V1_5-VERIFY: out of memory"); return VerificationConsistency::Inconsistent; } auto buffer = buffer_result.release_value(); // Encode the supplied message into the buffer encode(msg, buffer, em_bits); // Check that the expected message matches the encoded original message if (emsg != buffer) { return VerificationConsistency::Inconsistent; } return VerificationConsistency::Consistent; } private: inline ReadonlyBytes hash_function_digest_info(); }; template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::MD5>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 return { "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10", 18 }; } template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::SHA1>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 return { "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14", 15 }; } template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::SHA256>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 return { "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20", 19 }; } template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::SHA384>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 return { "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30", 19 }; } template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::SHA512>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 return { "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40", 19 }; } template<> inline ReadonlyBytes EMSA_PKCS1_V1_5<Crypto::Hash::Manager>::hash_function_digest_info() { // RFC8017 section 9.2 notes 1 switch (hasher().kind()) { case Hash::HashKind::MD5: return { "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10", 18 }; case Hash::HashKind::SHA1: return { "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14", 15 }; case Hash::HashKind::SHA256: return { "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20", 19 }; case Hash::HashKind::SHA384: return { "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30", 19 }; case Hash::HashKind::SHA512: return { "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40", 19 }; case Hash::HashKind::None: default: VERIFY_NOT_REACHED(); } } } }
[ "Ali.mpfard@gmail.com" ]
Ali.mpfard@gmail.com
6650fceeff808dfd6fc3eb095b820ecf5ef1dcae
5df66b7c0cf0241831ea7d8345aa4102f77eba03
/Carberp Botnet/source - absource/pro/all source/BJWJ/include/content/nsISyncLoadDOMService.h
c027f9caf8a793e4d5f31c6d26603c59ad76350c
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
bengalm/fireroothacker
e8f20ae69f4246fc4fe8c48bbb107318f7a79265
ceb71ba972caca198524fe91a45d1e53b80401f6
refs/heads/main
2023-04-02T03:00:41.437494
2021-04-06T00:26:28
2021-04-06T00:26:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,718
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/content/base/public/nsISyncLoadDOMService.idl */ #ifndef __gen_nsISyncLoadDOMService_h__ #define __gen_nsISyncLoadDOMService_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIURI; /* forward declaration */ class nsIPrincipal; /* forward declaration */ class nsIDOMDocument; /* forward declaration */ class nsIChannel; /* forward declaration */ /* starting interface: nsISyncLoadDOMService */ #define NS_ISYNCLOADDOMSERVICE_IID_STR "8095998d-ae1c-4cfa-9b43-0973e5d77eb0" #define NS_ISYNCLOADDOMSERVICE_IID \ {0x8095998d, 0xae1c, 0x4cfa, \ { 0x9b, 0x43, 0x09, 0x73, 0xe5, 0xd7, 0x7e, 0xb0 }} /************************************************************************* * * * **** NOTICE **** * * * * * * This interface is DEPRECATED! * * You should instead use XMLHttpRequest which now works both from * * Javascript and C++. * * * * Additionally, synchronous network loads are evil. Any delays * * from the server will appear as a hang in the mozilla UI. * * Therefore, they should be avoided as much as possible. * * * * Don't make me come over there!! * * * * * ************************************************************************/ /** * The nsISyncDOMLoadService interface can be used to synchronously load * a document. */ class NS_NO_VTABLE NS_SCRIPTABLE nsISyncLoadDOMService : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISYNCLOADDOMSERVICE_IID) /** * Synchronously load the document from the specified channel. * * @param aChannel The channel to load the document from. * @param aLoaderPrincipal Principal of loading document. For security * checks null if no securitychecks should be done * * @returns The document loaded from the URI. */ /* nsIDOMDocument loadDocument (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_SCRIPTABLE NS_IMETHOD LoadDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) = 0; /* nsIDOMDocument loadDocumentAsXML (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_SCRIPTABLE NS_IMETHOD LoadDocumentAsXML(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) = 0; /** * Synchronously load an XML document from the specified * channel. The channel must be possible to open synchronously. * * @param aChannel The channel to load the document from. * @param aLoaderPrincipal Principal of loading document. For security * checks null if no securitychecks should be done * * @returns The document loaded from the URI. */ /* nsIDOMDocument loadLocalDocument (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_SCRIPTABLE NS_IMETHOD LoadLocalDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsISyncLoadDOMService, NS_ISYNCLOADDOMSERVICE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSISYNCLOADDOMSERVICE \ NS_SCRIPTABLE NS_IMETHOD LoadDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD LoadDocumentAsXML(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD LoadLocalDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSISYNCLOADDOMSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD LoadDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return _to LoadDocument(aChannel, aLoaderPrincipal, _retval); } \ NS_SCRIPTABLE NS_IMETHOD LoadDocumentAsXML(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return _to LoadDocumentAsXML(aChannel, aLoaderPrincipal, _retval); } \ NS_SCRIPTABLE NS_IMETHOD LoadLocalDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return _to LoadLocalDocument(aChannel, aLoaderPrincipal, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSISYNCLOADDOMSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD LoadDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->LoadDocument(aChannel, aLoaderPrincipal, _retval); } \ NS_SCRIPTABLE NS_IMETHOD LoadDocumentAsXML(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->LoadDocumentAsXML(aChannel, aLoaderPrincipal, _retval); } \ NS_SCRIPTABLE NS_IMETHOD LoadLocalDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->LoadLocalDocument(aChannel, aLoaderPrincipal, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsSyncLoadDOMService : public nsISyncLoadDOMService { public: NS_DECL_ISUPPORTS NS_DECL_NSISYNCLOADDOMSERVICE nsSyncLoadDOMService(); private: ~nsSyncLoadDOMService(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsSyncLoadDOMService, nsISyncLoadDOMService) nsSyncLoadDOMService::nsSyncLoadDOMService() { /* member initializers and constructor code */ } nsSyncLoadDOMService::~nsSyncLoadDOMService() { /* destructor code */ } /* nsIDOMDocument loadDocument (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_IMETHODIMP nsSyncLoadDOMService::LoadDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMDocument loadDocumentAsXML (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_IMETHODIMP nsSyncLoadDOMService::LoadDocumentAsXML(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMDocument loadLocalDocument (in nsIChannel aChannel, in nsIPrincipal aLoaderPrincipal); */ NS_IMETHODIMP nsSyncLoadDOMService::LoadLocalDocument(nsIChannel *aChannel, nsIPrincipal *aLoaderPrincipal, nsIDOMDocument **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsISyncLoadDOMService_h__ */
[ "ludi@ps.ac.cn" ]
ludi@ps.ac.cn
11fe64495231f3cb2105707930c05f1a52227484
4ca0c84fb7af16b8470ab9ff408edd6d00c94f77
/SPOJ/7190. Guess the Number/7190.cpp
2d8e0f838f4338259be9d0db42da944c4b453616
[]
no_license
svanegas/programming_solutions
87305a09dd2a2ea0c05b2e2fb703d5cd2b142fc0
32e5f6c566910e165effeb79ec34a8886edfccff
refs/heads/master
2020-12-23T16:03:33.848189
2020-10-10T18:59:58
2020-10-10T18:59:58
12,229,967
8
10
null
null
null
null
WINDOWS-1250
C++
false
false
2,446
cpp
//Santiago Vanegas Gil. #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <sstream> #include <fstream> #include <cassert> #include <climits> #include <cstdlib> #include <cstring> #include <string> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #define D(x) cout << #x " is " << x << endl using namespace std; const double EPS = 1e-9; const double PI = acos(-1.0); template <class T> string toStr(const T &x) { stringstream s; s << x; return s.str(); } template <class T> int toInt(const T &x) { stringstream s; s << x; int r; s >> r; return r; } typedef long long ll; const ll MAXN = 23; bool sieve[MAXN + 5]; vector<ll> primes; void build_sieve() { memset(sieve, false, sizeof sieve); sieve[0] = sieve[1] = true; for (ll i = 2LL; i * i <= MAXN; ++i) { if (!sieve[i]) { for (ll j = i * i; j <= MAXN; j += i) { sieve[j] = true; } } } for (ll i = 2LL; i <= MAXN; ++i) { if (!sieve[i]) primes.push_back(i); } } ll minNumber(const string &s) { vector <ll> divisible; ll ans = 0LL; for (ll i = 0LL; i < s.size(); ++i) { if (s[i] == 'Y') { divisible.push_back(i + 1LL); ans = i + 1LL; } else if (ans == 0LL) ans = i + 2LL; } vector <ll> factors; int index = 0; //prime index int oneCount = 0; //counting if we’re done bool increment; //Increment prime index bool used; //If i used a prime factor to add it to list while (oneCount != divisible.size()) { increment = false; used = false; oneCount = 0; for (ll i = 0LL; i < divisible.size() * 1LL; ++i) { if (divisible[i] == 1LL) oneCount++; else if (divisible[i] % primes[index] == 0LL) { divisible[i] /= primes[index]; used = true; if (divisible[i] == 1LL) oneCount++; } } if (used) factors.push_back(primes[index]); if (!used) index++; } if (!factors.empty()) { ans = 1LL; for (ll i = 0LL; i < factors.size(); ++i) { ans *= (factors[i] * 1LL); } } for (ll i = 0LL; i < s.size(); ++i) { if (s[i] == 'N') { if (ans % (i + 1LL) == 0LL) { ans = -1LL; break; } } } return ans; } int main() { build_sieve(); string s; while (cin >> s && s != "*") { cout << minNumber(s) << endl; } return 0; }
[ "savanegasg@gmail.com" ]
savanegasg@gmail.com
f2b5ee833258801ca9a5676cdd4129f11d0ae610
ef53d738245b7e46b6b3453bad92547fae003791
/tcpcontroller.h
9ade551575dcea0c99666b9e5c46dcc934a13b6d
[]
no_license
defrixx/PA-3
7d708a67b393ab54d9f708f5d66b16ac74497b9b
3a889fbb2209640190e480911f71ef6125c561e8
refs/heads/master
2022-02-25T07:15:31.090709
2022-02-09T07:58:15
2022-02-09T07:58:15
150,431,528
0
0
null
null
null
null
UTF-8
C++
false
false
2,151
h
#ifndef TCPCONTROLLER_H #define TCPCONTROLLER_H #include <QObject> #include <QList> #include <QDebug> #include <QByteArray> #include <QDataStream> #include <QTcpServer> /* класс, инкапсулирующий * 1) сокет (конечную точку с буфером, связанную с сетевым адаптером) * 2) бесконечный цикл попыток чтения из сокета (т.н. "прослушка") * 3) генерация сигналов при поступлении каких-то данных на сокет сервера * 4) поддержка нескольких соединений */ #include <QTcpSocket> /* класс, инкапсулирующий * 1) буфер данных, который будет отправляться/считываться с адаптера * 2) функции для чтения/записи * 3) остальной функционал типичного устройства * ввода/вывода (наподобие QFile, QIODevice и т.д.) */ class tcpcontroller : public QObject { Q_OBJECT public: explicit tcpcontroller(QObject *parent = nullptr); QTcpServer * serv; // пункт (1) конспекта QTcpSocket * client_sock; QTcpSocket * server_sock; QString * message; /*QList<QTcpSocket *> sockets; // получатели данных QTcpSocket *firstSocket; // вещатель*/ // QList<QTcpSocket*> socket_list; - на случай необходимости поддержки нескольких соединений signals: sendMessage(); public slots: void sendMessag(QString message); void newConnection(); void clientReady(); /*void incommingConnection(); // обработчик входящего подключения void readyRead(); // обработчик входящих данных void stateChanged(QAbstractSocket::SocketState stat); // обработчик изменения состояния вещающего сокета (т.к. всегда есть вещатель)*/ }; #endif // TCPCONTROLLER_H
[ "defrixx@gmail.com" ]
defrixx@gmail.com
efa6d035d59d734ca67eeda8a043c4755277179d
bc459bcddd023ef777196c34cedb8ae7e1ea68d2
/day13.cc
c9a274989ab47ed2b06d4676ea8daeca38aeae1f
[]
no_license
toastwaffle/AoC2019
ad610e4d5af30aba199579f1d8dec3b0d4795085
c55a577a9665ce5a33060e4fbaa3593f02bbe48e
refs/heads/master
2020-09-25T23:20:16.696652
2019-12-15T20:52:45
2019-12-15T20:52:45
226,111,193
0
0
null
null
null
null
UTF-8
C++
false
false
2,244
cc
#include <map> #include <utility> #include <iostream> #include "intcode.h" int main() { std::map<std::pair<int64_t, int64_t>, int64_t> drawn; intcode::IntCode arcade("arcade", "/home/samuel/aoc/day13.txt"); int64_t outputs[3]; int idx = 0; int64_t score; arcade.SetOutputter([&drawn, &outputs, &idx, &score](int64_t output) { outputs[idx] = output; idx++; if (idx == 3) { if (outputs[0] == -1 && outputs[1] == 0) { score = outputs[2]; } else { drawn[std::pair<int64_t,int64_t>(outputs[0], outputs[1])] = outputs[2]; } idx = 0; } }); arcade.Run(); int count = 0; int64_t min_x = std::numeric_limits<int64_t>::max(); int64_t max_x = std::numeric_limits<int64_t>::min(); int64_t min_y = std::numeric_limits<int64_t>::max(); int64_t max_y = std::numeric_limits<int64_t>::min(); for (const auto [position, value] : drawn) { min_x = std::min(min_x, position.first); max_x = std::max(max_x, position.first); min_y = std::min(min_y, position.second); max_y = std::max(max_y, position.second); if (value == 2) count++; } std::cout << count << std::endl; std::cout << min_x << std::endl; std::cout << max_x << std::endl; std::cout << min_y << std::endl; std::cout << max_y << std::endl; int64_t ball_x = -1; int64_t paddle_x = -1; while (!arcade.IsHalted()) { for (int64_t y = min_y; y <= max_y; y++) { for (int64_t x = min_x; x <= max_x; x++) { switch (drawn[std::pair<int64_t, int64_t>(x, y)]) { case 1: std::cout << "█"; break; case 2: std::cout << "▒"; break; case 3: std::cout << "━"; paddle_x = x; break; case 4: std::cout << "o"; ball_x = x; break; default: std::cout << " "; break; } } std::cout << "\n"; } std::cout << paddle_x << ", " << ball_x << std::endl; if (paddle_x < ball_x) { arcade.SendInput(1); } else if (ball_x < paddle_x) { arcade.SendInput(-1); } else { arcade.SendInput(0); } } std::cout << score << std::endl; }
[ "samuel.littley@toastwaffle.com" ]
samuel.littley@toastwaffle.com
03d3f3d68a777bd21577b548d83896b6193ea0b8
31ba164d153487a5836dd13eae0befc350eac6bb
/RecycleBin.cpp
81d24a1bff1ebbfb70dc5d3f811413d411ab8218
[ "MIT" ]
permissive
christofmuc/juce-widgets
5b1e1caf153b844fcd3e88c9c4f26ed2135ca32b
b3c79ff792a035dcbb4a8a3249adb00334888f9b
refs/heads/master
2023-02-22T12:28:04.479594
2023-02-18T16:01:06
2023-02-18T16:01:06
228,012,633
10
1
null
null
null
null
UTF-8
C++
false
false
2,049
cpp
/* * MIT License * * Copyright (c) 2019-2023 Christof Ruch * * 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 "RecycleBin.h" #include "BinaryResources.h" #include "IconHelper.h" RecycleBin::RecycleBin() { IconHelper::setupIcon(this, wasteBin_, delete_png, delete_png_size, 128); addAndMakeVisible(wasteBin_); } void RecycleBin::resized() { auto bounds = getLocalBounds(); wasteBin_.setBounds(bounds); wasteBin_.setImagePlacement(juce::RectanglePlacement::xMid | juce::RectanglePlacement::yMid | juce::RectanglePlacement::onlyReduceInSize); } bool RecycleBin::isInterestedInDragSource(const SourceDetails& dragSourceDetails) { ignoreUnused(dragSourceDetails); return onItemDropped != nullptr; } void RecycleBin::itemDropped(const SourceDetails& dragSourceDetails) { if (onItemDropped) onItemDropped(dragSourceDetails.description); } void RecycleBin::mouseUp(const juce::MouseEvent& event) { juce::ignoreUnused(event); if (onClicked) { onClicked(); } }
[ "christof.ruch@gmx.de" ]
christof.ruch@gmx.de
a687a5393a11a8174192cb8fad60e45d8aa95e26
266a60c1437214751f5bf7995495fa8ba769008e
/Qt/示例7—文件/dialog.h
ef7eb6d9ce66f93fc191543af050c555b589e0dc
[]
no_license
AramakiYui/ReLearn-C-
ec4a268cd2107d4851c5e2219a58f9bb32b1ae61
2d17a7cde6bf5ea5bcd6ee26c39baa84906b09a5
refs/heads/master
2020-05-03T07:39:47.604283
2019-10-14T11:27:25
2019-10-14T11:27:25
178,504,413
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = nullptr); ~Dialog(); private slots: void on_pushButton1_clicked(); void on_pushButton2_clicked(); private: Ui::Dialog *ui; }; #endif // DIALOG_H
[ "291823655@qq.com" ]
291823655@qq.com
8fba3e7d0e1fca36841f905145eeb73e8c4bd9d3
ae8b1315e744352fe3812707eab7f1d45b0b26c5
/include/forward_list/ForwardListNode.h
cffb976094d32d88f849cae4d07e49bab8fc50ac
[ "MIT" ]
permissive
alisonbelow/cpp-stlcontainers
00f9ce09c08ef8b80611ed0fce2774ba76157874
1d3d8e2442f46387c302272971ad92d17a62e4fb
refs/heads/master
2020-04-16T11:34:52.313402
2019-04-10T16:20:34
2019-04-10T16:20:34
165,542,024
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
namespace stlcontainer { template <typename T> class ForwardList; template <typename T> class ForwardListIterator; template<typename NodeType> class ForwardListNode { // Friend declarations friend class ForwardListIterator<NodeType>; friend class ForwardList<NodeType>; // Type definitions public: using value_type = NodeType; using reference = value_type&; using const_reference = const reference; private: value_type _value; stlcontainer::ForwardListNode<NodeType>* _next; // Constructor and destructor ForwardListNode(const_reference value = value_type{}, stlcontainer::ForwardListNode<NodeType>* next = nullptr): _value(value), _next(next) {}; ~ForwardListNode() = default; }; } // namespace stlcontainer
[ "alisonbelow@gmail.com" ]
alisonbelow@gmail.com
b7b9421c8aea169f07f1b7fb9b2c4285905db6ed
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/xpressive/detail/utility/counted_base.hpp
0e72aa389a7ae8c811a68da3e8bf988ea946c8d3
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,371
hpp
////////////////////////////////////////////////////////////////////////////// // (c) Copyright Andreas Huber Doenni 2002-2005, Eric Niebler 2006 // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_XPRESSIVE_DETAIL_UTILITY_COUNTED_BASE_HPP_EAN_04_16_2006 #define BOOST_XPRESSIVE_DETAIL_UTILITY_COUNTED_BASE_HPP_EAN_04_16_2006 #include <boost/assert.hpp> #include <boost/checked_delete.hpp> #include <boost/detail/atomic_count.hpp> namespace boost { namespace xpressive { namespace detail { template<typename Derived> struct counted_base_access; ////////////////////////////////////////////////////////////////////////////// // counted_base template<typename Derived> struct counted_base { long use_count() const { return this->count_; } protected: counted_base() : count_(0) { } counted_base(counted_base<Derived> const &) : count_(0) { } counted_base &operator =(counted_base<Derived> const &) { return *this; } private: friend struct counted_base_access<Derived>; mutable boost::detail::atomic_count count_; }; ////////////////////////////////////////////////////////////////////////////// // counted_base_access template<typename Derived> struct counted_base_access { static void add_ref(counted_base<Derived> const *that) { ++that->count_; } static void release(counted_base<Derived> const *that) { BOOST_ASSERT(0 < that->count_); if(0 == --that->count_) { boost::checked_delete(static_cast<Derived const *>(that)); } } }; template<typename Derived> inline void intrusive_ptr_add_ref(counted_base<Derived> const *that) { counted_base_access<Derived>::add_ref(that); } template<typename Derived> inline void intrusive_ptr_release(counted_base<Derived> const *that) { counted_base_access<Derived>::release(that); } }}} // namespace boost::xpressive::detail #endif
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
1ef450697cef9e0b480725dc3e9c98f5f687aadb
17c0e55e9e0c40c3e28c3a6fccc7dfd07af75853
/Server/EchoServer.cpp
977ba535ba3fdaa9359199dbea8199c4f3fda4ad
[]
no_license
menessy2/distributed_project
266b936f2fa39787bd8aebacfcc7ceac25bacfcf
454147ffb80eecb773b634b646195518db889826
refs/heads/master
2021-01-20T20:56:25.873461
2014-12-16T20:31:39
2014-12-16T20:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
cpp
#include "EchoServer.h" EchoServer::EchoServer(int port) : Server(port) { } void EchoServer::dispatch_connection_to_UserHandler(Message *received_pkt,SocketAddress sck){ std::string ip = std::string(inet_ntoa(sck.sin_addr)); std::string port = std::to_string(ntohs(sck.sin_port)); std::string result = ip+":"+port; if ( user_handlers.count(result) > 0 ){ EchoUserHandler *handler = user_handlers[result]; handler->notify_user_about_incomming_message(*received_pkt); } else { EchoUserHandler *user = new EchoUserHandler(ip.c_str(),ntohs(sck.sin_port),sck,sockfd); user_handlers.insert( std::pair<const char*,UserHandler*>(result.c_str(), user ) ); //incomming_requests->enqueue( [=](){ // user->initialize_thread(*received_pkt,true); //}); std::promise<bool> p; auto future = p.get_future(); new std::thread(&EchoUserHandler::initialize_thread, user, *received_pkt,true,std::ref(p)); } }
[ "menessy@paymobsolutions.com" ]
menessy@paymobsolutions.com
ddd81e4f649b190a0a53d895019c758644b66a3c
93312a185cd1ec842b5fcb5ba5928d6573af25c3
/LLVM_parser/Boundary/NotUsed/DriverGraphPass.h
a565f3d8f4550a391c6fa3d683e2e518212e1c02
[]
no_license
boy999/sample
134cd69eebdc46adb7fbc138e1667dcafc6a2777
3f2e160b241842b83b0baa8453e9fa84089afd3a
refs/heads/master
2020-07-20T17:24:38.632391
2013-10-16T20:43:11
2013-10-16T20:43:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,588
h
#ifndef DRIVER_GRAPH_PASS_H #define DRIVER_GRAPH_PASS_H 1 #include "headers.h" #include "llvm_headers.h" #include <iostream> #include "GraphBuilder.h" /*#include "InstructionCounter.h"*/ /*#include "LoopIterationCounter.h"*/ /*#include "LoopProfiler.h"*/ using namespace llvm; namespace llvm { class DriverGraphPass : public ModulePass, public InstVisitor<DriverGraphPass> { public: static char ID; // Pass identification, replacement for typeid DriverGraphPass() : ModulePass((intptr_t)&ID) { clear(); } virtual bool runOnModule(Module& M); virtual const char* getPassName() const { return "DriverGraphPass"; } void clear(); /*virtual bool runOnFunction(Function* F);*/ virtual void getAnalysisUsage(AnalysisUsage &AU) const { /*AU.addRequired<InstructionCounter>();*/ AU.addRequired<LoopInfo>(); } void visitBinaryOperator(BinaryOperator& BI); void visitGetElementPtrInst(GetElementPtrInst& GEP); void visitLoadInst(LoadInst& LI); void visitStoreInst(StoreInst& SI); void visitReturnInst(ReturnInst& RI); void visitCallInst(CallInst& CI); void visitPHINode(PHINode& PN); void visitCmpInst(CmpInst &I); void visitBranchInst(BranchInst &I); void visitSwitchInst(SwitchInst &I); void visitSelectInst(SelectInst& SI); void visitCastInst(CastInst& BI); void visitInstruction(Instruction &I) { cerr << "Instruction type "<<I.getOpcodeName() <<" unhandled\n"; } LoopInfo* getLoopInfo(Function* F); private: GraphBuilder* mGraphBuilder; Graph* mGraph; }; } #endif
[ "yuanbozju@gmail.com" ]
yuanbozju@gmail.com
18ebd36e146182dd5da117b858f5fe608de044c9
876334415f164a95a2089a51fa4ed73a1633049e
/src/jam-engine/Core/GamepadPredefs.hpp
c510569246a2332e304b63b85f498f6a63207cff
[]
no_license
rooooooooob/jam-engine
bf3fc96e53a30ff22737e59684c02fc98aae3a2a
d44dcad9aa22698320984b9b84588f3d110d0b95
refs/heads/master
2020-12-24T16:32:05.337203
2016-05-07T20:32:10
2016-05-07T20:32:10
12,377,072
3
2
null
null
null
null
UTF-8
C++
false
false
1,443
hpp
#ifndef JE_GAMEPAD_PREDEFS_HPP #define JE_GAMEPAD_PREDEFS_HPP #include "Controller.hpp" namespace je { namespace Binds { namespace X360 { const Controller::Bind A(0); const Controller::Bind B(1); const Controller::Bind Y(2); const Controller::Bind X(3); const Controller::Bind LB(4); const Controller::Bind RB(5); const Controller::Bind Back(6); const Controller::Bind Start(7); const Controller::Bind LStickIn(8); const Controller::Bind RStickIn(9); const Controller::Bind LT(sf::Joystick::Axis::Z); const Controller::Bind RT(sf::Joystick::Axis::Z, true); const Controller::Bind LStickLeft(sf::Joystick::Axis::X, true); const Controller::Bind LStickRight(sf::Joystick::Axis::X); const Controller::Bind LStickUp(sf::Joystick::Axis::Y, true); const Controller::Bind LStickDown(sf::Joystick::Axis::Y); const Controller::Bind RStickLeft(sf::Joystick::Axis::U, true); const Controller::Bind RStickRight(sf::Joystick::Axis::U); const Controller::Bind RStickUp(sf::Joystick::Axis::R, true); const Controller::Bind RStickDown(sf::Joystick::Axis::R); const Controller::Bind DPadDown(sf::Joystick::Axis::PovX, true); const Controller::Bind DPadUp(sf::Joystick::Axis::PovX); const Controller::Bind DPadLeft(sf::Joystick::Axis::PovY, true); const Controller::Bind DPadRight(sf::Joystick::Axis::PovY); } // namespace 360 namespace PS3 { // TODO: define later } // namespace PS3 } // namespace Binds } // namespace #endif // JE_GAMEPAD_PREDEFS_HPP
[ "raftias@gmail.com" ]
raftias@gmail.com
c2d553e1c02de582158b31122b61b0afe0643e43
b3f9235a1eabffa0d3bb27397d2c523a4a6a0bab
/Engine/soundClass.cpp
d7dc8b808da29cb7058081be97e208c43aeae302
[]
no_license
poonasp257/DirectX-Tutorial
1063d50dd33644446cfc80a6e137f47c03bebf8a
dfbad4091d8943009eed73681108a567779b9a65
refs/heads/master
2020-05-02T21:35:55.824901
2019-05-27T05:40:57
2019-05-27T05:40:57
178,225,693
0
0
null
null
null
null
UTF-8
C++
false
false
8,520
cpp
/////////////////////////////////////////////////////////////////////////////// // Filename: soundclass.cpp /////////////////////////////////////////////////////////////////////////////// #include "soundclass.h" SoundClass::SoundClass() { m_DirectSound = 0; m_primaryBuffer = 0; m_secondaryBuffer1 = 0; } SoundClass::SoundClass(const SoundClass& other) { } SoundClass::~SoundClass() { } bool SoundClass::Initialize(HWND hwnd) { bool result; // Initialize direct sound and the primary sound buffer. result = InitializeDirectSound(hwnd); if (!result) { return false; } // Load a wave audio file onto a secondary buffer. result = LoadWaveFile("../Engine/data/sound01.wav", &m_secondaryBuffer1); if (!result) { return false; } // Play the wave file now that it has been loaded. result = PlayWaveFile(); if (!result) { return false; } return true; } void SoundClass::Shutdown() { // Release the secondary buffer. ShutdownWaveFile(&m_secondaryBuffer1); // Shutdown the Direct Sound API. ShutdownDirectSound(); return; } bool SoundClass::InitializeDirectSound(HWND hwnd) { HRESULT result; DSBUFFERDESC bufferDesc; WAVEFORMATEX waveFormat; // Initialize the direct sound interface pointer for the default sound device. result = DirectSoundCreate8(NULL, &m_DirectSound, NULL); if (FAILED(result)) { return false; } // Set the cooperative level to priority so the format of the primary sound buffer can be modified. result = m_DirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY); if (FAILED(result)) { return false; } // Setup the primary buffer description. bufferDesc.dwSize = sizeof(DSBUFFERDESC); bufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME; bufferDesc.dwBufferBytes = 0; bufferDesc.dwReserved = 0; bufferDesc.lpwfxFormat = NULL; bufferDesc.guid3DAlgorithm = GUID_NULL; // Get control of the primary sound buffer on the default sound device. result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &m_primaryBuffer, NULL); if (FAILED(result)) { return false; } // Setup the format of the primary sound bufffer. // In this case it is a .WAV file recorded at 44,100 samples per second in 16-bit stereo (cd audio format). waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nSamplesPerSec = 44100; waveFormat.wBitsPerSample = 16; waveFormat.nChannels = 2; waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; waveFormat.cbSize = 0; // Set the primary buffer to be the wave format specified. result = m_primaryBuffer->SetFormat(&waveFormat); if (FAILED(result)) { return false; } return true; } void SoundClass::ShutdownDirectSound() { // Release the primary sound buffer pointer. if (m_primaryBuffer) { m_primaryBuffer->Release(); m_primaryBuffer = 0; } // Release the direct sound interface pointer. if (m_DirectSound) { m_DirectSound->Release(); m_DirectSound = 0; } return; } bool SoundClass::LoadWaveFile(char* filename, IDirectSoundBuffer8** secondaryBuffer) { int error; FILE* filePtr; unsigned int count; WaveHeaderType waveFileHeader; WAVEFORMATEX waveFormat; DSBUFFERDESC bufferDesc; HRESULT result; IDirectSoundBuffer* tempBuffer; unsigned char* waveData; unsigned char *bufferPtr; unsigned long bufferSize; // Open the wave file in binary. error = fopen_s(&filePtr, filename, "rb"); if (error != 0) { return false; } // Read in the wave file header. count = fread(&waveFileHeader, sizeof(waveFileHeader), 1, filePtr); if (count != 1) { return false; } // Check that the chunk ID is the RIFF format. if ((waveFileHeader.chunkId[0] != 'R') || (waveFileHeader.chunkId[1] != 'I') || (waveFileHeader.chunkId[2] != 'F') || (waveFileHeader.chunkId[3] != 'F')) { return false; } // Check that the file format is the WAVE format. if ((waveFileHeader.format[0] != 'W') || (waveFileHeader.format[1] != 'A') || (waveFileHeader.format[2] != 'V') || (waveFileHeader.format[3] != 'E')) { return false; } // Check that the sub chunk ID is the fmt format. if ((waveFileHeader.subChunkId[0] != 'f') || (waveFileHeader.subChunkId[1] != 'm') || (waveFileHeader.subChunkId[2] != 't') || (waveFileHeader.subChunkId[3] != ' ')) { return false; } // Check that the audio format is WAVE_FORMAT_PCM. if (waveFileHeader.audioFormat != WAVE_FORMAT_PCM) { return false; } // Check that the wave file was recorded in stereo format. if (waveFileHeader.numChannels != 2) { return false; } // Check that the wave file was recorded at a sample rate of 44.1 KHz. if (waveFileHeader.sampleRate != 44100) { return false; } // Ensure that the wave file was recorded in 16 bit format. if (waveFileHeader.bitsPerSample != 16) { return false; } // Check for the data chunk header. if ((waveFileHeader.dataChunkId[0] != 'd') || (waveFileHeader.dataChunkId[1] != 'a') || (waveFileHeader.dataChunkId[2] != 't') || (waveFileHeader.dataChunkId[3] != 'a')) { return false; } // Set the wave format of secondary buffer that this wave file will be loaded onto. waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nSamplesPerSec = 44100; waveFormat.wBitsPerSample = 16; waveFormat.nChannels = 2; waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; waveFormat.cbSize = 0; // Set the buffer description of the secondary sound buffer that the wave file will be loaded onto. bufferDesc.dwSize = sizeof(DSBUFFERDESC); bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME; bufferDesc.dwBufferBytes = waveFileHeader.dataSize; bufferDesc.dwReserved = 0; bufferDesc.lpwfxFormat = &waveFormat; bufferDesc.guid3DAlgorithm = GUID_NULL; // Create a temporary sound buffer with the specific buffer settings. result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, NULL); if (FAILED(result)) { return false; } // Test the buffer format against the direct sound 8 interface and create the secondary buffer. result = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, (void**)&*secondaryBuffer); if (FAILED(result)) { return false; } // Release the temporary buffer. tempBuffer->Release(); tempBuffer = 0; // Move to the beginning of the wave data which starts at the end of the data chunk header. fseek(filePtr, sizeof(WaveHeaderType), SEEK_SET); // Create a temporary buffer to hold the wave file data. waveData = new unsigned char[waveFileHeader.dataSize]; if (!waveData) { return false; } // Read in the wave file data into the newly created buffer. count = fread(waveData, 1, waveFileHeader.dataSize, filePtr); if (count != waveFileHeader.dataSize) { return false; } // Close the file once done reading. error = fclose(filePtr); if (error != 0) { return false; } // Lock the secondary buffer to write wave data into it. result = (*secondaryBuffer)->Lock(0, waveFileHeader.dataSize, (void**)&bufferPtr, (DWORD*)&bufferSize, NULL, 0, 0); if (FAILED(result)) { return false; } // Copy the wave data into the buffer. memcpy(bufferPtr, waveData, waveFileHeader.dataSize); // Unlock the secondary buffer after the data has been written to it. result = (*secondaryBuffer)->Unlock((void*)bufferPtr, bufferSize, NULL, 0); if (FAILED(result)) { return false; } // Release the wave data since it was copied into the secondary buffer. delete[] waveData; waveData = 0; return true; } void SoundClass::ShutdownWaveFile(IDirectSoundBuffer8** secondaryBuffer) { // Release the secondary sound buffer. if (*secondaryBuffer) { (*secondaryBuffer)->Release(); *secondaryBuffer = 0; } return; } bool SoundClass::PlayWaveFile() { HRESULT result; // Set position at the beginning of the sound buffer. result = m_secondaryBuffer1->SetCurrentPosition(0); if (FAILED(result)) { return false; } // Set volume of the buffer to 100%. result = m_secondaryBuffer1->SetVolume(DSBVOLUME_MAX); if (FAILED(result)) { return false; } // Play the contents of the secondary sound buffer. result = m_secondaryBuffer1->Play(0, 0, 0); if (FAILED(result)) { return false; } return true; }
[ "poonasp257@naver.com" ]
poonasp257@naver.com
41a7b46d4e03028cdf4cee3bdc386e2a3de6c460
1e1b3f702bdf6c0544ae27a321c8ebe605434ee4
/Chapter3/Sample063/ColorComboDemo/ColorCombo.h
0f44dc011c6b7d4deb6e99f8b02727a920bcd8aa
[]
no_license
Aque1228556367/Visual_Cpp_By_Example
63e3d67e734b7d95385a329e4a1641e7b1727084
41f903d8c9938e7800d89fcff31b182bfc1c4f45
refs/heads/master
2021-03-12T20:36:56.780300
2015-05-08T02:05:46
2015-05-08T02:05:46
35,171,152
2
2
null
null
null
null
GB18030
C++
false
false
1,329
h
#if !defined(AFX_COLORCOMBO_H__01B62923_FA10_4C75_A6EE_B6BEADDDDCC4__INCLUDED_) #define AFX_COLORCOMBO_H__01B62923_FA10_4C75_A6EE_B6BEADDDDCC4__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ColorCombo.h : header file // #include <afxtempl.h> // CArray类头文件 ///////////////////////////////////////////////////////////////////////////// // CColorCombo window class CColorCombo : public CComboBox { // Construction public: CColorCombo(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CColorCombo) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); protected: virtual void PreSubclassWindow(); //}}AFX_VIRTUAL // Implementation public: virtual ~CColorCombo(); CArray<COLORREF, COLORREF> colors;//定义颜色数组 // Generated message map functions protected: //{{AFX_MSG(CColorCombo) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COLORCOMBO_H__01B62923_FA10_4C75_A6EE_B6BEADDDDCC4__INCLUDED_)
[ "1228556367@qq.com" ]
1228556367@qq.com
a435af5f38359a0fab98cd33763cbdcc273e5151
c1c3df6f9574cb2ba542fbe1d9e2f1d7690ade7d
/src/files/reading_text.cpp
497202aafe3f133816828b819e42f911c5a463f2
[]
no_license
RaduMilici/advanced_cpp_udemy
24a999464c2764f281cfe3414162748434a3c31c
0709b1b2ca4cd71bdba54a9bd91d6175ca7699eb
refs/heads/master
2021-01-22T05:33:29.755714
2017-05-06T10:20:52
2017-05-06T10:20:52
81,674,682
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include <iostream> #include <fstream> #include "exercises.h" using namespace std; namespace files { void reading_text(){ ifstream inFile; //input file stream inFile.open("src/files/exercises/writing_text_exercise.txt"); if(inFile.is_open()){ string line; while (!inFile.eof()){ getline(inFile, line); cout << line << endl; } inFile.close(); } else { cout << "can not open file" << endl; } } }
[ "radu.milic@aeche.ro" ]
radu.milic@aeche.ro
bdffeea759b1b6eaa01677f109eeedf15a7c8627
331a6e979536298125c35181ff3da4343f7029a0
/include/Frame.h
6c129be5fd66f1e9aa9e0caf2c8d501f99c1b32b
[]
no_license
intelpro/SLAM_practice
87cec01a8b88a672d5a202b74a52f94c7ea9ab93
f363068b46dcef1ee357d4a563e8bee63d7e545d
refs/heads/master
2020-11-28T07:38:48.972862
2019-12-27T09:28:34
2019-12-27T09:28:34
229,746,052
0
0
null
null
null
null
UTF-8
C++
false
false
3,175
h
#ifndef FRAME_H #define FRAME_H #include<vector> #include<ORBextractor.h> namespace MY_SLAM { #define FRAME_GRID_ROWS 48 #define FRAME_GRID_COLS 64 class Frame { public: Frame(); Frame(const cv::Mat &imLeft, const cv::Mat &imRight, ORBextractor* extractorLeft, ORBextractor* extractorRight, cv::Mat &K, cv::Mat &distCoef, const float &bf, const float &thDepth); void ExtractORB(int lr_flag, const cv::Mat& imLeft); bool PosInGrid(const cv::KeyPoint &kp, int &posX, int &posY); void SetPose(cv::Mat Tcw); void UpdatePoseMatrices(); void StereoMatch(); cv::Mat BackProjectStereo(const int &i); public: ORBextractor* mpORBextractorLeft; ORBextractor* mpORBextractorRight; // scale pyramid information int mnScaleLevels; float mfScaleFactor; float mfLogScaleFactor; std::vector<float> mvScaleFactors; std::vector<float> mvInvScaleFactors; std::vector<float> mvLevelSigma2; std::vector<float> mvInvLevelSigma2; // number of keypoints int N_keypoints; // vector of keypoints std::vector<cv::KeyPoint> mvKeys; std::vector<cv::KeyPoint> mvKeysRight; // vector of descriptor cv::Mat mDescriptor; cv::Mat mDescriptorRight; // undistorted keypoints std::vector<cv::KeyPoint> mvKeysUn; // Camera pose cv::Mat mTcw; // Frame id static long unsigned int nNextId; long unsigned int mnId; // Calibration matrix cv::Mat mK; static float fx; static float fy; static float cx; static float cy; static float invfx; static float invfy; cv::Mat mDistCoef; // stereo matching std::vector<float> mvuRight; std::vector<float> mvDepth; // mb (stero baseline) static bool mbInitialComputation; // baseline times fx float mbf; // stereo baseline in meters float mb; // Threshold for close and far point float mThDepth; // Undistorted image bound static float mnMinX; static float mnMaxX; static float mnMinY; static float mnMaxY; // Keypoints are assigned to cells in a grid to reduce matching complexity when projecting MapPoints. static float mfGridElementWidthInv; static float mfGridElementHeightInv; std::vector<std::size_t> mGrid[FRAME_GRID_COLS][FRAME_GRID_ROWS]; private: void ComputeImageBound(const cv::Mat& left_image); void UndistortKeyPoints(); void AssignFeaturesToGrid(); // Rotation, translation and camera center cv::Mat mRcw; cv::Mat mtcw; cv::Mat mRwc; cv::Mat mOw; }; } #endif
[ "intelpro@kaist.ac.kr" ]
intelpro@kaist.ac.kr
7082da40fd68e53847ef08fd3dddbb4206154538
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case30/case0/900/nut
82dd14a84e3e3f64dec2255146b2ee6ca31f9bc8
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
9,947
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "900"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 0.00243691 0.00235896 0.0022724 0.00219507 0.00212915 0.0020716 0.00202017 0.00197251 0.00192639 0.00187972 0.00183033 0.00177543 0.00171051 0.00162608 0.00151479 0.000217621 0.000230249 0.000238397 0.000224821 0.00021171 0.000200557 0.000181606 0.000156868 0.000151883 0.000156166 0.000166799 0.00018293 0.000204514 0.000228331 0.000243582 0.000263181 0.000275236 0.000291896 0.000256375 0.00276862 0.00306004 0.00307911 0.00298479 0.0029245 0.00290436 0.00290799 0.00289774 0.00286223 0.00279971 0.00270927 0.00258774 0.00242298 0.00217575 0.0018377 0.00144056 0.00125446 0.000340943 0.000531681 0.000645725 0.000752452 0.00079859 0.000628354 0.000266151 0.000201373 0.000218193 0.000284631 0.000381537 0.000504302 0.000651033 0.00081387 0.000964553 0.00123565 0.00119691 0.00116205 0.000322103 0.00296888 0.00341382 0.00314218 0.00283115 0.00271504 0.00272238 0.00279287 0.0028771 0.00294306 0.00297242 0.00295251 0.00287362 0.00272426 0.00247687 0.00215465 0.00185328 0.00126405 0.000528184 0.00140493 0.00138047 0.00130135 0.0011462 0.000904808 0.00027848 0.000208706 0.000233077 0.00026224 0.000294288 0.000330996 0.000374391 0.000427817 0.000498531 0.00139054 0.00124052 0.000913051 0.000479855 0.00311808 0.00369354 0.00284844 0.00230991 0.0023014 0.0025054 0.00275641 0.00294137 0.00304859 0.00308626 0.00306951 0.0029996 0.00286439 0.00263322 0.00233187 0.00205048 0.00157222 0.000757422 0.00186167 0.00182909 0.00161228 0.00130303 0.000986909 0.000718081 0.00052719 0.000545689 0.000566676 0.000585959 0.000605657 0.000628689 0.000658427 0.000699895 0.000764491 0.00232854 0.0024877 0.00219743 0.000746538 0.00325001 0.00379532 0.00228001 0.00193114 0.00271535 0.00346929 0.00392755 0.00396964 0.00368409 0.00340268 0.00320814 0.00306374 0.00290649 0.00267009 0.00236937 0.00208508 0.00173066 0.00175298 0.0024237 0.00270997 0.00265397 0.0025871 0.0025758 0.00262996 0.00273534 0.00287065 0.00292636 0.00294257 0.00293944 0.00293115 0.00293511 0.00296869 0.00304643 0.00319401 0.00317753 0.00306483 0.0026055 0.00106412 0.000919344 0.000794596 0.00338483 0.00370891 0.00175106 0.0023724 0.00388767 0.00437663 0.00450249 0.00437174 0.00385331 0.00344538 0.00318947 0.00301275 0.00283346 0.00259192 0.00231979 0.002091 0.00192915 0.00245923 0.00314573 0.00355129 0.00364438 0.00373324 0.00384871 0.00397809 0.00409937 0.00418665 0.00421888 0.00420675 0.00414731 0.00404296 0.0039107 0.00377774 0.0036615 0.00355421 0.00342564 0.00324202 0.00294176 0.00244493 0.00177521 0.000835445 0.00354334 0.0034941 0.00171718 0.00217478 0.00368107 0.00397055 0.00389854 0.00374331 0.00349782 0.00324104 0.00303706 0.00286961 0.00269382 0.00248106 0.00227065 0.00214586 0.00219918 0.00309725 0.00380763 0.00414331 0.00430914 0.00446646 0.00461593 0.00474803 0.00485907 0.00494607 0.00501611 0.00506348 0.00506645 0.00499394 0.00482605 0.00457961 0.00429684 0.00400443 0.00369996 0.00335424 0.00292528 0.00238996 0.0017951 0.000856062 0.00376702 0.00366565 0.00229045 0.00155081 0.00287874 0.00327776 0.00322907 0.00315519 0.00308306 0.00296807 0.00284332 0.00271639 0.0025749 0.00241539 0.00228138 0.00227214 0.00252683 0.00367145 0.00432305 0.00463453 0.00486335 0.00504101 0.00517513 0.0052706 0.00534126 0.00540921 0.00549385 0.00560574 0.00573976 0.00586326 0.00591146 0.00582266 0.00559283 0.00523509 0.00477811 0.00425017 0.00370732 0.00314226 0.00266321 0.00140786 0.00414656 0.00471246 0.00436048 0.0019555 0.00232308 0.00292323 0.00294039 0.00288851 0.00284701 0.00280205 0.00274104 0.00266606 0.00257472 0.00247245 0.0024018 0.00247721 0.00288262 0.00406066 0.00473453 0.00517242 0.00545365 0.00563508 0.00572456 0.00574962 0.00574311 0.0057365 0.00575491 0.00582037 0.00595242 0.00616109 0.00642576 0.00665409 0.00681623 0.00690098 0.00695027 0.00699676 0.00678213 0.00613484 0.00555596 0.00154943 0.00700241 0.0028864 0.00280914 0.0031016 0.00311818 0.00308902 0.00303238 0.00297589 0.0029348 0.00289448 0.00284387 0.00278272 0.00274696 0.00286732 0.00338381 0.00429442 0.00510187 0.00568765 0.0060459 0.00624713 0.00631375 0.00628901 0.00621946 0.00614269 0.00608599 0.00606919 0.00610819 0.00621569 0.006394 0.00661222 0.00683923 0.00703262 0.00712287 0.00701295 0.00665501 0.00601655 0.00494348 0.0015686 0.0032126 0.00266762 0.00365298 0.00347356 0.00334139 0.00319527 0.00305616 0.00291891 0.00286404 0.00285467 0.00285881 0.00285293 0.00284436 0.00291304 0.0032469 0.00391405 0.00476762 0.00560053 0.00618827 0.0064918 0.00657197 0.00652047 0.00641592 0.0063104 0.00623156 0.00618944 0.00618345 0.00620756 0.00625314 0.00630902 0.00635284 0.00634375 0.00623582 0.00599843 0.00557355 0.0049021 0.00419771 0.00163108 0.00137199 0.001398 0.00203669 0.00121335 0.00119142 0.00117175 0.00117209 0.00117724 0.0011862 0.00119786 0.00120807 0.00121906 0.00123031 0.00123949 0.00124249 0.00122637 0.00120674 0.0012048 0.00122451 0.00126506 0.00132805 0.00138968 0.00143539 0.00146154 0.00147119 0.00146971 0.00146232 0.00145295 0.00144399 0.00143639 0.00143 0.00142382 0.00141631 0.00140578 0.00139051 0.0013678 0.0013317 0.00127114 0.00122328 0.00126245 ) ; boundaryField { floor { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 29 ( 0.000179922 2.18861e-05 2.36781e-05 2.4827e-05 2.29088e-05 2.10411e-05 1.94402e-05 1.66918e-05 1.30409e-05 1.22961e-05 1.29358e-05 1.45144e-05 1.68828e-05 2.00076e-05 2.34043e-05 2.55547e-05 2.829e-05 2.99587e-05 3.22476e-05 2.73429e-05 2.73428e-05 3.63602e-05 5.71068e-05 9.04066e-05 0.000179922 2.1886e-05 3.88993e-05 6.32895e-05 9.1737e-05 ) ; } ceiling { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 43 ( 0.000163839 0.00016679 0.000237631 0.000145597 0.000143073 0.000140799 0.000140839 0.000141435 0.000142471 0.000143818 0.000144996 0.000146261 0.000147557 0.000148612 0.000148955 0.000147098 0.000144834 0.000144609 0.000146878 0.000151536 0.000158738 0.000165749 0.000170926 0.00017388 0.000174968 0.0001748 0.000173965 0.000172907 0.000171893 0.000171034 0.000170311 0.000169611 0.00016876 0.000167567 0.000165834 0.000163255 0.000159144 0.00015222 0.000146723 0.000151225 0.000458144 0.00051503 0.000362427 ) ; } sWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 0.00016387; } nWall { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 6(9.6249e-05 0.000101177 0.00010365 0.000185913 0.000192892 0.000151234); } sideWalls { type empty; } glass1 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(0.000281089 0.000316331 0.00033739 0.000352982 0.000366705 0.000380668 0.000397012 0.000419951 0.000458568); } glass2 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 2(0.000167831 0.000183794); } sun { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 14 ( 0.000280822 0.000272468 0.000263165 0.000254823 0.000247687 0.00024144 0.000235839 0.000230638 0.00022559 0.00022047 0.000215036 0.000208976 0.000201786 0.00019239 ) ; } heatsource1 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 3(0.000128273 0.000111206 9.62488e-05); } heatsource2 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 4(0.000171556 0.00015035 0.00015035 0.00015145); } Table_master { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(3.04168e-05 2.06161e-05 2.40789e-05 2.81602e-05 3.25761e-05 3.75577e-05 4.33559e-05 5.03786e-05 5.95075e-05); } Table_slave { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 9(6.31554e-05 6.55004e-05 6.81495e-05 7.05727e-05 7.30382e-05 7.59089e-05 7.9597e-05 8.47068e-05 9.25954e-05); } inlet { type calculated; value uniform 0.00700241; } outlet { type calculated; value nonuniform List<scalar> 2(0.00137199 0.001398); } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
45752759f0e4d250e2c46201b3b62128a10655be
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/content/browser/worker_host/shared_worker_service_impl.h
68828b1e9b121ba376b3e27391a03cb67fe506d2
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
6,482
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_WORKER_HOST_SHARED_WORKER_SERVICE_IMPL_H_ #define CONTENT_BROWSER_WORKER_HOST_SHARED_WORKER_SERVICE_IMPL_H_ #include <memory> #include <set> #include <string> #include <utility> #include "base/compiler_specific.h" #include "base/containers/unique_ptr_adapters.h" #include "base/macros.h" #include "base/observer_list.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/worker_host/shared_worker_host.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/shared_worker_service.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/mojom/loader/fetch_client_settings_object.mojom.h" #include "third_party/blink/public/mojom/worker/shared_worker_connector.mojom.h" #include "third_party/blink/public/mojom/worker/shared_worker_factory.mojom.h" #include "third_party/blink/public/mojom/worker/worker_main_script_load_params.mojom.h" namespace blink { class MessagePortChannel; } namespace content { class ChromeAppCacheService; class SharedWorkerInstance; class SharedWorkerHost; class StoragePartitionImpl; // Shared helper function bool IsShuttingDown(RenderProcessHost* host); // Created per StoragePartition. class CONTENT_EXPORT SharedWorkerServiceImpl : public SharedWorkerService { public: SharedWorkerServiceImpl( StoragePartitionImpl* storage_partition, scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, scoped_refptr<ChromeAppCacheService> appcache_service); ~SharedWorkerServiceImpl() override; // SharedWorkerService implementation. void AddObserver(Observer* observer) override; void RemoveObserver(Observer* observer) override; void EnumerateSharedWorkers(Observer* observer) override; bool TerminateWorker(const GURL& url, const std::string& name, const url::Origin& constructor_origin) override; // Uses |url_loader_factory| to load workers' scripts instead of // StoragePartition's URLLoaderFactoryGetter. void SetURLLoaderFactoryForTesting( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); // Creates the worker if necessary or connects to an already existing worker. void ConnectToWorker( GlobalFrameRoutingId client_render_frame_host_id, blink::mojom::SharedWorkerInfoPtr info, mojo::PendingRemote<blink::mojom::SharedWorkerClient> client, blink::mojom::SharedWorkerCreationContextType creation_context_type, const blink::MessagePortChannel& port, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory); // Virtual for testing. virtual void DestroyHost(SharedWorkerHost* host); void NotifyWorkerStarted(SharedWorkerId shared_worker_id, int worker_process_id, const base::UnguessableToken& dev_tools_token); void NotifyWorkerTerminating(SharedWorkerId shared_worker_id); void NotifyClientAdded(SharedWorkerId shared_worker_id, GlobalFrameRoutingId render_frame_host_id); void NotifyClientRemoved(SharedWorkerId shared_worker_id, GlobalFrameRoutingId render_frame_host_id); StoragePartitionImpl* storage_partition() { return storage_partition_; } private: friend class SharedWorkerHostTest; friend class SharedWorkerServiceImplTest; friend class TestSharedWorkerServiceImpl; FRIEND_TEST_ALL_PREFIXES(NetworkServiceRestartBrowserTest, SharedWorker); // Creates a new worker in the creator's renderer process. SharedWorkerHost* CreateWorker( SharedWorkerId shared_worker_id, const SharedWorkerInstance& instance, blink::mojom::FetchClientSettingsObjectPtr outside_fetch_client_settings_object, GlobalFrameRoutingId creator_render_frame_host_id, const std::string& storage_domain, const blink::MessagePortChannel& message_port, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory); void StartWorker( base::WeakPtr<SharedWorkerHost> host, const blink::MessagePortChannel& message_port, blink::mojom::FetchClientSettingsObjectPtr outside_fetch_client_settings_object, bool did_fetch_worker_script, std::unique_ptr<blink::PendingURLLoaderFactoryBundle> subresource_loader_factories, blink::mojom::WorkerMainScriptLoadParamsPtr main_script_load_params, blink::mojom::ControllerServiceWorkerInfoPtr controller, base::WeakPtr<ServiceWorkerObjectHost> controller_service_worker_object_host, const GURL& final_response_url); // Returns nullptr if there is no such host. SharedWorkerHost* FindMatchingSharedWorkerHost( const GURL& url, const std::string& name, const url::Origin& constructor_origin); void ScriptLoadFailed( mojo::PendingRemote<blink::mojom::SharedWorkerClient> client, const std::string& error_message); // Generates IDs for new shared workers. SharedWorkerId::Generator shared_worker_id_generator_; std::set<std::unique_ptr<SharedWorkerHost>, base::UniquePtrComparator> worker_hosts_; // |storage_partition_| owns |this|. StoragePartitionImpl* const storage_partition_; scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_; scoped_refptr<ChromeAppCacheService> appcache_service_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_override_; // Keeps a reference count of each worker-client pair so as to not send // duplicate OnClientAdded() notifications if the same frame connects multiple // times to the same shared worker. Note that this is a situation unique to // shared worker and cannot happen with dedicated workers and service workers. base::flat_map<std::pair<SharedWorkerId, GlobalFrameRoutingId>, int> shared_worker_client_counts_; base::ObserverList<Observer> observers_; base::WeakPtrFactory<SharedWorkerServiceImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SharedWorkerServiceImpl); }; } // namespace content #endif // CONTENT_BROWSER_WORKER_HOST_SHARED_WORKER_SERVICE_IMPL_H_
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
e7a6f2f0fec4c251e7e70588005de24d9d69bbb9
10c2506e01ac4ae7fb870fe7c6774d44617f4356
/NetWorkAdapterSetDlg.h
eb589e48785c739dafa89e2e7a6274bab0e20b1c
[ "MIT" ]
permissive
thfools/networkmonitor
7a00b7d351555f690d2595fbc0d62c41774d38a0
b58e7c6643922790d1cd51a401ba95f7e5c7d022
refs/heads/master
2021-05-11T03:37:11.041736
2016-08-28T08:42:02
2016-08-28T08:42:02
null
0
0
null
null
null
null
GB18030
C++
false
false
2,135
h
/* =============================================================================== The MIT License Copyright (C) 1994-2015 simawei<simawei@qq.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== */ #pragma once #include "afxcmn.h" // CNetWorkAdapterSetDlg 对话框 /************************************************************************/ /* 选择网卡对话框 */ /************************************************************************/ class CNetWorkAdapterSetDlg : public CDialog { DECLARE_DYNAMIC(CNetWorkAdapterSetDlg) public: CNetWorkAdapterSetDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CNetWorkAdapterSetDlg(); // 对话框数据 enum { IDD = IDD_NETWORKADAPTERSETDLG }; protected: virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() int GetSelectedItem(); public: CListCtrl m_listctrl; afx_msg void OnBnClickedOk(); afx_msg void OnNMDblclkList1(NMHDR *pNMHDR, LRESULT *pResult); };
[ "simawei@qq.com" ]
simawei@qq.com
19bc5023ae647a49a6cd6771a6c4ed70f632af2a
7638fd801d33c47dd4975b620c753b673e2a2954
/chrome/browser/ash/arc/nearby_share/nearby_share_session_impl.cc
1eea0ed018dfb3270603b37aef66ee15b22a438f
[ "BSD-3-Clause" ]
permissive
Mancoi64/chromium
06c6690c55d7c36ec9d97dda872f4f092bb5e845
34d255f7dd4dc91e671ed75b68bc0ae71480782c
refs/heads/master
2023-08-15T01:17:42.732355
2021-10-01T06:51:55
2021-10-01T06:51:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,208
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/arc/nearby_share/nearby_share_session_impl.h" #include <memory> #include <string> #include <vector> #include "ash/public/cpp/app_types_util.h" #include "base/bind.h" #include "base/callback_forward.h" #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/numerics/safe_conversions.h" #include "base/system/sys_info.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/apps/app_service/intent_util.h" #include "chrome/browser/ash/arc/arc_util.h" #include "chrome/browser/ash/arc/nearby_share/arc_nearby_share_uma.h" #include "chrome/browser/ash/arc/nearby_share/ui/error_dialog_view.h" #include "chrome/browser/ash/arc/nearby_share/ui/low_disk_space_dialog_view.h" #include "chrome/browser/ash/arc/nearby_share/ui/nearby_share_overlay_view.h" #include "chrome/browser/ash/arc/nearby_share/ui/progress_bar_dialog_view.h" #include "chrome/browser/ash/file_manager/path_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sharesheet/sharesheet_service.h" #include "chrome/browser/sharesheet/sharesheet_service_factory.h" #include "chrome/browser/sharesheet/sharesheet_types.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom-forward.h" #include "chrome/browser/webshare/prepare_directory_task.h" #include "chrome/common/chrome_paths_internal.h" #include "components/arc/arc_util.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "content/public/browser/browser_thread.h" #include "third_party/cros_system_api/constants/cryptohome.h" namespace arc { namespace { // Maximum time to wait for the ARC window to be initialized. // ARC Wayland messages and Mojo messages are sent across the same pipe. The // order in which the messages are sent is not deterministic. If the ARC // activity starts Nearby Share before the wayland message for the new has been // processed, the corresponding aura::Window for a given ARC activity task ID // will not be found. To get around this, NearbyShareSessionImpl will wait a // little while for the Wayland message to be processed and the window to be // initialized. constexpr base::TimeDelta kWindowInitializationTimeout = base::TimeDelta::FromSeconds(1); constexpr base::TimeDelta kProgressBarUpdateInterval = base::TimeDelta::FromMilliseconds(1500); constexpr uint64_t kShowProgressBarMinSizeInBytes = 12000000; // 12MB. constexpr char kIntentExtraText[] = "android.intent.extra.TEXT"; constexpr base::FilePath::CharType kArcNearbyShareDirname[] = FILE_PATH_LITERAL(".NearbyShare"); void DeletePathAndFiles(const base::FilePath& file_path) { DVLOG(1) << __func__; if (!file_path.empty() && base::PathExists(file_path)) { base::DeletePathRecursively(file_path); } } // Calculate the amount of disk space, in bytes, needed in |share_dir| to // stream |total_file_size| bytes from Android to the Chrome OS file system. static const int64_t CalculateRequiredSpace(const base::FilePath share_dir, const uint64_t total_file_size) { DVLOG(1) << __func__; int64_t free_disk_space = base::SysInfo::AmountOfFreeDiskSpace(share_dir); VLOG(1) << "Free disk space: " << free_disk_space; int64_t shared_files_size = static_cast<int64_t>(cryptohome::kMinFreeSpaceInBytes + total_file_size); VLOG(1) << "Shared file size: " << shared_files_size; return shared_files_size - free_disk_space; } } // namespace NearbyShareSessionImpl::NearbyShareSessionImpl( Profile* profile, uint32_t task_id, mojom::ShareIntentInfoPtr share_info, mojo::PendingRemote<mojom::NearbyShareSessionInstance> session_instance, mojo::PendingReceiver<mojom::NearbyShareSessionHost> session_receiver, SessionFinishedCallback session_finished_callback) : task_id_(task_id), session_instance_(std::move(session_instance)), session_receiver_(this, std::move(session_receiver)), share_info_(std::move(share_info)), profile_(profile), backend_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( // Should be USER_VISIBLE because we are downloading files requested // by the user and updating the UI on progress of transfers. // IO operations for temp files / directories cleanup should be // completed before shutdown. {base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), session_finished_callback_(std::move(session_finished_callback)) { session_receiver_.set_disconnect_handler(base::BindOnce( &NearbyShareSessionImpl::CleanupSession, weak_ptr_factory_.GetWeakPtr(), /*should_cleanup_files=*/true)); aura::Window* const arc_window = GetArcWindow(task_id_); if (arc_window) { VLOG(1) << "ARC window found"; UpdateNearbyShareWindowFound(true); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&NearbyShareSessionImpl::OnArcWindowFound, weak_ptr_factory_.GetWeakPtr(), arc_window)); } else { VLOG(1) << "No ARC window found for task ID: " << task_id_; env_observation_.Observe(aura::Env::GetInstance()); window_initialization_timer_.Start(FROM_HERE, kWindowInitializationTimeout, this, &NearbyShareSessionImpl::OnTimerFired); } } NearbyShareSessionImpl::~NearbyShareSessionImpl() = default; // static base::FilePath NearbyShareSessionImpl::GetUserCacheFilePath( const Profile* profile) { DCHECK(profile); base::FilePath cache_base_path; chrome::GetUserCacheDirectory(profile->GetPath(), &cache_base_path); return cache_base_path.Append(kArcNearbyShareDirname); } void NearbyShareSessionImpl::OnNearbyShareClosed( views::Widget::ClosedReason reason) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DVLOG(1) << __func__; // If share is not continuing after sharesheet closes (e.g. cancel, esc key, // lost focus, etc.), we will clean up the current session including files. // Otherwise cleanup session object and wait for Nearby Share to cleanup cache // files when they are no longer needed for transfer. bool should_cleanup_files = reason != views::Widget::ClosedReason::kAcceptButtonClicked; CleanupSession(should_cleanup_files); } // Overridden from aura::EnvObserver: void NearbyShareSessionImpl::OnWindowInitialized(aura::Window* const window) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(window); DVLOG(1) << __func__; if (ash::IsArcWindow(window) && (arc::GetWindowTaskId(window) == task_id_)) { env_observation_.Reset(); arc_window_observation_.Observe(window); } } // Overridden from aura::WindowObserver void NearbyShareSessionImpl::OnWindowVisibilityChanged( aura::Window* const window, bool visible) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DVLOG(1) << __func__; absl::optional<int> task_id = arc::GetWindowTaskId(window); DCHECK(task_id.has_value()); DCHECK_GE(task_id.value(), 0); if (visible && (base::checked_cast<uint32_t>(task_id.value()) == task_id_)) { VLOG(1) << "ARC Window is visible"; if (window_initialization_timer_.IsRunning()) { window_initialization_timer_.Stop(); } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&NearbyShareSessionImpl::OnArcWindowFound, weak_ptr_factory_.GetWeakPtr(), window)); } } void NearbyShareSessionImpl::OnArcWindowFound(aura::Window* const arc_window) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(arc_window); DCHECK(profile_); DVLOG(1) << __func__; arc_window_ = arc_window; if (share_info_->files.has_value()) { // File sharing. const base::FilePath arc_nearby_share_directory = GetUserCacheFilePath(profile_); file_handler_ = base::MakeRefCounted<ShareInfoFileHandler>( profile_, share_info_.get(), arc_nearby_share_directory, backend_task_runner_); prepare_directory_task_ = std::make_unique<webshare::PrepareDirectoryTask>( arc_nearby_share_directory, file_handler_->GetTotalSizeOfFiles()); prepare_directory_task_->StartWithCallback( base::BindOnce(&NearbyShareSessionImpl::OnPreparedDirectory, weak_ptr_factory_.GetWeakPtr())); } else { // Sharing text. ShowNearbyShareBubbleInArcWindow(); } } apps::mojom::IntentPtr NearbyShareSessionImpl::ConvertShareIntentInfoToIntent() const { DCHECK(share_info_); DVLOG(1) << __func__; std::string text; if (share_info_->extras.has_value() && share_info_->extras->contains(kIntentExtraText)) { text = share_info_->extras->at(kIntentExtraText); } // Sharing files & text if (share_info_->files.has_value()) { const auto share_file_paths = file_handler_->GetFilePaths(); DCHECK_GT(share_file_paths.size(), 0); const auto share_file_mime_types = file_handler_->GetMimeTypes(); const size_t expected_total_files = file_handler_->GetNumberOfFiles(); DCHECK_GT(expected_total_files, 0); if (share_file_paths.size() != expected_total_files) { LOG(ERROR) << "Actual number of files streamed does not match expected number: " << expected_total_files; return nullptr; } return apps_util::CreateShareIntentFromFiles( absl::nullopt, share_file_paths, share_file_mime_types, text, share_info_->title); } // Sharing only text if (!text.empty()) { apps::mojom::IntentPtr share_intent = apps_util::CreateShareIntentFromText(text, share_info_->title); share_intent->mime_type = share_info_->mime_type; return share_intent; } return nullptr; } void NearbyShareSessionImpl::OnPreparedDirectory(base::File::Error result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(arc_window_); DCHECK_GT(file_handler_->GetTotalSizeOfFiles(), 0); DVLOG(1) << __func__; if (result == base::File::FILE_ERROR_NO_SPACE) { LOG(ERROR) << "Not enough disk space to proceed with sharing."; // Calculate required space and then show the LowDiskSpace Dialog backend_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&CalculateRequiredSpace, file_handler_->GetShareDirectory(), file_handler_->GetTotalSizeOfFiles()), base::BindOnce(&NearbyShareSessionImpl::OnShowLowDiskSpaceDialog, weak_ptr_factory_.GetWeakPtr())); return; } // TODO(b/191232168): Figure out why PrepareDirectoryTask is flaky. Ignoring // the error seem to always work otherwise will sometimes return error. PLOG_IF(WARNING, result != base::File::FILE_OK) << "Prepare Directory was not successful"; file_handler_->StartPreparingFiles( /*started_callback=*/base::BindOnce( &NearbyShareSessionImpl::OnFileStreamingStarted, weak_ptr_factory_.GetWeakPtr()), /*completed_callback=*/ base::BindOnce(&NearbyShareSessionImpl::ShowNearbyShareBubbleInArcWindow, weak_ptr_factory_.GetWeakPtr()), /*update_callback=*/ base::BindRepeating(&NearbyShareSessionImpl::OnProgressBarUpdate, weak_ptr_factory_.GetWeakPtr())); } void NearbyShareSessionImpl::OnNearbyShareBubbleShown( sharesheet::SharesheetResult result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (VLOG_IS_ON(1)) { switch (result) { case sharesheet::SharesheetResult::kSuccess: VLOG(1) << "OnNearbyShareBubbleShown: SUCCESS"; break; case sharesheet::SharesheetResult::kCancel: VLOG(1) << "OnNearbyShareBubbleShown: CANCEL"; break; case sharesheet::SharesheetResult::kErrorAlreadyOpen: VLOG(1) << "OnNearbyShareBubbleShown: ALREADY OPEN"; break; default: VLOG(1) << "OnNearbyShareBubbleShown: UNKNOWN"; } } if (result != sharesheet::SharesheetResult::kSuccess) { ShowErrorDialog(); } } void NearbyShareSessionImpl::OnFileStreamingStarted() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(arc_window_); DCHECK(file_handler_); DVLOG(1) << __func__; // Only show the progress bar if total files size is greater than // |kShowProgressBarMinSizeInBytes|, otherwise minimize unnecessary // UI step as the file streaming time should be < 1 second. if (file_handler_->GetTotalSizeOfFiles() > kShowProgressBarMinSizeInBytes) { const bool is_multiple_files = file_handler_->GetNumberOfFiles() > 1; progress_bar_view_ = std::make_unique<ProgressBarDialogView>(is_multiple_files); ProgressBarDialogView::Show(arc_window_, progress_bar_view_.get()); // Keep updating the progress bar if the interval timer elapsed to update // the user on the file streaming progress. progress_bar_update_timer_.Start( FROM_HERE, kProgressBarUpdateInterval, this, &NearbyShareSessionImpl::OnProgressBarIntervalElapsed); } } void NearbyShareSessionImpl::ShowNearbyShareBubbleInArcWindow( absl::optional<base::File::Error> result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(arc_window_); DVLOG(1) << __func__; // If the progress bar is visible at this point, stop the update interval // timer so that we can show the Nearby Share bubble. if (progress_bar_update_timer_.IsRunning()) { progress_bar_update_timer_.Stop(); } // Close any overlay and respective child views that may still be shown. progress_bar_view_.reset(); NearbyShareOverlayView::CloseOverlayOn(arc_window_); // Only applicable if sharing files. if (result.has_value() && result.value() != base::File::FILE_OK) { LOG(ERROR) << "Failed to complete file streaming with error: " << base::File::ErrorToString(result.value()); ShowErrorDialog(); return; } backend_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&NearbyShareSessionImpl::ConvertShareIntentInfoToIntent, base::Unretained(this)), base::BindOnce( &NearbyShareSessionImpl::OnConvertedShareIntentInfoToIntent, weak_ptr_factory_.GetWeakPtr())); } void NearbyShareSessionImpl::OnConvertedShareIntentInfoToIntent( apps::mojom::IntentPtr intent) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(arc_window_); DVLOG(1) << __func__; if (!intent) { LOG(ERROR) << "No share info found."; ShowErrorDialog(); return; } sharesheet::SharesheetService* sharesheet_service = sharesheet::SharesheetServiceFactory::GetForProfile(profile_); if (!sharesheet_service) { LOG(ERROR) << "Cannot find sharesheet service."; ShowErrorDialog(); return; } base::FilePath share_path; if (file_handler_) { share_path = file_handler_->GetShareDirectory(); } sharesheet_service->ShowNearbyShareBubbleForArc( arc_window_, std::move(intent), sharesheet::SharesheetMetrics::LaunchSource::kArcNearbyShare, /*delivered_callback=*/ base::BindOnce(&NearbyShareSessionImpl::OnNearbyShareBubbleShown, weak_ptr_factory_.GetWeakPtr()), /*close_callback=*/ base::BindOnce(&NearbyShareSessionImpl::OnNearbyShareClosed, weak_ptr_factory_.GetWeakPtr()), /*cleanup_callback=*/base::BindOnce(&DeletePathAndFiles, share_path)); } void NearbyShareSessionImpl::OnTimerFired() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // TODO(b/191232397): Handle error case. LOG(ERROR) << "ARC window didn't get initialized within " << kWindowInitializationTimeout.InSeconds() << " second(s)"; UpdateNearbyShareWindowFound(false); CleanupSession(/*should_cleanup_files=*/true); } void NearbyShareSessionImpl::OnProgressBarIntervalElapsed() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DVLOG(1) << __func__; if (progress_bar_view_) { progress_bar_view_->UpdateInterpolatedProgressBarValue(); } } void NearbyShareSessionImpl::OnProgressBarUpdate(double value) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DVLOG(1) << "OnProgressBarUpdate with value: " << value; if (progress_bar_view_) { // Only show value if there is forward progress. if (value > progress_bar_view_->GetProgressBarValue()) { progress_bar_view_->UpdateProgressBarValue(value); } } } void NearbyShareSessionImpl::CleanupSession(bool should_cleanup_files) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DVLOG(1) << __func__; // PrepareDirectoryTask must first relinquish ownership of |share_path|. prepare_directory_task_.reset(); if (file_handler_) { base::FilePath share_path = file_handler_->GetShareDirectory(); // Delete any file descriptor handles for files that were created during // the session and owned by |file_handler_|. Even if handles are released, // the physical files remain until DeletePathAndFiles is called. file_handler_.reset(); if (should_cleanup_files) { VLOG(1) << "Deleting session files including base path: " << share_path; // Delete any files and the top level share directory with the same // |backend_task_runner_| that is used for all file IO operations. // Make sure |session_finished_callback_| is not run until the // |backend_task_runner_| is no longer in use. backend_task_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(&DeletePathAndFiles, share_path), base::BindOnce(&NearbyShareSessionImpl::FinishSession, weak_ptr_factory_.GetWeakPtr())); return; } } FinishSession(); } void NearbyShareSessionImpl::ShowErrorDialog() { DCHECK(arc_window_); DVLOG(1) << __func__; ErrorDialogView::Show(arc_window_, base::BindOnce(&NearbyShareSessionImpl::CleanupSession, weak_ptr_factory_.GetWeakPtr(), /*should_cleanup_files=*/true)); } void NearbyShareSessionImpl::FinishSession() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(session_instance_); DVLOG(1) << __func__; // Stop timers and destroy any lingering UI surfaces or observers. arc_window_observation_.Reset(); env_observation_.Reset(); if (window_initialization_timer_.IsRunning()) { window_initialization_timer_.Stop(); } if (progress_bar_update_timer_.IsRunning()) { progress_bar_update_timer_.Stop(); } progress_bar_view_.reset(); aura::Window* const arc_window = GetArcWindow(task_id_); if (arc_window) { NearbyShareOverlayView::CloseOverlayOn(arc_window); } // Cleanup the session on Android side. session_instance_->OnNearbyShareViewClosed(); // Delete the session object by task ID from the ArcNearbyShareBridge map. if (session_finished_callback_) { VLOG(1) << "Deleting session with task ID: " << task_id_; std::move(session_finished_callback_).Run(task_id_); } } void NearbyShareSessionImpl::OnShowLowDiskSpaceDialog( int64_t required_disk_space) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_GT(required_disk_space, 0); DVLOG(1) << "OnCalculateRequiredSpace required_disk_space: " << required_disk_space; LowDiskSpaceDialogView::Show( arc_window_, file_handler_->GetNumberOfFiles(), required_disk_space, base::BindOnce(&NearbyShareSessionImpl::OnLowStorageDialogClosed, weak_ptr_factory_.GetWeakPtr())); } void NearbyShareSessionImpl::OnLowStorageDialogClosed( bool should_open_storage_settings) { if (should_open_storage_settings) { chrome::SettingsWindowManager::GetInstance()->ShowOSSettings( profile_, chromeos::settings::mojom::kStorageSubpagePath); } CleanupSession(/*should_cleanup_files=*/true); } } // namespace arc
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
819bb95b13bafcbc4398f6ddde7a61b78dfa9252
3f78ac9921f1d12340210045af9659f8485fb521
/ReliefMap/v5.cpp
e6563370c23ddc0504fa48700928961efdf12ee8
[]
no_license
cfyuen/Topcoder-Marathon
d2d1d42540081255432bdd2e34b9f255c83bf84d
0b617f323212ea08a48c1a7748696ddef669178b
refs/heads/master
2020-03-19T06:01:34.617770
2018-06-04T08:16:26
2018-06-04T08:16:26
135,984,163
0
0
null
null
null
null
UTF-8
C++
false
false
42,649
cpp
#include<iostream> #include<vector> #include<string> #include<cstdio> #include<algorithm> #include<ctime> #include<cstdlib> #include<fstream> #include<cmath> #include<queue> using namespace std; template <class NUM> NUM sqr (NUM X) { return X*X; } struct coor { int x,y; } low,high; int w,h,v[600][600],per[600][600],em[600][600],draw[600][600],appr[600][600],repave=6,canind=0; vector<double> ret; vector<pair<double,double> > edge,cand; vector<pair<int,double> > est[600][600]; vector<string> contour; vector<pair<coor,double> > known,edgpt; int dx[]={1,-1,0,0},dy[]={0,0,1,-1},d8x[]={1,1,1,0,0,-1,-1,-1},d8y[]={-1,0,1,-1,1,-1,0,1}; double D=0.0,ask[600][600]; //delete when submit FILE *debug,*result; int localtest=0,stseed=0,endseed=10; int NoM=0; double C[600][600]; int sttime; int tcnt=0; void start() { sttime=clock(); } double runtime() { return (clock()-sttime)/1000.0; } double dourand() { return (rand()*32768+rand())/1073741824.0; } double Gaussian() { double a,b,r; do { a=dourand()*2-1; b=dourand()*2-1; r=a*a+b*b; } while (r*r>1); return sqrt(-2*log(r*r)/(r*r))*a; } class Relief { public: double measure (int x,int y) { if (localtest==0) { printf("?\n%d\n%d\n",x,y); fflush(stdout); double Mret; scanf("%lf",&Mret); return Mret; } else { NoM++; return max(min(C[y][x] + Gaussian(),100.0),0.0); } } }; Relief Relief; //til here /* have it when submit timeval sttime; void start() { gettimeofday(&sttime,NULL); } double runtime() { timeval tt, nowt; gettimeofday(&tt,NULL); timersub(&tt,&sttime,&nowt); return (nowt.tv_sec*1000+nowt.tv_usec/1000)/1000.0; } */ class ReliefMap { public: double accmea (int x,int y) { double td[5]; if (ask[y][x]>-1e-9) return ask[y][x]; for (int i=0; i<3; i++) td[i]=Relief.measure(x,y); sort(td,td+3); ask[y][x]=td[1]; return td[1]; } int extpt (int x,int y) { if (x<0 || x>=h || y<0 || y>=w) return 0; if (contour[x][y]!='1') return 0; if (x==0 || y==0 || x==h-1 || y==w-1) return 0; for (int i=0; i<4; i++) if (x+dx[i]>=0 && x+dx[i]<h && y+dy[i]>=0 && y+dy[i]<w && contour[x+dx[i]][y+dy[i]]=='0') return 0; return 1; } vector <double> getMap(vector <string> Contour) { contour=Contour; w=contour[0].length(); h=contour.size(); ret.clear(); ret.resize(w*h); for (int i=0; i<w*h; i++) ret[i]=-1.0; memset(v,0,sizeof(v)); memset(per,0,sizeof(per)); memset(em,0,sizeof(em)); low.x=low.y=high.x=high.y=-1; D=0.0; edge.clear(); known.clear(); for (int i=0; i<h; i++) for (int j=0; j<w; j++) ask[i][j]=-1; start(); for (int k=0; k<h; k++) { for (int l=0; l<w; l++) if (contour[k][l]=='1') { if (v[k][l]==0) fprintf(debug,"*"); else fprintf(debug,"!"); } else fprintf(debug,"%d",v[k][l]); fprintf(debug,"\n"); } //find D memset(v,0,sizeof(v)); for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (extpt(i,j)==1 && v[i][j]==0) { /* if (extpt(i-1,j)==0 && extpt(i+1,j)==0 && extpt(i,j-1)==0 && extpt(i,j+1)==0) { coor tc; tc.x=i; tc.y=j; double td=accmea(j,i); known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); } */ coor tc; tc.x=i; tc.y=j; double td=accmea(j,i); known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); queue<coor> eq; v[tc.x][tc.y]=1; eq.push(tc); while (!eq.empty()) { tc=eq.front(); eq.pop(); for (int l=0; l<4; l++) { coor ttc; ttc.x=tc.x+dx[l]; ttc.y=tc.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) if (v[ttc.x][ttc.y]==0 && contour[ttc.x][ttc.y]=='1') { v[ttc.x][ttc.y]=1; eq.push(ttc); } } } } for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (per[i][j]==0 && contour[i][j]=='0') { coor now; now.x=i; now.y=j; int line=0; memset(v,0,sizeof(v)); queue<coor> fq; fq.push(now); per[now.x][now.y]=1; v[now.x][now.y]=1; while (!fq.empty()) { now=fq.front(); fq.pop(); for (int k=0; k<8; k++) if (now.x+d8x[k]>=0 && now.x+d8x[k]<h && now.y+d8y[k]>=0 && now.y+d8y[k]<w && v[now.x+d8x[k]][now.y+d8y[k]]==0) { coor tc; tc.x=now.x+d8x[k]; tc.y=now.y+d8y[k]; if (contour[tc.x][tc.y]=='1') { line++; int isline=0; queue<coor> lq; lq.push(tc); v[tc.x][tc.y]=1; per[tc.x][tc.y]=2; while (!lq.empty()) { tc=lq.front(); //fprintf(debug,"%d %d\n",tc.x,tc.y); lq.pop(); int testex=0; if (extpt(tc.x,tc.y)==1) testex=1; for (int l=0; l<4; l++) if (tc.x+dx[l]>=0 && tc.x+dx[l]<h && tc.y+dy[l]>=0 && tc.y+dy[l]<w) if (contour[tc.x+dx[l]][tc.y+dy[l]]=='1' && extpt(tc.x+dx[l],tc.y+dy[l])==1) testex=1; if (testex==0) isline=1; for (int l=0; l<4; l++) if (tc.x+dx[l]>=0 && tc.x+dx[l]<h && tc.y+dy[l]>=0 && tc.y+dy[l]<w) if (v[tc.x+dx[l]][tc.y+dy[l]]==0 && contour[tc.x+dx[l]][tc.y+dy[l]]=='1') { coor ttc=tc; ttc.x+=dx[l]; ttc.y+=dy[l]; v[ttc.x][ttc.y]=1; per[ttc.x][ttc.y]=2; lq.push(ttc); } } if (isline==0) line--; } else { v[tc.x][tc.y]=1; per[tc.x][tc.y]=1; fq.push(tc); } } } /* for (int k=0; k<h; k++) { for (int l=0; l<w; l++) if (contour[k][l]=='1') { if (v[k][l]==0) fprintf(debug,"*"); else fprintf(debug,"!"); } else fprintf(debug,"%d",v[k][l]); fprintf(debug,"\n"); } */ //fprintf(debug,"l=%d\n",line); if (line<2) { fprintf(debug,"LINE==1\n"); int addedge=1; for (int k=0; k<h; k++) for (int l=0; l<w; l++) if (v[k][l]==1 && extpt(k,l)==1) { if (ask[k][l]<-1e-9) { double ph=accmea(l,k); coor tc; tc.x=k; tc.y=l; //known.push_back(make_pair(tc,ph)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,ph); } addedge=0; goto stop; } stop: ; if (addedge==1 && edge.size()<4) { /* int point=0; double toth=0.0; coor tc; for (int k=0; k<h; k++) for (int l=0; l<w; l++) if (v[k][l]==1 && contour[k][l]=='1' && point<repave) { double tm[4]; int tdx[4],tdy[4]; memset(tdx,-1,sizeof(tdx)); tdx[0]=k; tdy[0]=l; for (int m=0; m<4; m++) if (k+dx[m]>=0 && k+dx[m]<h && l+dy[m]>=0 && l+dy[m]<w && contour[k+dx[m]][l+dy[m]]=='0') if (v[k+dx[m]][l+dy[m]]==1) { tdx[1]=k+dx[m]; tdy[1]=l+dy[m]; break; } for (int m=0; m<4; m++) if (k+dx[m]>=0 && k+dx[m]<h && l+dy[m]>=0 && l+dy[m]<w && contour[k+dx[m]][l+dy[m]]=='0') if (v[k+dx[m]][l+dy[m]]==0) { tdx[2]=k+dx[m]; tdy[2]=l+dy[m]; break; } if (tdx[1]!=-1 && tdx[2]!=-1) { for (int m=0; m<3; m++) tm[m]=Relief.measure(tdy[m],tdx[m]); for (int m=0; m<3; m++) toth+=tm[m]; toth-=max(tm[0],max(tm[1],tm[2])); fprintf(debug,"(%d,%d)-%0.4lf (%d,%d)-%0.4lf (%d,%d)-%0.4lf %0.4lf\n",tdx[0],tdy[0],tm[0],tdx[1],tdy[1],tm[1],tdx[2],tdy[2],tm[2],toth); tc.x=k; tc.y=l; point++; } } edge.push_back(toth/(point*2)); fprintf(debug,"edge: (%d,%d) %0.4lf\n",tc.x,tc.y,toth/(point*2)); */ coor tc; for (int k=0; k<h; k++) for (int l=0; l<w; l++) if (v[k][l]==1 && contour[k][l]=='1') { double tm[4],toth=0.0; int tdx[4],tdy[4]; memset(tdx,-1,sizeof(tdx)); tdx[0]=k; tdy[0]=l; for (int m=0; m<4; m++) if (k+dx[m]>=0 && k+dx[m]<h && l+dy[m]>=0 && l+dy[m]<w && contour[k+dx[m]][l+dy[m]]=='0') if (v[k+dx[m]][l+dy[m]]==1) { tdx[1]=k+dx[m]; tdy[1]=l+dy[m]; break; } for (int m=0; m<4; m++) if (k+dx[m]>=0 && k+dx[m]<h && l+dy[m]>=0 && l+dy[m]<w && contour[k+dx[m]][l+dy[m]]=='0') if (v[k+dx[m]][l+dy[m]]==0) { tdx[2]=k+dx[m]; tdy[2]=l+dy[m]; break; } if (tdx[1]!=-1 && tdx[2]!=-1) { for (int m=0; m<3; m++) { tm[m]=accmea(tdy[m],tdx[m]); //original pos } tc.x=tdx[0]; tc.y=tdy[0]; known.push_back(make_pair(tc,tm[0])); toth=(tm[0]+min(tm[1],tm[2]))/2; fprintf(debug,"(%d,%d)-%0.4lf (%d,%d)-%0.4lf (%d,%d)-%0.4lf %0.4lf\n",tdx[0],tdy[0],tm[0],tdx[1],tdy[1],tm[1],tdx[2],tdy[2],tm[2],toth); tc.x=k; tc.y=l; edge.push_back(make_pair(min(tm[1],tm[2]),tm[0])); fprintf(debug,"edge: (%d,%d) %0.4lf\n",tc.x,tc.y,toth); goto finish; } } finish: ; } } //fprintf(debug,"\n\n"); } queue<coor> eq; memset(v,0,sizeof(v)); for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (extpt(i,j)==1) { v[i][j]=1; v[i+1][j]=1; v[i-1][j]=1; v[i][j+1]=1; v[i][j-1]=1; } coor tc; tc.x=h/2; tc.y=w/2; eq.push(tc); v[tc.x][tc.y]=1; while (edge.size()<4 && !eq.empty()) { tc=eq.front(); eq.pop(); if (contour[tc.x][tc.y]=='1' && extpt(tc.x,tc.y)==0 && em[tc.x][tc.y]==0) { double tm[4],toth=0.0; int tdx[4],tdy[4]; memset(tdx,-1,sizeof(tdx)); fprintf(debug,"(%d %d)\n",tc.x,tc.y); tdx[0]=tc.x; tdy[0]=tc.y; for (int m=0; m<4; m++) if (tc.x+dx[m]>=0 && tc.x+dx[m]<h && tc.y+dy[m]>=0 && tc.y+dy[m]<w && contour[tc.x+dx[m]][tc.y+dy[m]]=='0') if (v[tc.x+dx[m]][tc.y+dy[m]]==1) { tdx[1]=tc.x+dx[m]; tdy[1]=tc.y+dy[m]; break; } for (int m=0; m<4; m++) if (tc.x+dx[m]>=0 && tc.x+dx[m]<h && tc.y+dy[m]>=0 && tc.y+dy[m]<w && contour[tc.x+dx[m]][tc.y+dy[m]]=='0') if (v[tc.x+dx[m]][tc.y+dy[m]]==0) { tdx[2]=tc.x+dx[m]; tdy[2]=tc.y+dy[m]; break; } if (tdx[1]!=-1 && tdx[2]!=-1) { for (int m=0; m<3; m++) { tm[m]=accmea(tdy[m],tdx[m]); //original pos } coor ttc; ttc.x=tdx[0]; ttc.y=tdy[0]; //known.push_back(make_pair(ttc,tm[0])); toth=(tm[0]+min(tm[1],tm[2]))/2; fprintf(debug,"(%d,%d)-%0.4lf (%d,%d)-%0.4lf (%d,%d)-%0.4lf %0.4lf\n",tdx[0],tdy[0],tm[0],tdx[1],tdy[1],tm[1],tdx[2],tdy[2],tm[2],toth); edge.push_back(make_pair(min(tm[1],tm[2]),tm[0])); fprintf(debug,"edge: (%d,%d) %0.4lf\n",tc.x,tc.y,toth); queue<coor> lq; lq.push(tc); em[tc.x][tc.y]=1; coor now; while (!lq.empty()) { now=lq.front(); lq.pop(); for (int i=0; i<4; i++) if (now.x+dx[i]>=0 && now.x+dx[i]<h && now.y+dy[i]>=0 && now.y+dy[i]<w && contour[now.x+dx[i]][now.y+dy[i]]=='1' && em[now.x+dx[i]][now.y+dy[i]]==0) { em[now.x+dx[i]][now.y+dy[i]]=1; coor ttc; ttc.x=now.x+dx[i]; ttc.y=now.y+dy[i]; lq.push(ttc); } } } } for (int i=0; i<4; i++) if (tc.x+dx[i]>=0 && tc.x+dx[i]<h && tc.y+dy[i]>=0 && tc.y+dy[i]<w && v[tc.x+dx[i]][tc.y+dy[i]]==0) { v[tc.x+dx[i]][tc.y+dy[i]]=1; coor ttc; ttc.x=tc.x+dx[i]; ttc.y=tc.y+dy[i]; eq.push(ttc); } } fprintf(debug,"AllEdge: %d\n",edge.size()); for (int i=0; i<edge.size(); i++) fprintf(debug,"%d: %0.4lf-%0.4lf, %0.4lf\n",i,edge[i].first,edge[i].second,(edge[i].first+edge[i].second)/2); //use edge data to calculate D double lasterr=1e10,stpt=1e10; int ok=0; for (int i=0; i<edge.size(); i++) { stpt=min(stpt,(edge[i].first+edge[i].second)/2); for (int j=i+1; j<edge.size(); j++) if (abs( (edge[i].first+edge[i].second)/2-(edge[j].first+edge[j].second)/2 )>1.45) stpt=min(stpt,abs( (edge[i].first+edge[i].second)/2-(edge[j].first+edge[j].second)/2 )); } fprintf(debug,"stpt = %0.4lf\n",stpt); for (double td=max(2.0,stpt*0.8); td<10; td+=1e-3) { double err=0.0; for (int i=0; i<edge.size(); i++) err+=sqrt(abs(((edge[i].first+edge[i].second)/2)/td-(int)(((edge[i].first+edge[i].second)/2)/td+0.5))); //if (td<stpt+2) fprintf(debug,"%0.4lf: %0.4lf\n",td,err); if (err>lasterr) { if (ok==1) cand.push_back(make_pair(err,td-1e-3)); ok=0; } else ok=1; lasterr=err; } sort(cand.begin(),cand.end()); int tsz=cand.size(); for (int i=0; i<tsz; i++) if (cand[i].second/2>2) cand.push_back(make_pair(cand[i].first,cand[i].second/2)); D=cand[0].second; for (int i=0; i<cand.size(); i++) fprintf(debug,"canD: %0.4lf\n",cand[i].second); fprintf(debug,"time find D: %0.4lfs\n",runtime()); //find out all contour line int fillall=1,newlin=0,rep=0; adjust: rep=0; fprintf(debug,"D = %0.4lf\n",D); memset(draw,0,sizeof(draw)); for (int i=0; i<h; i++) for (int j=0; j<w; j++) est[i][j].clear(); fillall=1; do { vector<coor> willdraw; fillall=1; newlin=0; for (int i=0; i<known.size(); i++) for (int j=i+1; j<known.size(); j++) { coor c1=known[i].first,c2=known[j].first; willdraw.clear(); double h1=known[i].second,h2=known[j].second; int lvl1=(int)(h1/D),lvl2=(int)(h2/D); if (abs(c1.x-c2.x)+abs(c1.y-c2.y)>5) { int betw=0; if (abs(c1.x-c2.x)>abs(c1.y-c2.y)) { if (c1.x>c2.x) { swap(c1,c2); swap(h1,h2); swap(lvl1,lvl2); } int edb=0,prev=0; for (int k=0; k<4; k++) { if (c1.x+dx[k]>=0 && c1.x+dx[k]<h && c1.y+dy[k]>=0 && c1.y+dy[k]<w && contour[c1.x+dx[k]][c1.y+dy[k]]=='1') edb++; if (!(c1.x+dx[k]>=0 && c1.x+dx[k]<h && c1.y+dy[k]>=0 && c1.y+dy[k]<w)) edb++; } if (extpt(c1.x,c1.y)==0 && edb>=2 && contour[c1.x][c1.y]=='1') { prev=1; willdraw.push_back(c1); betw++; } else prev=0; for (int tx=c1.x+1; tx<=c2.x; tx++) { int ty=c1.y+(int)((c2.y-c1.y)*((tx-c1.x)*1.0/(c2.x-c1.x))); edb=0; for (int k=0; k<4; k++) { if (tx+dx[k]>=0 && tx+dx[k]<h && ty+dy[k]>=0 && ty+dy[k]<w && contour[tx+dx[k]][ty+dy[k]]=='1') edb++; if (!(tx+dx[k]>=0 && tx+dx[k]<h && ty+dy[k]>=0 && ty+dy[k]<w)) edb++; } if (extpt(tx,ty)==0 && edb>=2 && contour[tx][ty]=='1') { if (prev==0) { coor tc; tc.x=tx; tc.y=ty; willdraw.push_back(tc); prev=1; betw++; } } else prev=0; } } else { if (c1.y>c2.y) { swap(c1,c2); swap(h1,h2); swap(lvl1,lvl2); } int edb=0,prev=0; for (int k=0; k<4; k++) { if (c1.x+dx[k]>=0 && c1.x+dx[k]<h && c1.y+dy[k]>=0 && c1.y+dy[k]<w && contour[c1.x+dx[k]][c1.y+dy[k]]=='1') edb++; if (!(c1.x+dx[k]>=0 && c1.x+dx[k]<h && c1.y+dy[k]>=0 && c1.y+dy[k]<w)) edb++; } if (extpt(c1.x,c1.y)==0 && edb>=2 && contour[c1.x][c1.y]=='1') { prev=1; willdraw.push_back(c1); betw++; } else prev=0; for (int ty=c1.y+1; ty<=c2.y; ty++) { int tx=c1.x+(int)((c2.x-c1.x)*((ty-c1.y)*1.0/(c2.y-c1.y))); edb=0; for (int k=0; k<4; k++) { if (tx+dx[k]>=0 && tx+dx[k]<h && ty+dy[k]>=0 && ty+dy[k]<w && contour[tx+dx[k]][ty+dy[k]]=='1') edb++; if (!(tx+dx[k]>=0 && tx+dx[k]<h && ty+dy[k]>=0 && ty+dy[k]<w)) edb++; } if (extpt(tx,ty)==0 && edb>=2 && contour[tx][ty]=='1') { if (prev==0) { coor tc; tc.x=tx; tc.y=ty; willdraw.push_back(tc); prev=1; betw++; } } else prev=0; } } fprintf(debug,"(%d,%d) %0.4lf -- (%d,%d) %0.4lf\n",c1.x,c1.y,h1,c2.x,c2.y,h2); fprintf(debug,"%d %d betw:%d\n",lvl1,lvl2,betw); if (abs(lvl2-lvl1)>=betw+3) { canind++; if (canind==cand.size()) break; D=cand[canind].second; goto adjust; } if (abs(lvl2-lvl1)>=betw-1 && betw>0) { //if (abs(lvl2-lvl1)==betw && betw>0) { int mul,initlvl; if (lvl2>lvl1) { mul=1; initlvl=(int)(min(h1-0.8,100.0)/D)+1; //fprintf(debug,"initlvl: %0.4lf\n",initlvl*D); int fx=willdraw[0].x,fy=willdraw[0].y; if ((abs(fx-c2.x)<=1 || abs(fy-c2.y)<=1) && abs(fx-c2.x)+abs(fy-c2.y)<=5) initlvl++; //fprintf(debug,"initlvl: %0.4lf\n",initlvl*D); } else { mul=-1; initlvl=(int)(min(h2+0.8,100.0)/D); initlvl+=willdraw.size(); int fx=willdraw[willdraw.size()-1].x,fy=willdraw[willdraw.size()-1].y; //fprintf(debug,"fin(%d,%d) %d initlvl: %0.4lf\n",fx,fy,abs(fx-c2.x)+abs(fy-c2.y),initlvl*D); fflush(debug); if ((abs(fx-c2.x)<=1 || abs(fy-c2.y)<=1) && abs(fx-c2.x)+abs(fy-c2.y)<=5) initlvl--; //fprintf(debug,"initlvl: %0.4lf\n",initlvl*D); } //flood fill contour line int check=0; for (int k=0; k<willdraw.size(); k++) { coor tc=willdraw[k]; double here=(initlvl+mul*k)*D; if ((check==0 || k==willdraw.size()-1)) { double cmea; check=1; if (draw[tc.x][tc.y]==0) cmea=accmea(tc.y,tc.x); else cmea=ret[tc.x*w+tc.y]; if (abs(here-cmea)>2.2) { fprintf(debug,"corr (%d,%d):%0.4lf %0.4lf\n",tc.x,tc.y,here,cmea); if (here>cmea) initlvl-=(int)((here-cmea)/D+0.5); else initlvl+=(int)((cmea-here)/D+0.5); } } here=(initlvl+mul*k)*D; if (draw[tc.x][tc.y]==0) { newlin=1; fprintf(debug,"(%d,%d) nhere:%0.4lf\n",tc.x,tc.y,here); //if (mul==1) here-=D; ret[tc.x*w+tc.y]=here; draw[tc.x][tc.y]=1; queue<coor> eq; eq.push(tc); while (!eq.empty()) { tc=eq.front(); eq.pop(); for (int l=0; l<4; l++) { coor ttc; ttc.x=tc.x+dx[l]; ttc.y=tc.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) if (draw[ttc.x][ttc.y]==0 && contour[ttc.x][ttc.y]=='1') { draw[ttc.x][ttc.y]=1; ret[ttc.x*w+ttc.y]=here; eq.push(ttc); } } } } } } } } for (int i=0; i<known.size(); i++) { coor tc=known[i].first; //if (contour[tc.x][tc.y]=='1') fprintf(debug,"(%d,%d) draw:%d\n",tc.x,tc.y,draw[tc.x][tc.y]); if (contour[tc.x][tc.y]=='1' && draw[tc.x][tc.y]==0) { draw[tc.x][tc.y]=1; newlin=1; double here=known[i].second; ret[tc.x*w+tc.y]=here; if (extpt(tc.x,tc.y)==0) { queue<coor> eq; eq.push(tc); while (!eq.empty()) { tc=eq.front(); eq.pop(); for (int l=0; l<4; l++) { coor ttc; ttc.x=tc.x+dx[l]; ttc.y=tc.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) if (draw[ttc.x][ttc.y]==0 && contour[ttc.x][ttc.y]=='1') { draw[ttc.x][ttc.y]=1; ret[ttc.x*w+ttc.y]=here; eq.push(ttc); } } } } } } if (newlin==0) { canind++; if (canind==cand.size()) break; D=cand[canind].second; goto adjust; } /* for (int k=0; k<h; k++) { for (int l=0; l<w; l++) if (contour[k][l]=='1') { if (draw[k][l]==0) fprintf(debug,"*"); else fprintf(debug,"!"); } else if (draw[k][l]==0) fprintf(debug,"0"); else fprintf(debug,"1"); fprintf(debug,"\n"); } */ fprintf(debug,"time find contour: %0.4lfs\n",runtime()); //fill in the other squares memset(v,0,sizeof(v)); int tcnt=0; for (int i=0; i<h; i++) for (int j=0; j<w; j++) { coor tc; tc.x=i; tc.y=j; if (v[tc.x][tc.y]==0 && draw[tc.x][tc.y]==1) { double here=ret[tc.x*w+tc.y]; memset(appr,0,sizeof(appr)); queue<pair<int,coor> > fq; queue<coor> eq; eq.push(tc); fq.push(make_pair(0,tc)); draw[tc.x][tc.y]=2; v[tc.x][tc.y]=1; appr[tc.x][tc.y]=1; while (!eq.empty()) { tc=eq.front(); eq.pop(); for (int l=0; l<4; l++) { coor ttc; ttc.x=tc.x+dx[l]; ttc.y=tc.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) if (v[ttc.x][ttc.y]==0 && contour[ttc.x][ttc.y]=='1') { v[ttc.x][ttc.y]=1; appr[ttc.x][ttc.y]=1; draw[ttc.x][ttc.y]=2; eq.push(ttc); fq.push(make_pair(0,ttc)); } } } int lvl=0; fprintf(debug,"(%d,%d) here:%0.4lf\n",tc.x,tc.y,here); while (!fq.empty()) { tc=fq.front().second; lvl=fq.front().first; fq.pop(); est[tc.x][tc.y].push_back(make_pair(lvl,here)); for (int l=0; l<4; l++) { coor ttc; ttc.x=tc.x+dx[l]; ttc.y=tc.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) { int pass=0; if (extpt(ttc.x-1,ttc.y)==1 || extpt(ttc.x+1,ttc.y)==1 || extpt(ttc.x,ttc.y-1)==1 || extpt(ttc.x,ttc.y+1)==1) pass=1; if (appr[ttc.x][ttc.y]==0 && (contour[ttc.x][ttc.y]=='0' || pass==1)) { appr[ttc.x][ttc.y]=1; fq.push(make_pair(lvl+1,ttc)); } } } } } } fprintf(debug,"time fill other:%0.4lfs\n",runtime()); //confirm 4 corners if (est[0][0].size()==0) { if (ask[0][0]<-1e-7) { double td=accmea(0,0); coor tc; tc.x=0; tc.y=0; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); } fillall=0; } if (est[h-1][0].size()==0) { if (ask[h-1][0]<-1e-7) { double td=accmea(0,h-1); coor tc; tc.x=h-1; tc.y=0; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); } fillall=0; } if (est[0][w-1].size()==0) { if (ask[0][w-1]<-1e-7) { double td=accmea(w-1,0); coor tc; tc.x=0; tc.y=w-1; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); } fillall=0; } if (est[h-1][w-1].size()==0) { if (ask[h-1][w-1]<-1e-7) { double td=accmea(w-1,h-1); coor tc; tc.x=h-1; tc.y=w-1; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); } fillall=0; } //confirm side if (fillall==1) { int st=-1,end=-1; for (int i=0; i<h; i++) { if (est[i][0].size()==0) { if (st==-1) st=i; } else if (end==-1 && st!=-1) { end=i; double td=accmea(0,(end+st)/2); coor tc; tc.x=(end+st)/2; tc.y=0; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); fillall=0; end=-1; st=-1; } } st=-1; end=-1; for (int i=0; i<h; i++) { if (est[i][w-1].size()==0) { if (st==-1) st=i; } else if (end==-1 && st!=-1) { end=i; double td=accmea(w-1,(end+st)/2); coor tc; tc.x=(end+st)/2; tc.y=w-1; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); fillall=0; end=-1; st=-1; } } st=-1; end=-1; for (int i=0; i<w; i++) { if (est[0][i].size()==0) { if (st==-1) st=i; } else if (end==-1 && st!=-1) { end=i; double td=accmea((end+st)/2,0); coor tc; tc.x=0; tc.y=(end+st)/2; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); fillall=0; end=-1; st=-1; } } st=-1; end=-1; for (int i=0; i<w; i++) { if (est[h-1][i].size()==0) { if (st==-1) st=i; } else if (end==-1 && st!=-1) { end=i; double td=accmea((end+st)/2,h-1); coor tc; tc.x=h-1; tc.y=(end+st)/2; known.push_back(make_pair(tc,td)); fprintf(debug,"measure: (%d,%d) %0.4lf\n",tc.x,tc.y,td); fillall=0; end=-1; st=-1; } } } for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (est[i][j].size()==0) fillall=0; rep++; } while (fillall==0 && rep<5); for (int k=0; k<h; k++) { for (int l=0; l<w; l++) fprintf(debug,"%d",est[k][l].size()); fprintf(debug,"\n"); } //fine tuning int mxlvl=0; coor ob; do { mxlvl=0; for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (est[i][j].size()==1) { if (est[i][j][0].first>mxlvl) { mxlvl=est[i][j][0].first; ob.x=i; ob.y=j; } } if (mxlvl>3) { memset(v,0,sizeof(v)); double here=accmea(ob.y,ob.x); memset(appr,0,sizeof(appr)); queue<pair<int,coor> > fq; fq.push(make_pair(0,ob)); v[ob.x][ob.y]=1; draw[ob.x][ob.y]=1; ret[ob.x*w+ob.y]=here; fprintf(debug,"new:(%d,%d) here:%0.4lf\n",ob.x,ob.y,here); int lvl; while (!fq.empty()) { ob=fq.front().second; lvl=fq.front().first; fq.pop(); est[ob.x][ob.y].push_back(make_pair(lvl,here)); for (int l=0; l<4; l++) { coor ttc; ttc.x=ob.x+dx[l]; ttc.y=ob.y+dy[l]; if (ttc.x>=0 && ttc.x<h && ttc.y>=0 && ttc.y<w) if (appr[ttc.x][ttc.y]==0 && contour[ttc.x][ttc.y]=='0') { appr[ttc.x][ttc.y]=1; fq.push(make_pair(lvl+1,ttc)); } } } } } while (mxlvl>3); for (int k=0; k<h; k++) { for (int l=0; l<w; l++) fprintf(debug,"%d",est[k][l].size()); fprintf(debug,"\n"); } //use data to estimate height for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (ret[i*w+j]<-1e-7) { draw[i][j]=1; int weight=0; double sum=0.0; sort(est[i][j].begin(),est[i][j].end()); if (est[i][j].size()==0) { fprintf(debug,"OBS: (%d,%d)\n",i,j); continue; } if (est[i][j].size()==1) { fprintf(debug,"HI: (%d,%d)\n",i,j); ret[i*w+j]=est[i][j][0].second; continue; } for (int k=1; k<est[i][j].size(); k++) if (abs(est[i][j][k].second-est[i][j][0].second)>1e-7) { swap(est[i][j][k],est[i][j][1]); break; } weight=est[i][j][0].first+est[i][j][1].first; //fprintf(debug,"(%d,%d) sz:%d w:%d: %0.4lf %0.4lf\n",i,j,est[i][j].size(),weight,est[i][j][0].second,est[i][j][1].second); sum=est[i][j][1].first*est[i][j][0].second+est[i][j][0].first*est[i][j][1].second; fflush(debug); if (weight!=0) { sum/=weight; //fprintf(debug,"(%d,%d) s:%0.4lf\n",i,j,sum); } fflush(debug); ret[i*w+j]=sum; } for (int i=0; i<h; i++) for (int j=0; j<w; j++) if (ret[i*w+j]<-1e-7) ret[i*w+j]=50; fprintf(debug,"time estimate:%0.4lfs\n",runtime()); return ret; } }; int main () { ReliefMap RM; debug=fopen("debug.txt","w"); result=fopen("result.txt","w"); if (localtest==0) { vector<string> CON; int HH; scanf("%d",&HH); CON.resize(HH); for (int i=0; i<HH; i++) cin >> CON[i]; vector<double> RET; RET=RM.getMap(CON); printf("!\n"); for (int i=0; i<CON.size()*CON[0].length(); i++) cout << RET[i] << endl; fflush(stdout); } else { int nowseed=0; while (nowseed<endseed) { int H,W,MaxM; NoM=0; H=rand()%451+50; W=rand()%451+50; MaxM=(int)sqrt(W*H); int Bas,Bx[30],By[30],Bz[30],Bf[30]; double Bw[30]; Bas=rand()%11+15; for (int i=0; i<Bas; i++) { Bx[i]=rand()%W; By[i]=rand()%H; Bz[i]=rand()%100; Bf[i]=rand()%100+100; Bw[i]=dourand()*0.5+0.3; } for (int i=0; i<H; i++) for (int j=0; j<W; j++) { double NN,DD,Dis; NN=0.0; DD=0.0; for (int k=0; k<Bas; k++) { Dis=sqrt(pow(i-By[k],2.0)+pow(j-Bx[k],2.0)); Dis=pow(Dis+Bf[k],-Bw[k]); NN+=Dis*Bz[k]; DD+=Dis; } C[i][j]=NN/DD; } double Hmin=C[0][0],Hmax=C[0][0]; for (int i=0; i<H; i++) for (int j=0; j<W; j++) { Hmin=min(Hmin,C[i][j]); Hmax=max(Hmax,C[i][j]); } for (int i=0; i<H; i++) for (int j=0; j<W; j++) C[i][j] = (C[i][j]-Hmin)/(Hmax-Hmin)*100; vector<string> CON; for (int i=0; i<H; i++) { string all0=""; for (int j=0; j<W; j++) all0+="0"; CON.push_back(all0); } double CD; CD=dourand()*8.0+2.0; for (double m=0.0; m<100; m+=CD) { for (int i=0; i<H; i++) for (int j=0; j<W; j++) if (C[i][j]<m) { for (int k=0; k<8; k++) { int tx=i+d8x[k],ty=j+d8y[k]; if (tx>=0 && tx<H && ty>=0 && ty<W && C[tx][ty]>m) CON[i][j]='1'; } } } int Ismin,Ismax; for (int i=1; i<H-1; i++) for (int j=1; j<W-1; j++) { Ismin=1; Ismax=1; for (int k=0; k<8; k++) { if (C[i][j]<=C[i+d8x[k]][j+d8y[k]]) Ismax=0; if (C[i][j]>=C[i+d8x[k]][j+d8y[k]]) Ismin=0; } if (Ismin || Ismax) { CON[i][j]='1'; CON[i+1][j]='1'; CON[i-1][j]='1'; CON[i][j+1]='1'; CON[i][j-1]='1'; } } vector<double> RET; printf("Seed: %d\n",nowseed); if (nowseed>=stseed) { fprintf(result,"H = %d W = %d\n",H,W); fprintf(result,"D = %0.8lf\n",CD); /* for (int k=0; k<H; k++) { for (int l=0; l<W; l++) if (CON[k][l]=='1') fprintf(result,"*"); else fprintf(result,"0"); fprintf(result,"\n"); } */ fflush(result); } RET=RM.getMap(CON); double AvgErr=0.0; for (int i=0; i<H; i++) for (int j=0; j<W; j++) AvgErr += pow(C[i][j]-RET[i*W+j],2); AvgErr/=(W*H); double Sco; Sco=1.0/(AvgErr*pow(100,NoM*1.0/MaxM)); if (nowseed>=stseed) { fprintf(result,"Error = %0.6lf\n",AvgErr); fprintf(result,"%d of %d measures used\n",NoM,MaxM); fprintf(result,"Score = %0.8lf\n",Sco); fprintf(result,"\n\n\n"); } nowseed++; } } return 0; }
[ "cfyuen.trevor@gmail.com" ]
cfyuen.trevor@gmail.com
021f60002cfe8c363991f96625d7afb915315ccd
527fa8af82535a63982625ea3881738f6e55b497
/source/uwp/Renderer/lib/AdaptiveRenderArgs.h
9b8c50636649e3dd7f65b0fd28d1b3ab99949ff0
[ "MIT" ]
permissive
Pepsi1x1/AdaptiveCards
bd89f47d898ccc2b647a23092774e38ece32211f
fa64485b7b8dde16916910d6c29391de1d6d59fe
refs/heads/main
2021-06-30T01:34:41.737221
2020-07-16T16:13:44
2020-07-16T16:13:44
280,222,153
1
0
MIT
2020-09-01T21:11:15
2020-07-16T17:57:12
null
UTF-8
C++
false
false
2,072
h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "AdaptiveCards.Rendering.Uwp.h" namespace AdaptiveNamespace { class AdaptiveRenderArgs : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::WinRtClassicComMix>, ABI::AdaptiveNamespace::IAdaptiveRenderArgs> { AdaptiveRuntime(AdaptiveRenderArgs); public: AdaptiveRenderArgs() : m_isInShowCard(false), m_allowAboveTitleIconPlacement(false), m_ancestorHasFallback(false) { } HRESULT RuntimeClassInitialize() noexcept; HRESULT RuntimeClassInitialize(ABI::AdaptiveNamespace::ContainerStyle containerStyle, _In_opt_ IInspectable* parentElement, _In_opt_ IAdaptiveRenderArgs* renderArgs) noexcept; IFACEMETHODIMP get_ContainerStyle(_Out_ ABI::AdaptiveNamespace::ContainerStyle* value) override; IFACEMETHODIMP put_ContainerStyle(ABI::AdaptiveNamespace::ContainerStyle value) override; IFACEMETHODIMP get_ParentElement(_COM_Outptr_ IInspectable** value) override; IFACEMETHODIMP put_ParentElement(_In_ IInspectable* value) override; IFACEMETHODIMP get_IsInShowCard(_Out_ boolean* isInShowCard) override; IFACEMETHODIMP put_IsInShowCard(boolean isInShowCard) override; IFACEMETHODIMP get_AllowAboveTitleIconPlacement(_Out_ boolean* value) override; IFACEMETHODIMP put_AllowAboveTitleIconPlacement(boolean value) override; IFACEMETHODIMP get_AncestorHasFallback(_Out_ boolean* hasFallback); IFACEMETHODIMP put_AncestorHasFallback(boolean hasFallback); private: ABI::AdaptiveNamespace::ContainerStyle m_containerStyle; Microsoft::WRL::ComPtr<IInspectable> m_parentElement; boolean m_isInShowCard; boolean m_allowAboveTitleIconPlacement; boolean m_ancestorHasFallback; }; ActivatableClass(AdaptiveRenderArgs); }
[ "noreply@github.com" ]
Pepsi1x1.noreply@github.com
d772a7335dd415749afdc01693c0accfd2521722
653f6d190f4c229c251c606f98bbff68ec6abc7c
/s02_imagePlane/imgPlaneSplit.cpp
0112d259828803a19c3040ffa6c103d75a96bfef
[]
no_license
Fujiwara-Laboratory/VideoProcessing
238aa20831b16de953294693a5d214c4f8bdcdb2
1364e0601290862c6692fc1d3639ef96670a573b
refs/heads/master
2022-11-23T03:03:25.146494
2020-07-22T06:46:31
2020-07-22T06:46:31
261,650,816
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include <opencv2/opencv.hpp> int main(int argc, char **argv){ cv::Mat srcM; std::vector<cv::Mat> rgbPlanes; srcM = cv::imread(argv[1], cv::IMREAD_COLOR); if(srcM.empty()) return -1; cv::split(srcM, rgbPlanes); cv::imshow("b", rgbPlanes[0]); cv::imshow("g", rgbPlanes[1]); cv::imshow("r", rgbPlanes[2]); cv::imwrite("test.jpg", rgbPlanes[2]); cv::waitKey(0); return 0; }
[ "noreply@github.com" ]
Fujiwara-Laboratory.noreply@github.com
c70eadb03a598427d5b8db367c8d3fe32aca7d54
8e91fc84bb407d83b945150cc680a881fc0d5fea
/CSCI 340/Assignment 7/studentgrade.h
30a6daca275b49efafa6f78a04edca92dd2c16f0
[ "MIT" ]
permissive
joedanpar/Academic-Projects
c7efb2fbcb06d17b1e9bcaad8715ada8adf96aac
3279420cd2002a81ee83d916a4072fc10cc97480
refs/heads/master
2021-01-10T09:58:15.873501
2019-02-03T16:34:47
2019-02-03T16:34:47
44,362,745
0
1
null
null
null
null
UTF-8
C++
false
false
2,288
h
#ifndef STUGRADE_H #define STUGRADE_H #include <iostream> #include <string> using namespace std; class StudentGrade { private: string name, Zid, grade; public: StudentGrade(); StudentGrade(const string &, const string &, const string &); virtual ~StudentGrade(); string get_name() const; string get_Zid() const; string get_grade() const; void set_name(const string &); void set_Zid(const string &); void set_grade(const string &); bool operator== (const StudentGrade &) const; friend ostream & operator<< (ostream &, const StudentGrade &); bool operator < (StudentGrade) const; bool operator > (StudentGrade) const; }; StudentGrade::StudentGrade() { name = ""; Zid = ""; grade = ""; } StudentGrade::StudentGrade(const string & newname, const string & newzid, const string & newgrade) { name = newname; Zid = newzid; grade = newgrade; } StudentGrade::~StudentGrade() { } string StudentGrade::get_name() const { return name; } string StudentGrade::get_Zid() const { return Zid; } string StudentGrade::get_grade() const { return grade; } void StudentGrade::set_name(const string & newname) { name = newname; } void StudentGrade::set_Zid(const string & newZid) { Zid = newZid; } void StudentGrade::set_grade(const string & newgrade) { grade = newgrade; } bool StudentGrade::operator== (const StudentGrade & s) const { if(get_name() == s.get_name() && get_Zid() == s.get_Zid() && get_grade() == s.get_grade()) return true; else return false; } ostream & operator<< (ostream & cout, const StudentGrade & s) { cout << s.get_name() << ", " << s.get_Zid() << ", " << s.get_grade(); return cout; } bool StudentGrade::operator< (StudentGrade s) const { if(get_grade() < s.get_grade()) return true; else if (get_grade() > s.get_grade()) return false; else if (get_grade() == s.get_grade()) if (get_Zid() < s.get_Zid()) return true; else return false; return false; } bool StudentGrade::operator> (StudentGrade s) const { if(get_grade() > s.get_grade()) return true; else if (get_grade() < s.get_grade()) return false; else if (get_grade() == s.get_grade()) if (get_Zid() > s.get_Zid()) return true; else return false; return false; } #endif
[ "joedanpar@gmail.com" ]
joedanpar@gmail.com
20f89e723ea907de9d76403e6740bf910c8d8184
0150d34d5ced4266b6606c87fbc389f23ed19a45
/Cpp/SDK/BP_1P_Upper_parameters.h
25f12509c42e24ea156e1084adee822e3691b6a9
[ "Apache-2.0" ]
permissive
joey00186/Squad-SDK
9aa1b6424d4e5b0a743e105407934edea87cbfeb
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
refs/heads/master
2023-02-05T19:00:05.452463
2021-01-03T19:03:34
2021-01-03T19:03:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,336
h
#pragma once // Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function BP_1P_Upper.BP_1P_Upper_C.AnimGraph struct UBP_1P_Upper_C_AnimGraph_Params { struct FPoseLink AnimGraph; // (Parm, OutParm, NoDestructor) }; // Function BP_1P_Upper.BP_1P_Upper_C.AnimNotify_1PDetachLeftHand struct UBP_1P_Upper_C_AnimNotify_1PDetachLeftHand_Params { }; // Function BP_1P_Upper.BP_1P_Upper_C.AnimNotify_1PAttachLeftHand struct UBP_1P_Upper_C_AnimNotify_1PAttachLeftHand_Params { }; // Function BP_1P_Upper.BP_1P_Upper_C.OnVaultClimbStop struct UBP_1P_Upper_C_OnVaultClimbStop_Params { }; // Function BP_1P_Upper.BP_1P_Upper_C.ExecuteUbergraph_BP_1P_Upper struct UBP_1P_Upper_C_ExecuteUbergraph_BP_1P_Upper_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "tahmaniak@gmail.com" ]
tahmaniak@gmail.com
903e9a893a8d07d2ef0e466a9931cb362d11c647
29217bba0162f7a1183f909b17d5612d3194d661
/Laozi/MouseSignalInfo.h
426d8e9d03f67343a216c9a87e8c67056ef9b1f3
[]
no_license
etoolkit/Laozi
7dda5f31e41349d1c90636f07e63c3fe08eb5b2f
4c843cf2c9e5dfe80decea98b6645f70c4e57d95
refs/heads/master
2023-02-25T18:01:09.517910
2021-01-26T02:06:02
2021-01-26T02:06:02
null
0
0
null
null
null
null
GB18030
C++
false
false
974
h
#pragma once #include "Resource.h" #define GestureElmCount 8 #define WM_SIGNAL_INFO WM_USER+600 #define WM_INIT_SI WM_USER+700 // CMouseSignalInfo 对话框 class CMouseSignalInfo : public CDialogEx { DECLARE_DYNAMIC(CMouseSignalInfo) enum EnumGesture { None=0,Left=1,Right=2,Up=3,Down=4 }; enum EnumEvent { NoneEvent,Close,Mini,Restore,ToRight, ToLeft, ToTop, ToBottom, ToCenter,Back,Redo,PageUp,PageDown,PageHome,PageEnd,CtrlTab,CtrlShiftTab,AltTab,AltShiftTab }; public: CMouseSignalInfo(CWnd* pParent = NULL); // 标准构造函数 virtual ~CMouseSignalInfo(); // 对话框数据 enum { IDD = IDD_DIALOG_MouseSignalInfo }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 ULONG_PTR m_nGdiplusToken; CMouseSignalInfo::EnumGesture m_cMouseSignals[GestureElmCount]; DECLARE_MESSAGE_MAP() afx_msg LRESULT OnSignalInfo(WPARAM wParam,LPARAM lParam); public: virtual BOOL OnInitDialog(); afx_msg void OnPaint(); };
[ "shijie.wang@aspose.com" ]
shijie.wang@aspose.com
13544126b54c78e282c1b548661798a1044524c1
35e52969c08bcadfc12d665c221f47e7e11c465b
/20130512_Software_Development_Yaml_Data_Explorer/src/Controllers/MenuController.h
95afc3889056d90959b942174549df962db637c8
[ "MIT" ]
permissive
andrehtissot/oldthings
9c8178a9840668b2555c5711b9b014c978ffb2e0
e947f6ca168939c3781de39bdf5799e49a0021a9
refs/heads/master
2021-01-11T12:38:37.133796
2016-12-09T18:36:42
2016-12-09T18:36:42
72,486,238
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
#ifndef _CONTROLLERS_MENU_CONTROLLER_H_ #define _CONTROLLERS_MENU_CONTROLLER_H_ namespace Controllers { class MenuController : public Controller { public: MenuController(); MenuController(Controller* const caller); ~MenuController(); void openView(); void closeView(); void selectOption(Utils::Options::Option* option); void openTotalHoursPerProjectController(); void openTotalHoursPerUserController(); void openTotalHoursPerUserVersusEstimatedController(); void openTotalHoursPerProjectVersusEstimatedController(); }; } #endif
[ "andrehtissot@gmail.com" ]
andrehtissot@gmail.com
7364ac163c6de87e4d9ce5d2ec39f2ee2b799b61
a9bb5c9a11f37c6093a319d0ee9e49a3a9cf5019
/Player.cpp
522c557d33e6bcdae639148610ab0d2b62cfbfbb
[]
no_license
CaptainKi11z/Planet-Wars
5e942e087de5d12bb5684e47ba9642316fb20c98
12871b6b068537b40ca4a73853e7bda8d6d70153
refs/heads/master
2020-12-30T19:11:34.736551
2011-12-09T18:18:23
2011-12-09T18:18:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,635
cpp
// // Player.cpp // SpongeBobWars // // Created by Philip Dougherty on 11/23/11. // Copyright 2011 UW Madison. All rights reserved. // #include "Player.h" Player::Player() { fireResources = 0; waterResources = 0; earthResources = 0; windResources = 0; this->fleet = new Fleet(this); this->myNodes = new Node*[Model::getSelf()->numNodes]; this->nodesOwned = 0; } Player::~Player() { delete this->fleet; } bool Player::iOwnNode(Node *node) { for(int i = 0; i < this->nodesOwned; i++) { if(myNodes[i] == node) return true; } return false; } void Player::surrenderNode(Node *node) { bool found; for(int i = 0; i < this->nodesOwned; i++) { if(myNodes[i] == node) found = true; if(found) myNodes[i] = myNodes[i+1]; } node->owner = Model::getSelf()->nullPlayer; } void Player::attackNode(Node *attackNode, Node *defendNode) { } void Player::conquerNode(Node *node) { if(!iOwnNode(node)) { if(node->owner != Model::getSelf()->nullPlayer) node->owner->surrenderNode(node); myNodes[nodesOwned++] = node; } node->owner = this; } Unit * Player::deployUnit(Node *planet, int type) { //Check if unit of requested type exists on any ships on current planet, //or if player contains enough resources to create another one. //If so, remove unit from player's army and return unit. Else, return null. return Model::getSelf()->nullUnit; } void Player::endTurn() { fleet->refreshShips(); } void Player::draw() { fleet->draw(); }
[ "phildo211@gmail.com" ]
phildo211@gmail.com
36a700e46c8fb9dc9ac5bb3f63736f9a9666acd2
844969bd953d7300f02172c867725e27b518c08e
/SDK/BP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc_classes.h
5748c38a3c03dc580c3290188e75c92764d6db28
[]
no_license
zanzo420/SoT-Python-Offset-Finder
70037c37991a2df53fa671e3c8ce12c45fbf75a5
d881877da08b5c5beaaca140f0ab768223b75d4d
refs/heads/main
2023-07-18T17:25:01.596284
2021-09-09T12:31:51
2021-09-09T12:31:51
380,604,174
0
0
null
2021-06-26T22:07:04
2021-06-26T22:07:03
null
UTF-8
C++
false
false
912
h
#pragma once // Name: SoT, Version: 2.2.1.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc.BP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc_C // 0x0000 (FullSize[0x0130] - InheritedSize[0x0130]) class UBP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc_C : public UItemDesc { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc.BP_fod_Devilfish_03_FirelightRaw_00_a_ItemDesc_C"); return ptr; } void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51171051+DougTheDruid@users.noreply.github.com" ]
51171051+DougTheDruid@users.noreply.github.com
cc87326ecc4abbd556e49dbcf209fbfc50cb53b5
cf1ea40fd061c5042cebe8e97c436bc931afb4f3
/Serie_02_03_Rectangle/rectangle.cpp
314c5270f5ae21cdf5bb1594d62a5c97ddedc577
[]
no_license
cptnSeldon/CppCourse
9615029ba27a0ec8e12c07fb9998f9dc247ddec3
3d64fab28babcb7464b338d40a733c4ec52aa04e
refs/heads/master
2020-04-24T03:20:13.278329
2020-03-11T13:40:42
2020-03-11T13:40:42
171,667,050
0
0
null
null
null
null
UTF-8
C++
false
false
2,790
cpp
#include "rectangle.h" //CONSTRUCTORS ///default Rectangle::Rectangle() : upLeft(Point()), downRight(Point()) { //upLeft = Point(); //downRight = Point(); } ///parameterized Rectangle::Rectangle(Point upLeft, Point downRight) { /* .-> | ˇ (x_up,y_up) .___________. <----X----> ^ | Y | ˇ .___________. (x_down,y_down) X = x_down-x_up Y = y_down-y_up */ //test : x_up < x_down => ok, y_up < y_down => ok if (upLeft.x < downRight.x && upLeft.y < downRight.y) { this->upLeft = upLeft; this->downRight = downRight; } else { this->upLeft = downRight; this->downRight = upLeft; } } ///copy Rectangle::Rectangle(const Rectangle & other) { this->upLeft = other.upLeft; this->downRight = other.downRight; } //FUNCTIONS ///getters : maths functions int Rectangle::getPerimeter() { /* .-> | ˇ (x_up,y_up) .___________. <----X----> ^ | Y | ˇ .___________. (x_down,y_down) X = x_down-x_up Y = y_down-y_up */ return (downRight.x - upLeft.x) * 2 + (downRight.y - upLeft.y) * 2; } int Rectangle::getArea() { return (downRight.x - upLeft.x) * (downRight.y - upLeft.y); } ///print graphic result void Rectangle::show() { char character = 'x'; //window : 25 lines for 80 caracters max for(int i = 0; i < 25; i++) { for(int j = 0; j < 80; j++) { if(j >= upLeft.x && i >= upLeft.y && j <= downRight.x && i <= downRight.y) { cout << character; } else { cout << '.'; } } cout << endl; } } ///translation of rectangle void Rectangle::translate(int x, int y) { this->upLeft.x += x; this->upLeft.y += y; this->downRight.x += x; this->downRight.y += y; } ///check if a point is inside the current rectangle bool Rectangle::contains(Point & other) { /* .-> | ˇ (x_up,y_up) .___________. <----X----> ^ | Y | ˇ .___________. (x_down,y_down) X = x_down-x_up Y = y_down-y_up */ if(other.x < this->upLeft.x && other.x > this->downRight.x && other.y < this->upLeft.y && other.y > this->downRight.y) { return false; } else { return true; } }
[ "julia.nemeth@he-arc.ch" ]
julia.nemeth@he-arc.ch
ad854d064937e5e258fb23311c44ee6e2a107b6f
d787ade353b9c47e8b239a51aafbdafbc6962d34
/src/languagenut/skills.cpp
ab878fc16dfbc7e77e4bba67cf743fb13d76eea3
[]
no_license
charleywright/LanguageNutter
860886e6f4042f59dc407550f48d91b2f58d2044
26ec0a2e3ff42292d817e96f879ecd7196f94e07
refs/heads/master
2023-08-15T13:51:20.263496
2021-09-14T18:28:57
2021-09-14T18:28:57
405,486,551
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
#include "languagenut.hpp" languagenut::types::skills languagenut::client::get_skills() { json data = this->authed_request("skillsController/getStudent"); return languagenut::types::skills(data); }
[ "charleywright06@gmail.com" ]
charleywright06@gmail.com
8612b4a128829aa2d31ece7a9885e441702f506c
463f5f9e55da4e52e0b4061882f97e976c5aaee3
/BlanS - A04/MyCamera.h
d85b3599fde07645ecbf76778a8a9ce5ca5b2316
[ "MIT" ]
permissive
Avix101/Simplex_2016_Fall
7a7dee0595440a1b551e357b92b236fc7f0dac55
7b34bb0e620b4af1bcdc8d084d33668da8503b92
refs/heads/master
2021-08-23T22:15:00.190002
2017-12-06T20:23:54
2017-12-06T20:23:54
103,872,681
0
0
null
2017-09-18T00:26:49
2017-09-18T00:26:49
null
UTF-8
C++
false
false
5,911
h
/*---------------------------------------------- Programmer: Alberto Bobadilla (labigm@gmail.com) Date: 2017/06 ----------------------------------------------*/ #ifndef __MYCAMERACLASS_H_ #define __MYCAMERACLASS_H_ #include "Definitions.h" namespace Simplex { class MyCamera { vector3 m_v3Position = vector3(0.0f, 0.0f, 10.0f); //Where my camera is located vector3 m_v3Target = vector3(0.0f, 0.0f, 0.0f); //What I'm looking at vector3 m_v3Up = vector3(0.0f, 1.0f, 0.0f); //What is up vector3 m_v3StartingOrientation = m_v3Target - m_v3Position; //The initial orientation of the camera represented as a vector3 quaternion m_qCurrentOrientation = quaternion(m_v3StartingOrientation); //The current orientation of the camera represented as a quaternion bool m_bPerspective = true; //perspective view? False is Orthographic float m_fFOV = 45.0f; //Field of View vector2 m_v2Resolution = vector2(1280.0f, 720.0f); //Resolution of the window vector2 m_v2NearFar = vector2(0.001f, 1000.0f); //Near and Far planes vector2 m_v2Horizontal = vector2(-5.0f, 5.0f); //Orthographic horizontal projection vector2 m_v2Vertical = vector2(-5.0f, 5.0f); //Orthographic vertical projection matrix4 m_m4View; //View matrix matrix4 m_m4Projection; //Projection Matrix public: /* USAGE: Constructor ARGUMENTS: --- OUTPUT: the class object */ MyCamera(); /* USAGE: constructor ARGUMENTS: - vector3 a_v3Position -> Where my camera is located - vector3 a_v3Target -> What I'm looking at - vector3 a_v3Upward -> What is up OUTPUT: --- */ MyCamera(vector3 a_v3Position, vector3 a_v3Target, vector3 a_v3Upward); /* USAGE: Copy constructor ARGUMENTS: MyCamera const& other -> object to copy OUTPUT: --- */ MyCamera(MyCamera const& other); /* USAGE: Copy Assignment operator ARGUMENTS: MyCamera const& other -> object to copy OUTPUT: --- */ MyCamera& operator=(MyCamera const& other); /* USAGE: Initialize the class ARGUMENTS: --- OUTPUT: --- */ void Init(void); /* USAGE: Release pointers in the class ARGUMENTS: --- OUTPUT: --- */ void Release(void); /* USAGE: swap the content with an incoming object ARGUMENTS: --- OUTPUT: --- */ void Swap(MyCamera& other); /* USAGE: Destructor ARGUMENTS: --- OUTPUT: --- */ ~MyCamera(void); /* USAGE: Sets the position of the camera ARGUMENTS: vector3 a_v3Position -> Position where we want the camera to be OUTPUT: --- */ void SetPosition(vector3 a_v3Position); /* USAGE: Gets the position of the camera ARGUMENTS: --- OUTPUT: position of the camera */ vector3 GetPosition(void); /* USAGE: Sets the position of the camera ARGUMENTS: vector3 a_v3Target -> What we want the camera to look at OUTPUT: --- */ void SetTarget(vector3 a_v3Target); /* USAGE: Gets the position of the camera ARGUMENTS: --- OUTPUT: position of the camera */ vector3 GetTarget(void); /* USAGE: Sets the position of the camera ARGUMENTS: vector3 a_v3Up -> What up means in the world OUTPUT: --- */ void SetUp(vector3 a_v3Up); /* USAGE: Gets the position of the camera ARGUMENTS: --- OUTPUT: position of the camera */ vector3 GetUp(void); /* USAGE: Sets Perspective Camera ARGUMENTS: bool a_bPerspective = true -> is camera perspective or orthographic OUTPUT: --- */ void SetPerspective(bool a_bPerspective = true); /* USAGE: Sets the Field of View of the camera for perspective use ARGUMENTS: float a_fFOV -> field of view to apply to the camera OUTPUT: --- */ void SetFOV(float a_fFOV); /* USAGE: Sets the resolution of the camera aspect ratio ARGUMENTS: vector2 a_v2Resolution -> resolution of the window OUTPUT: --- */ void SetResolution(vector2 a_v2Resolution); /* USAGE: Sets the near and far planes of the camera ARGUMENTS: vector2 a_v2NearFar -> near far planes OUTPUT: --- */ void SetNearFar(vector2 a_v2NearFar); /* USAGE: Sets the horizontal planes of the camera ARGUMENTS: vector2 a_v2Horizontal -> horizontal planes OUTPUT: --- */ void SetHorizontalPlanes(vector2 a_v2Horizontal); /* USAGE: Sets the vertical planes of the camera ARGUMENTS: vector2 a_v2Vertical -> vertical planes OUTPUT: --- */ void SetVerticalPlanes(vector2 a_v2Vertical); /* USAGE: Gets the projection matrix of the camera ARGUMENTS: --- OUTPUT: projection matrix of the camera */ matrix4 GetProjectionMatrix(void); /* USAGE: Gets the view matrix of the camera ARGUMENTS: --- OUTPUT: view matrix of the camera */ matrix4 GetViewMatrix(void); /* USAGE: Resets the camera to default values ARGUMENTS: --- OUTPUT: --- */ void ResetCamera(void); /* USAGE: Set the position target and up of the camera at once ARGUMENTS: - vector3 a_v3Position -> Where my camera is located - vector3 a_v3Target -> What I'm looking at - vector3 a_v3Upward -> What is up OUTPUT: --- */ void SetPositionTargetAndUp(vector3 a_v3Position, vector3 a_v3Target, vector3 a_v3Upward = AXIS_Y); /* USAGE: Calculate what the camera should be looking at with the values of position target and up ARGUMENTS: --- OUTPUT: --- */ void CalculateViewMatrix(void); /* USAGE: Calculate how the camera sees the world ARGUMENTS: --- OUTPUT: --- */ void CalculateProjectionMatrix(void); /* USAGE: Calculate how the camera sees the world ARGUMENTS: The axis to rotate around, and the amount to rotate around that axis OUTPUT: --- */ void RotateCamera(vector3 axis, float angle); /* USAGE: Calculate how the camera sees the world ARGUMENTS: How far to move the camera forward (or backwards if negative), and how far to move to the right (or left if negative) OUTPUT: --- */ void MoveCamera(float forward, float right); /* USAGE: Calculates and returns the camera's right vector ARGUMENTS: --- OUTPUT: Gives back the camera's right vector */ vector3 GetRight(void); }; } //namespace Simplex #endif //__MYCAMERACLASS_H_ /* USAGE: ARGUMENTS: --- OUTPUT: --- */
[ "stashablank@gmail.com" ]
stashablank@gmail.com
de86b6c3b1c9c43a5317afd174fe856c3f695d46
e9c02bb0df7ad3a928cf7c97b8294451eaa8dbc8
/graph-source-code/96-D/539780.cpp
523412d34ac3e0e20969907578972c7b5b4a7126
[ "MIT" ]
permissive
AmrARaouf/algorithm-detection
b157a534545fa8920bbe94e7307d4b937a74aa60
59f3028d2298804870b32729415d71eec6116557
refs/heads/master
2021-01-13T14:37:04.074339
2015-12-06T21:14:31
2015-12-06T21:14:31
45,905,817
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
cpp
//Language: GNU C++ #include <string> #include <vector> #include <map> #include <utility> #include <cmath> #include <cstdlib> #include <cstring> #include <queue> #include <stack> #include <set> #include <sstream> #include <algorithm> #include <iostream> #include <iomanip> #include <cstdio> #include <cassert> using namespace std; #define INF 0x3f3f3f3f #define INFL 1LL<<62 #define ALL(v) v.begin(),v.end() typedef pair<int,int> pii; typedef long long ll; ll mat[1005][1005]; int n; ll taxitime[1005]; ll taxicost[1005]; int seen[1005]; int vis[1005]; ll d[1005]; void dfs(int x,ll cost){ seen[x]=1; for(int i=0;i<n;i++) if(mat[x][i]&&!seen[i]&&cost>=mat[x][i]) dfs(i,cost-mat[x][i]); } int main(){ int e; cin>>n>>e; int s,t; cin>>s>>t; s--;t--; for(int i=0;i<e;i++){ int a,b; ll c; cin>>a>>b>>c; a--;b--; if(!mat[a][b]) mat[a][b]=mat[b][a]=c; else mat[a][b]=mat[b][a]=min(mat[a][b],c); } for(int i=0;i<n;i++) cin>>taxitime[i]>>taxicost[i]; for(int i=0;i<n;i++) d[i]=INFL; memset(vis,0,sizeof(vis)); d[s]=0; while(1){ int u=-1; ll dmin=INFL; for(int i=0;i<n;i++) if(!vis[i]&&d[i]<dmin){ u=i; dmin=d[i]; } if(u==-1||u==t) break; vis[u]=1; memset(seen,0,sizeof(seen)); dfs(u,taxitime[u]); for(int i=0;i<n;i++) if(u!=i&&seen[i]&&d[u]+taxicost[u]<d[i]){ d[i]=d[u]+taxicost[u]; } } if(d[t]==INFL) cout<<"-1"<<endl; else cout<<d[t]<<endl; return 0; }
[ "amr.abdelraouf93@gmail.com" ]
amr.abdelraouf93@gmail.com
d48c0744489f7175234a7ced512b0bd545a8ce9c
afd9b6a29d8d615b62d9ffce4ce604e2d84a3591
/GraphicLibrary/GraphicObject.h
e4e977945281a93acc047e90841208fe5b92ceb9
[]
no_license
mojoe12/TowerDefense
6a20e1f9517840a6106c109c59ceeda4590e92b9
50fd7ab1c91f55b7828a15be5bf66ae1b9c82b7b
refs/heads/master
2021-09-21T19:15:38.326071
2018-08-30T13:52:42
2018-08-30T13:52:42
105,226,485
0
0
null
null
null
null
UTF-8
C++
false
false
205
h
#pragma once #include <windows.h> #include "GraphicLibrary.h" #pragma comment(lib, "d2d1.lib") namespace GraphicLibrary { class GraphicObject { public: GraphicObject(); ~GraphicObject(); }; }
[ "josephahutter@gmail.com" ]
josephahutter@gmail.com
e18c658cce751e1c66ba270decf7883063e6f1da
9b157a8bd608ecffe9a3d21692a64d065d4eb8c6
/arduino/arduino_pid_speedV4/arduino_pid_speedV4.ino
4298c18b32e33d2ee1dc16161c8032b415a8921d
[]
no_license
CVandermies/patrouilleur_web
4661411f32430c05179c926d11dfa93a1e3387f2
38b2c5cd88706b0d45a611ede94c1e899d29f1da
refs/heads/main
2023-04-28T19:56:31.686856
2021-05-16T21:46:21
2021-05-16T21:46:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,965
ino
#include <PinChangeInt.h> /* Motor - PID speed control (1) Receive command from Visual Studio (via COM1): set_speed, kP, kI, kD (2) Control motor speed through PWM (PWM is base on PID calculation) (3) Send pv_speed to Visual Studio -> show in graph */ boolean stringComplete = false; // whether the string is complete boolean motor_start = false; String mySt = ""; char myChar; const byte pin_aG = 2; //for encoder pulse A const byte pin_bG = 12; //for encoder pulse B const byte pin_aD = 3; //for encoder pulse A const byte pin_bD = 4; //for encoder pulse B const byte pin_fwdG = 5; //for H-bridge: run motor forward const byte pin_bwdG = 6; //for H-bridge: run motor backward const byte pin_fwdD = 9; //for H-bridge: run motor forward const byte pin_bwdD = 10; //for H-bridge: run motor backward double encoderAG = 0; double encoderBG = 0; double encoderAD = 0; double encoderBD = 0; double set_speedG = 0; double set_speedD = 0; double pv_speedG = 0; double e_speedG = 0; //error of speed = set_speed - pv_speed double e_speed_preG = 0; //last error of speed double e_speed_sumG = 0; //sum error of speed double pwm_pulseG = 0; //this value is 0~255 double pv_speedD = 0; double e_speedD = 0; //error of speed = set_speed - pv_speed double e_speed_preD = 0; //last error of speed double e_speed_sumD = 0; //sum error of speed double pwm_pulseD = 0; //this value is 0~255 double kp = 0.015; //0.015 - 0.01 -0.01 for G motor double ki = 0.01;// double kd = 0.01; int i=0; int interval=100; unsigned long previousMillis=0; unsigned long previousMillis1=0; String text_speeds; void setup() { pinMode(pin_aG,INPUT_PULLUP); pinMode(pin_bG,INPUT_PULLUP); pinMode(pin_aD,INPUT_PULLUP); pinMode(pin_bD,INPUT_PULLUP); pinMode(pin_fwdD,OUTPUT); pinMode(pin_bwdD,OUTPUT); pinMode(pin_fwdG,OUTPUT); pinMode(pin_bwdG,OUTPUT); attachInterrupt(digitalPinToInterrupt(pin_aG), detect_aG,CHANGE); attachInterrupt(digitalPinToInterrupt(pin_aD), detect_aD, CHANGE); attachPinChangeInterrupt(pin_bG, detect_bG,CHANGE); attachPinChangeInterrupt(pin_bD, detect_bD, CHANGE); Serial.begin(9600); digitalWrite(pin_fwdG,0); //stop motor digitalWrite(pin_bwdG,0); //stop motor digitalWrite(pin_fwdD,0); //stop motor digitalWrite(pin_bwdD,0); //stop motor } void loop() { if (stringComplete) { // clear the string when COM receiving is completed mySt = ""; //note: in code below, mySt will not become blank, mySt is blank until '\n' is received stringComplete = false; } //receive command from Visual Studio if (mySt.substring(0,8) == "vs_start"){ motor_start = true; } if (mySt.substring(0,7) == "vs_stop"){ digitalWrite(pin_fwdD,0); digitalWrite(pin_bwdD,0); digitalWrite(pin_fwdG,0); digitalWrite(pin_bwdG,0); //stop motor motor_start = false; } if (mySt.substring(0,9) == "vs_speedG"){ set_speedG = mySt.substring(9,mySt.length()).toFloat(); //get string after set_speed } if (mySt.substring(0,9) == "vs_speedD"){ set_speedD = mySt.substring(9,mySt.length()).toFloat(); //get string after set_speed } if (mySt.substring(0,5) == "vs_kp"){ kp = mySt.substring(5,mySt.length()).toFloat(); //get string after vs_kp } if (mySt.substring(0,5) == "vs_ki"){ ki = mySt.substring(5,mySt.length()).toFloat(); //get string after vs_ki } if (mySt.substring(0,5) == "vs_kd"){ kd = mySt.substring(5,mySt.length()).toFloat(); //get string after vs_kd } //CHOOSE YOUR STYLE RUN //set_speed=1000; //motor_start = true; bool back = false; unsigned long currentMillis=millis(); if ( currentMillis-previousMillis>= interval){ // boucle appellé toutes les 100ms previousMillis=currentMillis; pv_speedG = ((encoderAG+encoderBG)*600)/64; //calculate motor speed[rpm] // Serial.println(pv_speedG); encoderAG=0; encoderBG=0; pv_speedD = ((encoderAD+encoderBD)*600)/64; //calculate motor speed[rpm] encoderAD=0; encoderBD=0;// 64 ticks -- 1 tr // x ticks -- 0.1 sec // x ticks -- 0.1/60 min // x ticks*600 -- 1min // x ticks*600 /64 pour avoir les tr/min avant la reduction //print out speed unsigned long currentMillis1=millis(); if ( currentMillis1-previousMillis1>= 55){ // boucle appellé toutes les 100ms previousMillis1=currentMillis; text_speeds.concat(pv_speedG); text_speeds.concat(":"); text_speeds.concat(pv_speedD); text_speeds.concat(":"); Serial.println(text_speeds); text_speeds=""; //Print speed (rpm) value to Visual Studio } //PID program if (motor_start){ e_speedG= set_speedG - pv_speedG; pwm_pulseG = e_speedG*kp + e_speed_sumG*ki + (e_speedG - e_speed_preG)*kd; e_speed_preG = e_speedG; //save last (previous) error e_speed_sumG += e_speedG; //sum of error e_speedD= set_speedD - pv_speedD; pwm_pulseD = e_speedD*kp + e_speed_sumD*ki + (e_speedD - e_speed_preD)*kd; e_speed_preD = e_speedD; //save last (previous) error e_speed_sumD += e_speedD; //sum of error } else{ e_speedD = 0; e_speed_preD = 0; e_speed_sumD = 0; pwm_pulseD = 0; e_speedG = 0; e_speed_preG = 0; e_speed_sumG = 0; pwm_pulseG = 0; } byte pin_runG =5; byte pin_runD=10; // check if go forward or backward if(back==true){ pin_runG = pin_bwdG; //for H-bridge: run motor forward pin_runD = pin_bwdD; } else{ pin_runG=pin_fwdG; pin_runD=pin_fwdD; } // RUN MOTOR D if (pwm_pulseD <255 & pwm_pulseD >0){ analogWrite(pin_runD,pwm_pulseD); //set motor speed } else{ if(pwm_pulseD>255){ analogWrite(pin_runD,255); } else{ analogWrite(pin_runD,0); } } // RUN MOTOR G if (pwm_pulseG <255 & pwm_pulseG >0){ analogWrite(pin_runG,pwm_pulseG); //set motor speed } else{ if (pwm_pulseG>255){ analogWrite(pin_runG,255); } else{ analogWrite(pin_runG,0); } } } } void detect_aG() { encoderAG+=1; //increasing encoder at new pulse } void detect_bG() { encoderBG+=1; //increasing encoder at new pulse } void detect_aD() { encoderAD+=1; //increasing encoder at new pulse } void detect_bD() { encoderBD+=1; //increasing encoder at new pulse } void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: if (inChar != '\n') { mySt += inChar; } // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } }
[ "noreply@github.com" ]
CVandermies.noreply@github.com
97340e153703102f7d980bdcdbc51b72c28ec312
f1e1ebd6e6489f6eb4a9dfc7e962b01169bf2119
/projects/20200331 - Graphic/graphic.cpp
64a13c2b519665907f092465e7b6379be4908b6c
[]
no_license
juliosant/learn_CG-2020-1
9d23c6ed7bb25c9d7e757985634fa95599c91a81
32108b540caa295600bcb15defea41020446b017
refs/heads/master
2022-12-25T20:47:22.878739
2020-09-29T15:16:21
2020-09-29T15:16:21
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,048
cpp
//Júlio Victor Santiago; #include <iostream> #include <stdio.h> #include <string.h> #include<GLFW/glut.h> #include<Windows.h> GLint xRaster = 25, yRaster = 150; GLubyte label[36] = { 'J','a', 'n', 'F', 'e', 'v', 'M' , 'a', 'r', 'A','b', 'r', 'M', 'a', 'i', 'J' , 'u', 'n', 'J','u', 'l', 'A', 'g', 'o', 'S', 'e', 't', 'O','u', 't', 'N', 'o', 'v', 'D', 'e', 'z' }; GLint dataValue[12]{ 420, 342, 324, 310, 262, 185, 190, 196, 217, 240, 312, 438 }; void init(void) { glClearColor(0.0, 0.0, 0.0, 0); glMatrixMode(GL_PROJECTION); gluOrtho2D(0, 600, 0, 500); } void lineSegment(void) { GLint month, k; GLint x = 30; int n; glClear(GL_COLOR_BUFFER_BIT); glShadeModel(GL_SMOOTH); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_STRIP); for (k = 0; k < 12; k++) { n = dataValue[k]; if(n>= 300){ glColor3f(1.0, 0.0, 0.0); } if (n> 200 and n< 300) { glColor3f(1.0, 1.0, 0.0); } if (n <= 200) { glColor3f(0.0, 1.0, 0.0); } glVertex2i(x + k * 50, dataValue[k] - 4); } glEnd(); glColor3f(1.0, 0.0, 0.0); // Set marker color to red. for (k = 0; k < 12; k++) { n = dataValue[k]; if (n>= 300) { glColor3f(1.0, 0.0, 0.0); } if (n > 200 and dataValue[k] < 300) { glColor3f(1.0, 1.0, 0.0); } if (n <= 200) { glColor3f(0.0, 1.0, 0.0); } glRasterPos2i(xRaster + k * 50, dataValue[k] - 4); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, '*'); } glColor3f(1.0, 1.0, 1.0); // Set text color to white. xRaster = 20; // Display chart labels. for (month = 0; month < 12; month++) { glRasterPos2i(xRaster, yRaster); for (k = 3 * month; k < 3 * month + 3; k++) glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, label[k]); xRaster += 50; }; glFlush(); } // Programa Principal int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(50, 100); glutInitWindowSize(400, 300); glutCreateWindow("Capitulo 5"); init(); glutDisplayFunc(lineSegment); glutMainLoop(); return 0; }
[ "ctiebs@7setlabs.local" ]
ctiebs@7setlabs.local
750269d29b9606043226a5d36697e4e441892bd8
22134572c6455cbb431feb42815f86d22bb3feb5
/sprout/type/operation/pop_front.hpp
dae12354617f3de56dfb9d16297c1191a798a048
[ "BSL-1.0" ]
permissive
minamiyama1994/Sprout
49aecf397784c90596a47b32386ab13066d8a16d
f42e92b448c255161683e5cc7e456a1b77fd5d7e
refs/heads/master
2021-01-17T20:58:37.804818
2014-05-06T09:47:10
2014-05-06T09:47:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,354
hpp
/*============================================================================= Copyright (c) 2011-2014 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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) =============================================================================*/ #ifndef SPROUT_TYPE_OPERATION_POP_FRONT_HPP #define SPROUT_TYPE_OPERATION_POP_FRONT_HPP #include <sprout/config.hpp> #include <sprout/index_tuple/metafunction.hpp> #include <sprout/type/tuple.hpp> #include <sprout/type/rebind_types.hpp> namespace sprout { namespace types { // // pop_front // template<typename Tuple> struct pop_front { private: template<typename IndexTuple> struct apply_impl; template<sprout::index_t... Indexes> struct apply_impl<sprout::index_tuple<Indexes...> > : public sprout::types::rebind_types< Tuple >::template apply< typename sprout::types::tuple_element<Indexes, Tuple>::type... > {}; public: typedef typename apply_impl< typename sprout::index_range<1, sprout::types::tuple_size<Tuple>::value>::type >::type type; }; } // namespace types } // namespace sprout #endif // #ifndef SPROUT_TYPE_OPERATION_POP_FRONT_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
eccce67a7b8759c32115af2b8b9d781997e18fad
567395083ece9a0e5c4ff432b21163f585f6c62b
/c++/educative.io/1.literals/ratio.cpp
a678f7d50125e105daa9fb846779747f2ab44142
[ "MIT" ]
permissive
surendrasah/Coding-Playground
3f9fa9ce9b0fd0d629bc67328f4b1cfe2461384d
714babcc10cf9dde5c6f110bd16a12dc05064b60
refs/heads/master
2022-04-16T18:59:01.627463
2020-04-09T07:21:39
2020-04-09T07:21:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
249
cpp
#include <iostream> #include <chrono> using namespace std; int main(){ typedef ratio<5,4> ratio1; typedef ratio<2700> ratio2; cout << ratio1::num << endl << ratio1::den << endl; cout << ratio2::num << endl << ratio2::den << endl; }
[ "kalyan.ben10@live.com" ]
kalyan.ben10@live.com
c98c0e15e7f10cedb275781fd1d30fc09ef50628
94a155b2925f863dedfab9088b3a1233241e0563
/Motor2D/j1EntityManager.h
ce964136182e3e0ec3d897884a86d3193cc0e989
[ "MIT" ]
permissive
Adria-F/Clean-code-base-2D
21e4a5b8aad87e2eaccfc5bfad5eb1324eb0301f
20004a42c31b891cf54ccf35de2100653d2c0763
refs/heads/master
2020-03-19T15:00:27.217434
2018-06-08T18:18:03
2018-06-08T18:18:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
611
h
#ifndef __J1ENTITYMANAGER_H__ #define __J1ENTITYMANAGER_H__ #include "j1Module.h" #include <list> #define DEFAULT_ENTITY_SPEED 150 #include "Entity.h" class j1EntityManager : public j1Module { public: j1EntityManager() {} ~j1EntityManager(); // Called before the first frame bool Start(); // Called each loop iteration bool Update(float dt); // Called before quitting bool CleanUp(); Entity* createAlly(int x, int y); Entity* createEnemy(int x, int y); Entity* getEntity(int id); public: std::list<Entity*> entities; Entity* selected_entity = nullptr; }; #endif / __J1ENTITYMANAGER_H__
[ "adriaferrer2898@gmail.com" ]
adriaferrer2898@gmail.com
a4dd1f8504a045ea55f355f3b119649d716a9b5d
337259edcd7a30fd9a52384b192008f1a5687348
/otevri.h
63a3774767b25b5567dbb3920e53be8e2fa0536f
[]
no_license
alda519/crossdurr
29d804e4682a01136e0ba24ad330314b7f49e7f0
4711a6910f51d90c90bde79907e492cf753539c9
refs/heads/master
2021-01-02T08:52:33.222818
2012-12-16T16:16:03
2012-12-16T16:16:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
259
h
#ifndef OTEVRI_H #define OTEVRI_H #include <QDialog> namespace Ui { class Otevri; } class Otevri : public QDialog { Q_OBJECT public: explicit Otevri(QWidget *parent = 0); ~Otevri(); private: Ui::Otevri *ui; }; #endif // OTEVRI_H
[ "michal.cupak@gmail.com" ]
michal.cupak@gmail.com
5cfd8faa28962315982fffe62131e89051e65487
1e063c43cd27da15da2a9183d18c0313a4586313
/Main_V6/Board_Slave/Setup.cpp
d5c8101dbe685ac56df3d66e668a4f7e1592d4ac
[]
no_license
RIRPolytech/2017-2018_4A
2c4d7425182d6172fd06b5373138ec17eb4c51fc
10347740459d33d1458f294f05e1d25e921aef2f
refs/heads/master
2020-03-17T18:59:59.051036
2018-05-17T17:00:06
2018-05-17T17:00:06
133,842,258
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
#include "Setup.h" void Setup::Encoder() { // CODEUR DROIT pinMode(VOIXA_DROITE, INPUT); pinMode(VOIXB_DROITE, INPUT); digitalWrite(VOIXA_DROITE, HIGH); digitalWrite(VOIXB_DROITE, HIGH); // CODEUR GAUCHE pinMode(VOIXA_GAUCHE, INPUT); pinMode(VOIXB_GAUCHE, INPUT); digitalWrite(VOIXA_GAUCHE, HIGH); digitalWrite(VOIXB_GAUCHE, HIGH); }
[ "noreply@github.com" ]
RIRPolytech.noreply@github.com
392b6bc1ba220ced09a6c2c99c479d062a16bd80
d5f75adf5603927396bdecf3e4afae292143ddf9
/paddle/fluid/inference/api/resource_manager.h
03345403159d58f33c438a442b0139285d1bde34
[ "Apache-2.0" ]
permissive
jiweibo/Paddle
8faaaa1ff0beaf97ef7fb367f6c9fcc065f42fc4
605a2f0052e0ffb2fab3a4cf4f3bf1965aa7eb74
refs/heads/develop
2023-07-21T03:36:05.367977
2022-06-24T02:31:11
2022-06-24T02:31:11
196,316,126
3
2
Apache-2.0
2023-04-04T02:42:53
2019-07-11T03:51:12
Python
UTF-8
C++
false
false
4,534
h
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <atomic> #include <functional> #include <map> #include <memory> #include <mutex> #include "paddle/fluid/platform/macros.h" #include "paddle/phi/api/include/tensor.h" #include "paddle/phi/backends/cpu/forwards.h" #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) #include "paddle/fluid/platform/device/gpu/gpu_types.h" #include "paddle/phi/backends/gpu/forwards.h" #include "paddle/phi/backends/gpu/gpu_decls.h" #include "paddle/phi/backends/gpu/gpu_resources.h" #endif namespace paddle { namespace internal { class EigenGpuStreamDevice; } // namespace internal class CPUContextResource { public: CPUContextResource(); Eigen::DefaultDevice* GetCPUEigenDevice() const; private: void InitCPUResource(); private: std::unique_ptr<Eigen::DefaultDevice> cpu_eigen_device_; }; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) class GPUContextResource { public: explicit GPUContextResource(const phi::Place& place, void* stream); ~GPUContextResource(); gpuStream_t GetStream() const; dnnHandle_t GetDnnHandle() const; blasHandle_t GetBlasHandle() const; blasHandle_t GetBlasTensorCoreHandle() const; blasHandle_t GetBlasTF32Handle() const; blasLtHandle_t GetBlasLtHandle() const; phi::solverHandle_t GetSolverDnHandle() const; phi::sparseHandle_t GetSparseHandle() const; Eigen::GpuDevice* GetGpuEigenDevice() const; int GetGpuComputeCapability() const; int GetGpuRuntimeVersion() const; int GetGpuDriverVersion() const; int GetGPUMultiProcessors() const; int GetGpuMaxThreadsPerMp() const; int GetGpuMaxThreadsPerBlock() const; std::array<int, 3> GetGpuMaxGridDimSize() const; private: void InitGPUResource(void* stream); void DestroyGPUResource(); void InitGpuProperties(); void InitGpuEigenDevice(); void InitDnnHanlde(); void DestroyDnnHandle(); void InitBlasHandle(); void DestroyBlasHandle(); void InitBlasLtHandle(); void DestroyBlasLtHandle(); void InitSolverHandle(); void DestroySolverHandle(); void InitSparseHandle(); void DestroySparseHandle(); private: phi::Place place_; int compute_capability_; int runtime_version_; int driver_version_; int multi_process_; int max_threads_per_mp_; int max_threads_per_block_; std::array<int, 3> max_grid_dim_size_; bool owned_stream_{true}; gpuStream_t stream_; std::unique_ptr<Eigen::GpuDevice> gpu_eigen_device_; std::unique_ptr<internal::EigenGpuStreamDevice> eigen_stream_; blasHandle_t blas_handle_{nullptr}; blasHandle_t blas_tensor_core_handle_{nullptr}; blasHandle_t blas_tf32_tensor_core_handle_{nullptr}; blasLtHandle_t blaslt_handle_{nullptr}; dnnHandle_t dnn_handle_{nullptr}; phi::solverHandle_t solver_handle_{nullptr}; phi::sparseHandle_t sparse_handle_{nullptr}; // DnnWorkspaceHandle }; #endif class ResourceManager { public: ResourceManager() = default; static ResourceManager& Instance() { static ResourceManager* resource_manager = new ResourceManager; return *resource_manager; } // CPU Resource public: void InitCPUResource(); CPUContextResource* GetCPUResource() const; private: std::mutex cpu_mutex_; std::unique_ptr<CPUContextResource> cpu_resource_{nullptr}; // GPU Resource #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) public: void* InitGPUResource(const phi::Place& place, void* stream); void DestroyGPUResource(void* stream); GPUContextResource* GetGPUResource(void* stream) const; int RefCount(void* stream) const; private: void Decrease(void* stream); void Increase(void* stream); private: std::mutex gpu_mutex_; // a stream corresponding to a series of resource. std::map<void* /*stream*/, std::atomic<int>> ref_count_; std::map<void* /*stream*/, std::unique_ptr<GPUContextResource>> gpu_resources_; #endif private: DISABLE_COPY_AND_ASSIGN(ResourceManager); }; } // namespace paddle
[ "noreply@github.com" ]
jiweibo.noreply@github.com
a514964f4f071283c8fccc1797c0bfef1c7a4dcf
4f8e66ebd1bc845ba011907c9fc7c6400dd7a6be
/SDL_Core/src/components/JSONHandler/src/SDLRPCObjectsImpl/V2/SubscribeButton_request.cpp
bf1d4eb0b6548d7b2785e09a491980d906c7aa72
[]
no_license
zhanzhengxiang/smartdevicelink
0145c304f28fdcebb67d36138a3a34249723ae28
fbf304e5c3b0b269cf37d3ab22ee14166e7a110b
refs/heads/master
2020-05-18T11:54:10.005784
2014-05-18T09:46:33
2014-05-18T09:46:33
20,008,961
1
0
null
null
null
null
UTF-8
C++
false
false
2,769
cpp
// // Copyright (c) 2013, Ford Motor Company // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the // distribution. // // Neither the name of the Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "../include/JSONHandler/SDLRPCObjects/V2/SubscribeButton_request.h" #include "SubscribeButton_requestMarshaller.h" #include "../include/JSONHandler/SDLRPCObjects/V2/Marshaller.h" #include "ButtonNameMarshaller.h" #define PROTOCOL_VERSION 2 /* interface Ford Sync RAPI version 2.0O date 2012-11-02 generated at Thu Jan 24 06:36:23 2013 source stamp Thu Jan 24 06:35:41 2013 author RC */ using namespace NsSmartDeviceLinkRPCV2; SubscribeButton_request::~SubscribeButton_request(void) { } SubscribeButton_request::SubscribeButton_request(const SubscribeButton_request& c) : NsSmartDeviceLinkRPC::SDLRPCMessage(c) { *this=c; } bool SubscribeButton_request::checkIntegrity(void) { return SubscribeButton_requestMarshaller::checkIntegrity(*this); } SubscribeButton_request::SubscribeButton_request(void) : NsSmartDeviceLinkRPC::SDLRPCMessage(PROTOCOL_VERSION) { } bool SubscribeButton_request::set_buttonName(const ButtonName& buttonName_) { if(!ButtonNameMarshaller::checkIntegrityConst(buttonName_)) return false; buttonName=buttonName_; return true; } const ButtonName& SubscribeButton_request::get_buttonName(void) const { return buttonName; }
[ "kburdet1@ford.com" ]
kburdet1@ford.com
90a969c137d9f4c635491a883be56a36760a40a0
5979ad168e6780e5bc24d0ff58701febe8100395
/Desktop/rightWidget/sensorwarnsubdialog.cpp
5d1c324b0a92c41be1c1c836688cfb23aafdf93e
[]
no_license
mehome/qt
2be0bb32079a26d0803371a512d15aea3d82ef5a
ee474abc80edfeedcbd4f102a09b59ffd55db8df
refs/heads/master
2021-09-22T01:01:06.579673
2018-09-04T06:34:27
2018-09-04T06:34:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include "sensorwarnsubdialog.h" #include "ui_sensorwarnsubdialog.h" dialog_null_sensorWarnSubDialog::dialog_null_sensorWarnSubDialog(QWidget *parent) : QDialog(parent), ui(new Ui::dialog_null_sensorWarnSubDialog) { ui->setupUi(this); } dialog_null_sensorWarnSubDialog::~dialog_null_sensorWarnSubDialog() { delete ui; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain