text
stringlengths 8
6.88M
|
|---|
#include "SpaceMappedDataPersistenceHandler.h"
namespace Utilities
{
}
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
map<ll, ll> mp, mp1;
int main()
{
ll m,n,i,j,k,l,x,y,ans=0;
cin>>n;
fr(i,n)
{
cin>>x>>y;
ans+=mp[x+y]++, ans+=mp1[x-y]++;
}
cout<<ans<<endl;
}
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
void Solve() {
int N;
cin >> N;
if (N == 1) {
cout << 2 << "\n";
return;
}
if (N == 2) {
cout << 16 << "\n";
return;
}
if (N == 3) {
cout << 32 << "\n";
return;
}
cout << 4 << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
int T;
cin >> T;
while (T --> 0) {
Solve();
}
}
|
#include "SDL2DemoFramework.h"
#include "DemoUtils/DrawModel.h"
void SDL2DemoFramework::Input()
{
SDL_Event Event;
while(SDL_PollEvent(&Event))
{
if(Event.type == SDL_QUIT)
{
Running = false;
}
if(Event.type == SDL_KEYDOWN)
{
if(Event.key.keysym.sym == SDLK_w)
{CameraForward = true;}
if(Event.key.keysym.sym == SDLK_s)
{CameraBack = true;}
if(Event.key.keysym.sym == SDLK_a)
{CameraLeft = true;}
if(Event.key.keysym.sym == SDLK_d)
{CameraRight = true;}
if(Event.key.keysym.sym == SDLK_r)
{CameraUp = true;}
if(Event.key.keysym.sym == SDLK_f)
{CameraDown = true;}
if(Event.key.keysym.sym == SDLK_q)
{CameraRotLeft = true;}
if(Event.key.keysym.sym == SDLK_e)
{CameraRotRight = true;}
if(Event.key.keysym.sym == SDLK_3)
{SwitchDrawCso = true;}
if(Event.key.keysym.sym == SDLK_4)
{SwitchDrawJunction = true;}
if(Event.key.keysym.sym == SDLK_5)
{SwitchDrawSpline = true;}
if(Event.key.keysym.sym == SDLK_1)
{SetPreviousDemo = true;}
if(Event.key.keysym.sym == SDLK_2)
{SetNextDemo = true;}
if(Event.key.keysym.sym == SDLK_9)
{ChangeState = true;}
}
if(Event.type == SDL_KEYUP)
{
if(Event.key.keysym.sym == SDLK_w)
{CameraForward = false;}
if(Event.key.keysym.sym == SDLK_s)
{CameraBack = false;}
if(Event.key.keysym.sym == SDLK_a)
{CameraLeft = false;}
if(Event.key.keysym.sym == SDLK_d)
{CameraRight = false;}
if(Event.key.keysym.sym == SDLK_r)
{CameraUp = false;}
if(Event.key.keysym.sym == SDLK_f)
{CameraDown = false;}
if(Event.key.keysym.sym == SDLK_q)
{CameraRotLeft = false;}
if(Event.key.keysym.sym == SDLK_e)
{CameraRotRight = false;}
if(Event.key.keysym.sym == SDLK_3)
{SwitchDrawCso = false;}
if(Event.key.keysym.sym == SDLK_4)
{SwitchDrawJunction = false;}
if(Event.key.keysym.sym == SDLK_5)
{SwitchDrawSpline = false;}
if(Event.key.keysym.sym == SDLK_1)
{SetPreviousDemo = false;}
if(Event.key.keysym.sym == SDLK_2)
{SetNextDemo = false;}
if(Event.key.keysym.sym == SDLK_9)
{ChangeState = false;}
}
}
}
void SDL2DemoFramework::Logic()
{
if(CameraForward)
{Camera->Move(0.0,0.0,-5.0);}
if(CameraBack)
{Camera->Move(0.0,0.0, 5.0);}
if(CameraLeft)
{Camera->Move(-5.0,0.0,0.0);}
if(CameraRight)
{Camera->Move( 5.0,0.0,0.0);}
if(CameraUp)
{Camera->Move(0.0,-5.0,0.0);}
if(CameraDown)
{Camera->Move(0.0, 5.0,0.0);}
if(CameraRotLeft)
{Camera->Rotate(-10.0);}
if(CameraRotRight)
{Camera->Rotate( 10.0);}
if(SwitchDrawCso)
{
DRAW_CSO = !DRAW_CSO;
SDL_Delay(100);
}
if(SwitchDrawJunction)
{
DRAW_JUNCTION = !DRAW_JUNCTION;
SDL_Delay(100);
}
if(SwitchDrawSpline)
{
DRAW_SPLINE = !DRAW_SPLINE;
SDL_Delay(100);
}
if(SetPreviousDemo)
{
Demo->SetPreviousDemo();
SDL_Delay(100);
}
if(SetNextDemo)
{
Demo->SetNextDemo();
SDL_Delay(100);
}
if(ChangeState)
{
Demo->ChangeState();
SDL_Delay(100);
}
}
void SDL2DemoFramework::Rendering()
{
glClearColor(0.975f, 0.975f, 0.975f, 1.0f); // torlesi szin beallitasa
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // kepernyo torles
glViewport(0, 0, ScreenWidth, ScreenHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
Camera->ApplyProjectionTransform();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Camera->ApplyViewTransform();
Demo->Draw();
SDL_GL_SwapWindow(Window);
}
void SDL2DemoFramework::Loop()
{
while(Running)
{
Input();
Logic();
Rendering();
}
}
SDL2DemoFramework::SDL2DemoFramework(int width,int height,IDemo *demo,ICamera *camera)
:ScreenWidth(width),ScreenHeight(height),Demo(demo),Camera(camera)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
Window = SDL_CreateWindow("FuGenDemo",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_OPENGL);
if(Window == nullptr)
{
return;
}
GLContext = SDL_GL_CreateContext(Window);
if(GLContext == nullptr)
{
return;
}
SDL_ShowWindow(Window);
}
SDL2DemoFramework::~SDL2DemoFramework()
{
delete Demo;
delete Camera;
SDL_GL_DeleteContext(GLContext);
SDL_DestroyWindow(Window);
SDL_Quit();
}
|
#include "proto_printer_source.h"
#include <CORE/BASE/checks.h>
#include <CORE/BASE/logging.h>
#include <CORE/HASH/crc32.h>
#include <CORE/UTIL/stringutil.h>
#include <fstream>
#include <set>
#include <string>
using core::base::BlobSink;
using core::memory::Blob;
using core::types::EnumDef;
using core::types::FieldDef;
using core::types::MessageDef;
using core::types::ProtoDef;
using core::types::RpcFunctionDef;
using core::types::ServiceDef;
using core::types::tEnumList;
using core::types::tFieldList;
using core::types::tServiceList;
/**
*
*/
void printCppDescriptorGen(
std::ofstream &ofile,
const MessageDef &msgDef,
const std::string &package) {
const std::string genFunctionName =
core::util::IdentifierSafe(package + msgDef.m_name);
ofile << "static ::core::types::ProtoDescriptor InternalGenDescriptor_"
<< genFunctionName << "() {\n";
core::base::FakeSink sizer;
sizer << msgDef;
std::string buffer;
buffer.resize(sizer.size());
Blob bufferBlob(buffer);
BlobSink sink(bufferBlob);
sink << msgDef;
ASSERT(sizer.size() > 0);
ofile << "static const u8 data[" << sizer.size() << "] = {";
{
char hex[3];
snprintf(hex, 3, "%02x", buffer[0]);
ofile << "0x" << hex;
for (size_t i = 1; i < sizer.size(); ++i) {
char hex[3];
snprintf(hex, 3, "%02x", buffer[i]);
ofile << ", 0x" << hex;
}
}
ofile << "};\n";
ofile << "::core::memory::ConstBlob blob(data, ARRAY_LENGTH(data));\n";
ofile << "::core::base::ConstBlobSink sink(blob);\n";
ofile << "::core::types::MessageDef defSelf;\n";
ofile << "sink >> defSelf;\n";
ofile << "CHECK(!sink.fail());\n";
ofile << "return ::core::types::ProtoDescriptor(defSelf);\n";
ofile << "}\n";
ofile << "static const ::core::types::ProtoDescriptor &GenDescriptor_"
<< genFunctionName << "() {\n";
ofile << "static ::core::types::ProtoDescriptor descriptor = "
"InternalGenDescriptor_"
<< genFunctionName << "();\n";
ofile << "return descriptor;\n";
ofile << "}\n";
for (std::vector< MessageDef >::const_iterator message =
msgDef.m_messages.begin();
message != msgDef.m_messages.end();
++message) {
printCppDescriptorGen(ofile, *message, package + msgDef.m_name + "::");
}
}
/**
*
*/
void printStaticInitializers(
std::ofstream &ofile,
const MessageDef &msgDef,
const std::string &package) {
const std::string genFunctionName =
core::util::IdentifierSafe(package + msgDef.m_name);
ofile << "class StaticInitDescriptor_" << genFunctionName << " {\n";
ofile << "public: StaticInitDescriptor_" << genFunctionName << "() {\n";
ofile << "const ::core::types::ProtoDescriptor &descriptor = "
"GenDescriptor_"
<< genFunctionName << "();\n";
ofile << "::core::types::RegisterWithProtoDb(&descriptor);\n";
ofile << "}\n";
ofile << "};\n";
ofile << "static StaticInitDescriptor_" << genFunctionName << " temp_"
<< genFunctionName << ";\n";
for (std::vector< MessageDef >::const_iterator message =
msgDef.m_messages.begin();
message != msgDef.m_messages.end();
++message) {
printStaticInitializers(ofile, *message, package + msgDef.m_name + "::");
}
}
/**
*
*/
static void printCppVirtuals(
std::ofstream &ofile,
const MessageDef &msgDef,
const std::string &package) {
// Operator ==
ofile << "bool " << package << msgDef.m_name << "::operator ==(const "
<< package << msgDef.m_name << " &other) const {\n";
for (tFieldList::const_iterator field = msgDef.m_fields.begin();
field != msgDef.m_fields.end();
++field) {
if (field->m_repeated) {
ofile << "if (m_" << field->m_name << " != other.m_" << field->m_name
<< ") {\nreturn false;\n}\n";
} else if (field->m_type == FieldDef::FIELD_MSG) {
ofile << "if (has_" << field->m_name << "() != other.has_"
<< field->m_name << "()) {\nreturn false;\n}\n";
ofile << "if (has_" << field->m_name << "() && (m_" << field->m_name
<< " != other.m_" << field->m_name << ")) {\nreturn false;\n}\n";
} else {
ofile << "if (m_" << field->m_name << " != other.m_" << field->m_name
<< ") {\nreturn false;\n}\n";
}
}
ofile << "return true;\n";
ofile << "}\n\n";
// Operator !=
ofile << "bool " << package << msgDef.m_name << "::operator !=(const "
<< package << msgDef.m_name << " &other) const {\n";
ofile << "return !(*this == other);\n}\n\n";
// Serializers
ofile << "size_t " << package << msgDef.m_name << "::byte_size() const {\n";
ofile << "::core::base::FakeSink sink;\n";
ofile << "sink << *this;\n";
ofile << "return sink.size();\n";
ofile << "}\n\n";
ofile << "bool " << package << msgDef.m_name
<< "::oserialize(::core::base::iBinarySerializerSink &sink) const {\n";
ofile << "sink << *this;\n";
ofile << "return !sink.fail();\n";
ofile << "}\n";
ofile << "bool " << package << msgDef.m_name
<< "::iserialize(::core::base::iBinarySerializerSink &sink) {\n";
ofile << package << msgDef.m_name << "::Builder builder;\n";
ofile << "sink >> builder;\n";
ofile << "if (sink.fail()) {\n";
ofile << "return false;\n";
ofile << "}\n";
ofile << "*this = builder.build();\n";
ofile << "return true;\n";
ofile << "}\n";
ofile << "const void *" << package << msgDef.m_name
<< "::getField(const u32 fieldNum) const {\n";
{
int count = 0;
for (tFieldList::const_iterator field = msgDef.m_fields.begin();
field != msgDef.m_fields.end();
++field) {
if (!field->m_repeated) {
count++;
}
}
if (count > 0) {
ofile << "switch (fieldNum) {\n";
for (tFieldList::const_iterator field = msgDef.m_fields.begin();
field != msgDef.m_fields.end();
++field) {
if (field->m_repeated) {
continue;
}
ofile << "case " << field->m_fieldNum << ": {\n";
ofile << "return &m_" << field->m_name << ";\n";
ofile << "}\n";
}
ofile << "}\n";
}
}
ofile << "return nullptr;\n";
ofile << "}\n";
ofile << "const void *" << package << msgDef.m_name
<< "::getField(const u32 fieldNum, const size_t index) const {\n";
{
int count = 0;
for (tFieldList::const_iterator field = msgDef.m_fields.begin();
field != msgDef.m_fields.end();
++field) {
if (field->m_repeated) {
count++;
}
}
if (count > 0) {
ofile << "switch (fieldNum) {\n";
for (tFieldList::const_iterator field = msgDef.m_fields.begin();
field != msgDef.m_fields.end();
++field) {
if (!field->m_repeated) {
continue;
}
ofile << "case " << field->m_fieldNum << ": {\n";
ofile << "if (index >= get_" << field->m_name
<< "_size()) {\nreturn nullptr;\n}\n";
ofile << "return &m_" << field->m_name << "[index];\n";
ofile << "}\n";
}
ofile << "}\n";
}
}
ofile << "return nullptr;\n";
ofile << "}\n";
ofile << "const ::core::types::ProtoDescriptor &" << package << msgDef.m_name
<< "::getDescriptor() const {\n";
ofile << "return "
"GenDescriptor_"
<< core::util::IdentifierSafe(package) << msgDef.m_name << "();\n";
ofile << "}\n";
ofile << "\n";
for (std::vector< MessageDef >::const_iterator message =
msgDef.m_messages.begin();
message != msgDef.m_messages.end();
++message) {
printCppVirtuals(ofile, *message, package + msgDef.m_name + "::");
}
}
/**
* Prints the cpp file portion of the proto
*/
bool PrintCpp(
const ProtoDef &def,
const std::string &headerName,
const std::string &fileName) {
std::ofstream ofile(fileName);
if (!ofile.is_open()) {
return false;
}
ofile << "#include \"" << headerName << "\"\n";
ofile << "#include <CORE/UTIL/lexical_cast.h>\n";
if (!def.m_services.empty()) {
ofile << "#include <WRAPPERS/NET/packet_handler.h>\n";
}
ofile << "\n";
const std::vector< std::string > package =
core::util::Splitter().on('.').split(def.m_package);
for (std::vector< MessageDef >::const_iterator message =
def.m_messages.begin();
message != def.m_messages.end();
++message) {
printCppDescriptorGen(
ofile,
*message,
core::util::ReplaceStr(def.m_package, ".", "::") + "::");
}
for (std::vector< MessageDef >::const_iterator message =
def.m_messages.begin();
message != def.m_messages.end();
++message) {
printStaticInitializers(
ofile,
*message,
core::util::ReplaceStr(def.m_package, ".", "::") + "::");
}
for (std::vector< MessageDef >::const_iterator message =
def.m_messages.begin();
message != def.m_messages.end();
++message) {
printCppVirtuals(
ofile,
*message,
core::util::ReplaceStr(def.m_package, ".", "::") + "::");
}
/*
for (std::vector< ServiceDef >::const_iterator service =
def.m_services.begin();
service != def.m_services.end();
++service) {
printCppServiceHandlers(
ofile,
*service,
core::util::ReplaceStr(def.m_package, ".", "::") + "::");
}
*/
return true;
}
|
/*
pxCore Copyright 2005-2021 John Robinson
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.
*/
// pxWindowNative.cpp
#define PX_NATIVE
#include "rtLog.h"
#include "pxOffscreenNative.h"
#include "pxWindowNative.h"
#include "../pxKeycodes.h"
#include "../pxWindow.h"
#include "../pxWindowUtil.h"
#ifndef WINCE
#include <tchar.h>
#define _ATL_NO_HOSTING
//#include <atlconv.h>
#endif
#include "windowsx.h"
#if 1
#ifdef __APPLE__
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#if defined(PX_PLATFORM_WAYLAND_EGL) || defined(PX_PLATFORM_GENERIC_EGL)
#include <GLES2/gl2.h>
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2ext.h>
#else
#include <GL/glew.h>
#ifdef WIN32
#include <GL/wglew.h>
#endif // WIN32
#ifdef PX_PLATFORM_GLUT
#include <GL/glut.h>
#endif
#include <GL/gl.h>
#endif //PX_PLATFORM_WAYLAND_EGL
#endif
#endif
#pragma warning(disable : 4311)
#pragma warning(disable : 4312)
#define WM_DEFERREDCREATE WM_USER + 1000
// With the addition of getting native events
// maybe this should be deprecated?
#define WM_SYNCHRONIZEDMESSAGE WM_USER + 1001
#ifdef WINCE
#define MOBILE
#include "aygshell.h"
#endif
using namespace std;
void setWindowPtr(HWND w, void* p) {
#ifndef WINCE
SetWindowLongPtr(w, GWLP_USERDATA, (LONG)p);
#else
SetWindowLong(w, GWL_USERDATA, (LONG)p);
#endif
}
void* getWindowPtr(HWND w) {
#ifndef WINCE
return (void*)GetWindowLongPtr(w, GWLP_USERDATA);
#else
return (void*)GetWindowLong(w, GWL_USERDATA);
#endif
}
// pxWindow
pxError pxWindow::init(int left, int top, int width, int height) {
#ifndef MOBILE
return initNative(NULL, left, top, width, height, WS_OVERLAPPEDWINDOW, 0);
#else
return initNative(NULL, left, top, width, height, WS_VISIBLE, 0);
#endif
}
#include <string>
pxError pxWindowNative::initNative(HWND parent, int left, int top, int width,
int height, DWORD style, DWORD styleEx) {
HINSTANCE hInstance = ::GetModuleHandle(NULL);
std::string className = "pxWindow";
WNDCLASS wc;
if (!::GetClassInfo(hInstance, className.c_str(), &wc)) {
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)windowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = className.c_str();
RegisterClass(&wc);
}
#ifndef MOBILE
mWindow =
::CreateWindowEx(styleEx, "pxWindow", "", style, left, top, width, height,
parent, NULL, hInstance, (pxWindowNative*)this);
#else
mWindow = CreateWindow(className.c_str(), L"", style, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL,
NULL, hInstance, (pxWindowNative*)this);
if (mWindow) {
SHDoneButton(mWindow, SHDB_SHOW);
SHFullScreen(mWindow, SHFS_HIDESIPBUTTON);
}
#endif
#if 1
HDC hdc = ::GetDC(mWindow);
HGLRC hrc;
static PIXELFORMATDESCRIPTOR pfd = {sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER | PFD_SWAP_EXCHANGE,
PFD_TYPE_RGBA,
24,
0,
0,
0,
0,
0,
0,
8,
0,
0,
0,
0,
0,
0,
24,
8,
0,
PFD_MAIN_PLANE,
0,
0,
0,
0};
int pixelFormat = ChoosePixelFormat(hdc, &pfd);
if (::SetPixelFormat(hdc, pixelFormat, &pfd)) {
hrc = wglCreateContext(hdc);
if (::wglMakeCurrent(hdc, hrc)) {
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) throw std::runtime_error("glewInit failed");
char *GL_version = (char *)glGetString(GL_VERSION);
char *GL_vendor = (char *)glGetString(GL_VENDOR);
char *GL_renderer = (char *)glGetString(GL_RENDERER);
rtLogInfo("GL_version = %s", GL_version);
rtLogInfo("GL_vendor = %s", GL_vendor);
rtLogInfo("GL_renderer = %s", GL_renderer);
}
}
#endif
return mWindow ? PX_OK : PX_FAIL;
}
void pxWindowNative::size(int& width, int& height) {
RECT r;
GetClientRect(mWindow, &r);
width = r.right - r.left;
height = r.bottom - r.top;
}
pxError pxWindow::term() {
// ::DestroyWindow(mWindow);
return PX_OK;
}
#if 1
void pxWindow::invalidateRect(pxRect* r) {
RECT wr;
RECT* pwr = NULL;
if (r) {
pwr = ≀
SetRect(pwr, r->left(), r->top(), r->right(), r->bottom());
}
InvalidateRect(getHWND(), pwr, FALSE);
}
#endif
bool pxWindow::visibility() {
return IsWindowVisible(getHWND()) ? true : false;
}
void pxWindow::setVisibility(bool visible) {
ShowWindow(getHWND(), visible ? SW_SHOW : SW_HIDE);
}
pxError pxWindow::setAnimationFPS(uint32_t fps) {
#if 0
if (mTimerId)
{
KillTimer(mWindow, mTimerId);
mTimerId = NULL;
}
if (fps > 0)
{
mTimerId = SetTimer(mWindow, 1, 1000/fps, NULL);
}
return PX_OK;
#else
pxWindowNative::setAnimationFPS(fps);
return PX_OK;
#endif
}
pxError pxWindowNative::setAnimationFPS(long fps) {
if (mTimerId) {
KillTimer(getHWND(), mTimerId);
mTimerId = NULL;
}
if (fps > 0) {
mTimerId = SetTimer(getHWND(), 1, 1000 / fps, NULL);
}
return PX_OK;
}
void pxWindow::setTitle(const char* title) {
#if 0
USES_CONVERSION;
::SetWindowText(mWindow, A2T(title));
#else
#ifndef WINCE
::SetWindowTextA(getHWND(), title);
#endif
#endif
}
pxError pxWindow::beginNativeDrawing(pxSurfaceNative& s) {
s = ::GetDC(getHWND());
return s ? PX_OK : PX_FAIL;
}
pxError pxWindow::endNativeDrawing(pxSurfaceNative& s) {
::ReleaseDC(getHWND(), s);
return PX_OK;
}
// pxWindowNative
pxWindowNative::~pxWindowNative() { setWindowPtr(mWindow, NULL); }
void pxWindowNative::sendSynchronizedMessage(char* messageName, void* p1) {
synchronizedMessage m;
m.messageName = messageName;
m.p1 = p1;
::SendMessage(mWindow, WM_SYNCHRONIZEDMESSAGE, 0, (LPARAM)&m);
}
LRESULT __stdcall pxWindowNative::windowProc(HWND hWnd, UINT msg, WPARAM wParam,
LPARAM lParam) {
int mouseButtonShift = 0;
pxWindowNative* w;
static HDC hDC;
static HGLRC hRC;
#ifndef WINCE
if (msg == WM_NCCREATE)
#else
if (msg == WM_CREATE)
#endif
{
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
// ::SetProp(hWnd, _T("wnWindow"), (HANDLE)cs->lpCreateParams);
setWindowPtr(hWnd, cs->lpCreateParams);
w = (pxWindowNative*)cs->lpCreateParams;
w->mWindow = hWnd;
} else
w = (pxWindowNative*)getWindowPtr(hWnd);
bool consumed = false;
if (w) {
pxEventNativeDesc e;
e.wnd = hWnd;
e.msg = msg;
e.wParam = wParam;
e.lParam = lParam;
w->onEvent(e, consumed);
if (consumed) {
// ick
if (e.msg == WM_SETCURSOR)
return 1;
else
return 0;
}
// re resolve the window ptr since we have destroyed it
w = (pxWindowNative*)getWindowPtr(hWnd);
if (w) {
switch (msg) {
// Special case code to handle the "fake" close button in the form
// of an OK button on win mobile
#ifdef MOBILE
case WM_COMMAND: {
unsigned int wmId = LOWORD(wParam);
unsigned int wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId) {
case IDOK:
SendMessage(w->mWindow, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(w->mWindow, msg, wParam, lParam);
}
} break;
#endif
#if 1
case WM_CREATE:
// We have to retry setting the animation timer if it happened to
// early after creation
w->onCreate();
PostMessage(hWnd, WM_DEFERREDCREATE, 0, 0);
break;
case WM_DEFERREDCREATE:
// w->onCreate();
if (w->mAnimationFPS) w->setAnimationFPS(w->mAnimationFPS);
break;
case WM_CLOSE:
w->onCloseRequest();
return 0;
break;
case WM_DESTROY:
w->onClose();
// SetProp(hWnd, _T("wnWindow"), NULL);
wglMakeCurrent(hDC, nullptr);
wglDeleteContext(hRC);
#ifdef WINCE
setWindowPtr(hWnd, NULL);
#endif
break;
#ifndef WINCE
case WM_NCDESTROY:
setWindowPtr(hWnd, NULL);
break;
#endif
case WM_RBUTTONDOWN:
mouseButtonShift++;
case WM_MBUTTONDOWN:
mouseButtonShift++;
case WM_LBUTTONDOWN: {
#if 1
SetCapture(w->mWindow);
unsigned long flags = 1 << mouseButtonShift;
if (GetKeyState(VK_CONTROL) < 0) flags |= PX_MOD_CONTROL;
if (GetKeyState(VK_SHIFT) < 0) flags |= PX_MOD_SHIFT;
if (GetKeyState(VK_MENU) < 0) flags |= PX_MOD_ALT;
w->onMouseDown(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), flags);
#endif
} break;
case WM_RBUTTONUP:
mouseButtonShift++;
case WM_MBUTTONUP:
mouseButtonShift++;
case WM_LBUTTONUP: {
#if 1
ReleaseCapture();
unsigned long flags = 1 << mouseButtonShift;
if (GetKeyState(VK_CONTROL) < 0) flags |= PX_MOD_CONTROL;
if (GetKeyState(VK_SHIFT) < 0) flags |= PX_MOD_SHIFT;
if (GetKeyState(VK_MENU) < 0) flags |= PX_MOD_ALT;
w->onMouseUp(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), flags);
#endif
} break;
case WM_MOUSEWHEEL: {
int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
int direction = (int(wParam) > 0) ? 1 : -1;
// w->onScrollWheel((float)(GET_X_LPARAM(lParam) * direction),
// (float)(GET_Y_LPARAM(lParam) * direction));
w->onScrollWheel((float)0, (float)zDelta > 0 ? 16 : -16);
printf("zDelta: %d direction: %d x: %d y: %d\n", zDelta, direction,
GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} break;
case WM_MOUSEMOVE:
#if 1
#ifndef WINCE
if (!w->mTrackMouse) {
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hWnd;
if (TrackMouseEvent(&tme)) {
w->mTrackMouse = true;
}
}
#endif
w->onMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
#endif
break;
#ifndef WINCE
case WM_MOUSELEAVE:
w->mTrackMouse = false;
w->onMouseLeave();
break;
#endif
case WM_TIMER:
// Should filter this to a single id
w->onAnimationTimer();
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN: {
unsigned long flags = 0;
if (GetKeyState(VK_SHIFT) & 0x8000) {
flags |= PX_MOD_SHIFT;
}
if (GetKeyState(VK_CONTROL) & 0x8000) {
flags |= PX_MOD_CONTROL;
}
if (GetKeyState(VK_MENU) & 0x8000) {
flags |= PX_MOD_ALT;
}
uint32_t keyCode = keycodeFromNative((int)wParam);
if (keyCode) w->onKeyDown(keyCode, flags);
// w->onChar((char)wParam);
} break;
case WM_CHAR:
w->onChar((char)wParam);
break;
case WM_KEYUP:
case WM_SYSKEYUP: {
unsigned long flags = 0;
if (GetKeyState(VK_SHIFT) & 0x8000) {
flags |= PX_MOD_SHIFT;
}
if (GetKeyState(VK_CONTROL) & 0x8000) {
flags |= PX_MOD_CONTROL;
}
if (GetKeyState(VK_MENU) & 0x8000) {
flags |= PX_MOD_ALT;
}
uint32_t keycode = keycodeFromNative((int)wParam);
if (keycode) w->onKeyUp(keycode, flags);
} break;
case WM_PAINT:
#if 1
{
PAINTSTRUCT ps;
HDC dc = BeginPaint(w->mWindow, &ps);
w->onDraw(dc);
SwapBuffers(
dc); // JRJR TODO should this be moved elsewhere into gl layer
EndPaint(w->mWindow, &ps);
return 0;
}
#endif
break;
case WM_SIZE: {
w->onSize(LOWORD(lParam), HIWORD(lParam));
} break;
case WM_ERASEBKGND: {
#if 0
PAINTSTRUCT ps;
HDC dc = BeginPaint(w->mWindow, &ps);
w->onDraw(dc);
EndPaint(w->mWindow, &ps);
#endif
}
return 0;
break;
case WM_SYNCHRONIZEDMESSAGE: {
synchronizedMessage* m = (synchronizedMessage*)lParam;
w->onSynchronizedMessage(m->messageName, m->p1);
} break;
#endif
}
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
|
#include "bob.h"
namespace bob {
std::string hey(std::string line) {
line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());
int upperCase = 0, lowerCase = 0, digitCase = 0;
for (auto c : line) {
if (isupper(c)) upperCase++;
if (islower(c)) lowerCase++;
if (isdigit(c)) digitCase++;
}
if (line.size() == 0)
return "Fine. Be that way!";
else if (lowerCase == 0 && upperCase > 0 && line[line.size() - 1] == '?' && digitCase == 0)
return "Calm down, I know what I'm doing!";
else if (upperCase > 0 && digitCase > 0 && lowerCase == 0)
return "Whoa, chill out!";
else if (upperCase > 6)
return "Whoa, chill out!";
else if (line[line.size() - 1] == '?')
return "Sure.";
else
return "Whatever.";
}
} // namespace bob
|
#include "HashingFunctions.h"
/*
- A high load factor is making the searching slow
- While a low load factor is using too much memory
The perfect load factor for a hashtable is around ~log 2 (~0.7),
because of reasons I won't go into in this comment.. :p
In the linear probing table,
I'm using 20, because it's really close to the perfect load factor in this example, at least.
*/
#define HASH_TABLE_CHAINING_SIZE 20
int CreateAndPrintHashTableLinearProbing()
{
HashTableLinearProbing<const Course> hashTable(HASH_TABLE_CHAINING_SIZE);
const Course** courses = GetCoursesFromFile();
// Insertion of courses
for (int i = 0; i < MAX_COURSES; i++)
{
if (!courses[i]) break;
const Course& course = *courses[i];
if (hashTable.insert(course)) printf(".");
else printf("X");
}
system("cls");
printf("\nAll courses succesfully loaded.");
// Information
printf("\nNumber of collisions: %d.\n", hashTable.getNrOfCollisions());
printf("Load Factor: %f.\n", hashTable.loadFactor());
// Contains/Searching testing
SearchAndPrint(hashTable);
// Deallocate the courses
for (size_t i = 0; i < MAX_COURSES; i++)
if (courses[i])
delete courses[i];
// Deallocate the ptr to the course pointers
delete courses;
printf("Going back to main menu.\n\n\n");
return 0;
}
std::vector<std::string> GetContentFromFile()
{
FILE *ft;
int ch;
std::vector<std::string> lines;
errno_t error = fopen_s(&ft, "C:/temp/courses.txt", "r");
printf("Error: %s\n", strerror(error));
bool quit = false;
while (!quit)
{
std::string current = "";
int c = '\0';
do
{
if (c != '\0')
current.push_back(c);
c = fgetc(ft);
} while (c != '\n' && c != EOF);
if (c == EOF) quit = true;
lines.push_back(current);
current.clear();
}
fclose(ft);
return lines;
}
const Course** GetCoursesFromFile()
{
const Course** courses;
courses = new const Course*[MAX_COURSES];
for (size_t i = 0; i < MAX_COURSES; i++)
courses[i] = nullptr;
int numberOfCourses = 0;
float points;
std::string code, name;
std::vector<std::string> lines = GetContentFromFile();
for (size_t i = 0; i < lines.size();)
{
if (lines[i].empty()) break;
code = lines[i]; i++;
name = lines[i]; i++;
points = atof(lines[i].c_str()); i++;
courses[numberOfCourses] = new const Course(code, name, points);
numberOfCourses++;
}
return courses;
}
void SearchAndPrint(HashTableLinearProbing<const Course>& table)
{
char input[24];
printf("\nCheck if hashtable contains course code: \nInput:");
std::cin >> input;
const Course course(input, "", 0.f);
int index = table.contains(course);
printf("Searching..\n");
if (index == -1) printf("\nThe table does NOT contain the course with the code: %s.\n", input);
else
{
const Course result = table.get(index);
printf("\nResult:\n");
printf("Course Code: %s\n", result.getCode().c_str());
printf("Course Name: %s\n", result.getName().c_str());
printf("Course Points: %.2f\n", result.getPoints());
}
}
void RemoveCourse(HashTableLinearProbing<const Course>& table, const Course& word)
{
std::string savedString = word.getCode();
printf("\nRemoving..\n");
if (table.remove(word)) printf("Removed course: %s.\n", savedString.c_str());
else printf("Could not find %s\n", savedString.c_str());
}
|
#include "system/pr2_eih_mapping.h"
#include "sqp/pr2_eih_sqp.h"
#include "../util/logging.h"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
const int T = TIMESTEPS;
class PR2EihMappingNBV : public PR2EihMapping {
public:
PR2EihMappingNBV(int max_occluded_regions, double max_travel_distance) :
PR2EihMapping(max_occluded_regions, max_travel_distance) { };
PR2EihMappingNBV() : PR2EihMappingNBV(1, 0.1) { }
void next_best_view(int max_iters, const MatrixJ& j_sigma0,
const std::vector<Gaussian3d>& obj_gaussians, const std::vector<geometry3d::Triangle>& obstacles,
StdVectorJ& J, StdVectorU& U);
private:
void sample_joint_trajectory(const VectorJ& j0, StdVectorJ& J, StdVectorU& U);
};
void PR2EihMappingNBV::next_best_view(int max_iters, const MatrixJ& j_sigma0,
const std::vector<Gaussian3d>& obj_gaussians, const std::vector<geometry3d::Triangle>& obstacles,
StdVectorJ& J, StdVectorU& U) {
VectorJ j_t = arm->get_joints();
const double alpha = 10;
J = StdVectorJ(T);
StdVectorJ J_i(T);
U = StdVectorU(T-1);
StdVectorU U_i(T-1);
double min_cost = INFINITY;
for(int i=0; i < max_iters; ++i) {
sample_joint_trajectory(j_t, J_i, U_i);
double cost = sys->cost(J_i, j_sigma0, U_i, obj_gaussians, alpha, obstacles);
if (cost < min_cost) {
min_cost = cost;
J = J_i;
U = U_i;
}
}
for(const VectorJ& j : J) {
sim->plot_transform(sim->transform_from_to(arm_sim->fk(j), "base_link", "world"));
}
}
void PR2EihMappingNBV::sample_joint_trajectory(const VectorJ& j0, StdVectorJ& J, StdVectorU& U) {
J = StdVectorJ(T);
U = StdVectorU(T-1);
J[0] = j0;
for(int t=0; t < T-1; ) {
U[t] = (1/float(T))*(M_PI/4.0)*VectorU::Random();
J[t+1] = sys->dynfunc(J[t], U[t], VectorQ::Zero());
Matrix4d pose = arm_sim->fk(J[t+1]);
if (pose(2,3) >= arm_sim->fk(home_joints)(2,3)) {
++t; // if z position above home pose, for safety
}
}
}
void parse_args(int argc, char* argv[],
bool& pause, int& max_occluded_regions, double& max_travel_distance, int& max_iters) {
std::vector<double> init_traj_control_vec;
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("p", "Pause between stages")
("m", po::value<int>(&max_occluded_regions)->default_value(1), "Maximum number of occluded regions during BSP")
("d", po::value<double>(&max_travel_distance)->default_value(1.0), "Maximum distance traveled when executing BSP controls")
("i", po::value<int>(&max_iters)->default_value(1000), "Maximum iterations for next-best-view")
;
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);
po::notify(vm);
pause = vm.count("p");
if (vm.count("help")) {
std::cout << desc << "\n";
exit(0);
}
} catch (std::exception &e) {
std::cerr << "error: " << e.what() << "\n";
exit(0);
}
ROS_INFO_STREAM("Max occluded regions: " << max_occluded_regions);
ROS_INFO_STREAM("Max travel distance: " << max_travel_distance);
}
int main(int argc, char* argv[]) {
// initialize ros node
ros::init(argc, argv, "pr2_eih_nbv");
log4cxx::LoggerPtr my_logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME);
my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Info]);
ROS_INFO("Starting ROS node");
ros::spinOnce();
bool pause;
int max_occluded_regions;
double max_travel_distance;
int max_iters;
parse_args(argc, argv, pause, max_occluded_regions, max_travel_distance, max_iters);
PR2EihMappingNBV brett_nbv(max_occluded_regions, max_travel_distance);
std::vector<Gaussian3d> obj_gaussians;
std::vector<geometry3d::Triangle> obstacles;
MatrixJ j_sigma0 = (M_PI/4)*MatrixJ::Identity(); // TODO: never update in MPC
StdVectorJ J;
StdVectorU U;
StdVectorJ grasp_joint_traj, return_grasp_joint_traj;
ros::Duration(0.5).sleep();
ROS_INFO("Resetting kinfu and turning on head");
brett_nbv.reset_kinfu();
while(!ros::isShuttingDown()) {
ROS_INFO("Getting occluded regions");
if (pause) { ROS_INFO("Press enter"); std::cin.ignore(); }
brett_nbv.get_occluded_regions(obj_gaussians, obstacles);
brett_nbv.display_gaussian_means(obj_gaussians);
ros::spinOnce();
ROS_INFO("Finding next-best-view");
if (pause) { ROS_INFO("Press enter"); std::cin.ignore(); }
ros::spinOnce();
brett_nbv.next_best_view(max_iters, j_sigma0, obj_gaussians, obstacles, J, U);
ROS_INFO("Displaying next-best-view");
if (pause) { ROS_INFO("Press enter"); std::cin.ignore(); }
brett_nbv.display_trajectory(J);
ROS_INFO("Executing control");
if (pause) { ROS_INFO("Press enter"); std::cin.ignore(); }
ros::spinOnce();
brett_nbv.execute_controls(U);
ROS_INFO("Checking if there exists a valid grasp trajectory");
if (brett_nbv.is_valid_grasp_trajectory(grasp_joint_traj, return_grasp_joint_traj)) {
ROS_INFO("Valid grasp trajectory exists! Execute grasp");
if (pause) { ROS_INFO("Press enter"); std::cin.ignore(); }
brett_nbv.execute_grasp_trajectory(grasp_joint_traj, return_grasp_joint_traj);
ROS_INFO("Resetting kinfu and turning on head");
brett_nbv.reset_kinfu();
}
ros::spinOnce();
ros::Duration(0.1).sleep();
}
}
|
#include "Const.h"
#include "Box.h"
#include "Game.h"
/**
* @param type 類型
* @param x, y 左上角座標
* @param bitmap 遊戲區域圖
* @param back 背面圖像
*/
Box::Box(Type type, int x, int y, QPixmap* bitmap, Spirit* back) :
Spirit(type, x, y, bitmap),m_currentImage(&m_imageDown1),m_back(back)
{
// 加載圖像2
m_imageDown2.load( QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 1) );
}
/**
* 建構子
*/
Box::~Box()
{
delete m_back;
}
/**
* 移動
* @param nDirection 方向
* @return 移動结果
*/
Box::MoveResult Box::move(int nDirection)
{
Box::MoveResult moveResult = Box::NO_MOVE;
bool bLeftFromDest = false;
int nDestX = m_x, nDestY = m_y;//小人要移動到的位置的座標
switch (nDirection)
{
case Qt::Key_A:
nDestX--;
break;
case Qt::Key_D:
nDestX++;
break;
case Qt::Key_W:
nDestY--;
break;
case Qt::Key_S:
nDestY++;
break;
}
//如果旁邊是牆或箱子,則直接返回
if ( Game::s_spirits[nDestY][nDestX]->getType() <= Spirit::BOX )
{
return moveResult;
}
moveResult = Box::NORMAL_MOVED;
//判斷是否要離開目的地
if ( m_type == Spirit::BOX && m_back->getType() == Spirit::DESTINATION )
{
bLeftFromDest = true;
moveResult = Box::LEFT_FROM_DEST;
m_currentImage = &m_imageDown1;
}
//用背面對象擦除自己
m_back->draw();
Game::s_spirits[m_y][m_x] = m_back;
//計算新位置
m_x = nDestX;
m_y = nDestY;
//設置新的背面對象
m_back = Game::s_spirits[m_y][m_x];
//判斷是否到達目的地
if ( m_type == Spirit::BOX && m_back->getType() == Spirit::DESTINATION )
{
if (bLeftFromDest)
{
moveResult = Box::NORMAL_MOVED;
}
else
{
moveResult = Box::ARRIVED_ON_DEST;
}
m_currentImage = &m_imageDown2;
}
//重繪自己
m_drawer.begin(m_bitmap);
m_drawer.drawImage(m_x * Const::GRID_SIZE, m_y * Const::GRID_SIZE, *m_currentImage);
m_drawer.end();
//將自己保存到陣列中
Game::s_spirits[m_y][m_x] = this;
return moveResult;
}
|
#include "GLExt.h"
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays;
PFNGLCREATESHADERPROC glCreateShader;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLDETACHSHADERPROC glDetachShader;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLDELETEPROGRAMPROC glDeleteProgram;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation;
PFNGLUNIFORM1FPROC glUniform1f;
void InitGL(const QOpenGLContext *context)
{
glGenBuffers = (PFNGLGENBUFFERSPROC)context->getProcAddress("glGenBuffers");
glBindBuffer = (PFNGLBINDBUFFERPROC)context->getProcAddress("glBindBuffer");
glBufferData = (PFNGLBUFFERDATAPROC)context->getProcAddress("glBufferData");
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)context->getProcAddress("glDeleteBuffers");
//
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)context->getProcAddress("glGenVertexArrays");
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)context->getProcAddress("glBindVertexArray");
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)context->getProcAddress("glEnableVertexAttribArray");
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)context->getProcAddress("glVertexAttribPointer");
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)context->getProcAddress("glDeleteVertexArrays");
//
glCreateShader = (PFNGLCREATESHADERPROC)context->getProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)context->getProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)context->getProcAddress("glCompileShader");
glDeleteShader = (PFNGLDELETESHADERPROC)context->getProcAddress("glDeleteShader");
//
glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)context->getProcAddress("glGetObjectParameterivARB");
glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)context->getProcAddress("glGetInfoLogARB");
//
glCreateProgram = (PFNGLCREATEPROGRAMPROC)context->getProcAddress("glCreateProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)context->getProcAddress("glAttachShader");
glDetachShader = (PFNGLDETACHSHADERPROC)context->getProcAddress("glDetachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)context->getProcAddress("glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)context->getProcAddress("glUseProgram");
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)context->getProcAddress("glDeleteProgram");
//
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)context->getProcAddress("glGetUniformLocation");
glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)context->getProcAddress("glGetAttribLocation");
//
glUniform1f = (PFNGLUNIFORM1FPROC)context->getProcAddress("glUniform1f");
}
|
#include <iostream>
int main()
{
char* text = "Hello world!"; // Is error with /permissive- but is not with /permissive
std::cout << text << std::endl;
return 0;
}
|
namespace AST_Graph{
template<typename Functional1, typename Functional2>
DataMemberPointersToIR<Functional1,Functional2>::DataMemberPointersToIR(const Functional1& addNodeFunctional, const Functional2& addEdgeFunctional,traversalType tT, pointerHandling graphEmpty) : DOTRepresentation<SgNode*>(),
nodeFunctional(addNodeFunctional), edgeFunctional(addEdgeFunctional),whichTraversal(tT)
{
graphNull = graphEmpty;
if(tT == memory_pool_traversal)
traverseMemoryPool();
};
/*************************************************************************************************************
* The function
* AST_Graph::DataMemberPointersToIR<Functional1, Functional2>::visit( SgNode* node)
* is an implementation of the virtual visit member function in the AST memory pool traversal.
* This implementation does not affect the tailored whole AST traversal.
**************************************************************************************************************/
template<typename Functional1, typename Functional2>
void
DataMemberPointersToIR<Functional1, Functional2>::visit( SgNode* node)
{
std::pair<SgNode*,std::string> nodePair(node,node->class_name());
FunctionalReturnType nodeReturnValue = nodeFunctional(nodePair);
if( nodeReturnValue.addToGraph == true )
generateGraph(node,-10);
}
//See header file for comment
template<typename Functional1>
void writeGraphOfMemoryPoolToFile(std::string filename, AST_Graph::pointerHandling graphNullPointers, Functional1 addNodeFunctional){
DataMemberPointersToIR<Functional1,defaultFilterBinary> graph(addNodeFunctional, defaultFilterBinary(), memory_pool_traversal, graphNullPointers);
graph.writeToFileAsGraph(filename);
}
//See header file for comment
template<typename Functional1, typename Functional2>
void writeGraphOfMemoryPoolToFile(std::string filename, AST_Graph::pointerHandling graphNullPointers, Functional1 addNodeFunctional, Functional2 addEdgeFunctional){
DataMemberPointersToIR<Functional1, Functional2> graph(addNodeFunctional, addEdgeFunctional, AST_Graph::memory_pool_traversal,graphNullPointers);
graph.writeToFileAsGraph(filename);
}
//See header file for comment
template<typename Functional1, typename Functional2>
void writeGraphOfAstSubGraphToFile(std::string filename, SgNode* node, AST_Graph::pointerHandling graphNullPointers, Functional1 func1, Functional2 func2, int depth){
DataMemberPointersToIR<Functional1, Functional2> graph(func1, func2, AST_Graph::whole_graph_AST, graphNullPointers);
graph.generateGraph(node,depth);
graph.writeToFileAsGraph(filename);
}
//See header file for comment
template<typename Functional1>
void writeGraphOfAstSubGraphToFile(std::string filename, SgNode* node, AST_Graph::pointerHandling graphNullPointers, Functional1 func1, int depth){
// AST_Graph::writeGraphOfAstSubGraphToFile(filename,node,func1,func1,depth,graphNullPointers);
DataMemberPointersToIR<Functional1,defaultFilterBinary> graph(func1, defaultFilterBinary(), AST_Graph::whole_graph_AST, graphNullPointers);
graph.generateGraph(node,depth);
graph.writeToFileAsGraph(filename);
}
template<typename Functional1, typename Functional2>
void
DataMemberPointersToIR<Functional1,Functional2>::generateGraph(SgNode* graphNode,int depth){
ROSE_ASSERT(std::find(NodeExists.begin(),NodeExists.end(),graphNode)==NodeExists.end());
ROSE_ASSERT(graphNode!=NULL);
//The functional edgeFunctional implements the criteria for if a node is to be graphed. If this is NULL
std::pair<SgNode*,std::string> pairGraphNode(graphNode,std::string("WARNING: this is just a name to have a name DO NOT USE"));
FunctionalReturnType nodeReturnValue = nodeFunctional(pairGraphNode);
if(nodeReturnValue.addToGraph==true){
//std::cout << "The node currently graphed is " << graphNode.second << ": " << graphNode.first << std::endl;
std::vector<std::pair<SgNode*,std::string> > vectorOfPointers =
graphNode->returnDataMemberPointers();
//Add a graph node for the node Node
if(nodeReturnValue.DOTLabel == "")
addNode(graphNode,graphNode->class_name(),nodeReturnValue.DOTOptions);
else
addNode(graphNode,nodeReturnValue.DOTLabel,nodeReturnValue.DOTOptions);
NodeExists.push_back(graphNode);
//Generate code to graph this data member pointer and generate all edges pointing from this
//data member pointer to other data member pointers
for (NodeTypeVector::size_type i = 0; i < vectorOfPointers.size(); i++)
{
FunctionalReturnType edgeReturnValue;
std::pair<SgNode*,std::string> edgeEndPoint = vectorOfPointers[i];
if( edgeEndPoint.first == NULL ){
//Hangle NULL pointers
edgeReturnValue.addToGraph = false;
if(graphNull==graph_NULL)
addNullValue(graphNode,"",edgeEndPoint.second,"");
}else{
edgeReturnValue = edgeFunctional(graphNode,edgeEndPoint);
if( (whichTraversal==memory_pool_traversal) ){
//If the node the edge points to should not be graphed and the edge
//is to be graphed, do not graph the edge if the memory pool traversal
//is used.
if( nodeFunctional(edgeEndPoint).addToGraph == false )
edgeReturnValue.addToGraph = false;
}//END IF MemoryPoolTraversal
}//END IF-ELSE
//If the edge functional says that the edge should be added and the edge end point
//is a node which should be graphed then graph it if depth is not 0. Depth is a control
//stucture for the whole graph traversal which gives the user an option to set the number
//of levels to be followed from a node.
if( (depth!=0) & ( edgeReturnValue.addToGraph == true ) & ( nodeFunctional(edgeEndPoint).addToGraph == true ) ){
//If the functional says that this node is to be added, do so
//This recursive function call is specific to the whole AST traversal and is how it
//operates
if(whichTraversal == whole_graph_AST){
//See if the node has already been graphed
if(std::find(NodeExists.begin(),NodeExists.end(),vectorOfPointers[i].first) == NodeExists.end())
generateGraph(edgeEndPoint.first,depth-1);
}
if(edgeReturnValue.DOTLabel == "")
addEdge(graphNode,edgeEndPoint.second,edgeEndPoint.first,
edgeReturnValue.DOTOptions);
else
addEdge(graphNode,edgeReturnValue.DOTLabel,edgeEndPoint.first,
edgeReturnValue.DOTOptions);
}//END IF
}//END FOR
}//END IF addToGraph == true
};
};// END NAMESPACE AST_Graph
|
/*--------------------------------------------------------*/
/* */
/* Author: Farhan Tariq Janjua */
/* Fiverr: https://www.fiverr.com/users/a1_developers/ */
/* */
/*--------------------------------------------------------*/
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <AsyncTCP.h>
#include "SPIFFS.h"
#include "SDDSerial.h"
#include "PubSubClient.h"
#include <AsyncElegantOTA.h>
#include "soc/timer_group_struct.h"
#include "soc/timer_group_reg.h"
#define CONNECT_TIMEOUT 10000 // should connect in 20 sec
const char *mqtt_publish_topic; //= "username/feeds/camera";
String publishTopic;
const char* mqttServer = "csmd.yourbsg.com";
const int mqttPort = 1883;
const char* mqttUser = "ubuntu";
const char* mqttPassword = "CSmd-2020BSG";
const char* WIFI_SSID = "SSID"; // Your Wifi network name here
const char* WIFI_PASS = "PW"; // Your Wifi network password here
WiFiClient espClient;
PubSubClient client(espClient);
AsyncWebServer server(80);
char inst2_data;
String ser2_read;
String ser_read;// = Serial.read();
char inst_data;
//=====================================
//functions decleration
String processor(const String& var);
String mac = "";
String msgq = "";
void callback(char* topic, byte *payload, unsigned int length) {
for (int i = 0; i < length; i++)
{
Serial2.print((char)payload[i]);
}
Serial2.println();
}
// uncomment all the above
void setup() {
Serial.begin(115200);
String MACaddress;
MACaddress = WiFi.macAddress();
Serial.print ("hello from ");
Serial.println (MACaddress);
publishTopic = MACaddress + "/result";//mac address of espe32/result
mqtt_publish_topic = publishTopic.c_str();
Serial.print("TOPIC: ");
Serial.println(mqtt_publish_topic);
cmd_init(&Serial2);
// Connect to Wi-Fi
WiFi.begin( WIFI_SSID, WIFI_PASS);
Serial.println("Connecting Wifi...");
uint32_t now = millis();
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
if ((millis() - now) > CONNECT_TIMEOUT)
{
ESP.restart();
}
}
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Hi! Maurice This shit works.");
});
Serial.println("Ready!");
AsyncElegantOTA.begin(&server); // Start ElegantOTA
server.begin();
Serial.println("HTTP server started");
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Max Free Heap: ");
Serial.println(ESP.getMaxAllocHeap());
Serial.println(WiFi.macAddress());
mac = (WiFi.macAddress());
Serial.println("");
Serial.println(F("Ready. Press d"));
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
;
//MQTT send message
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(200);
}
}
char espmac[33];
char inespmac[28];
String msg1 = "";
String msg2 = "";
msg1 = "hello mjr from " + mac;
msg1.toCharArray(espmac, 33);
msg2 = mac + "/cmd";
msg2.toCharArray(inespmac, 28);
client.subscribe(inespmac);
// client.publish(espmac, "hello maurice");
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str(), mqttUser, mqttPassword)) {
Serial.println("connected");
client.setCallback(callback);
}
// else {
// Serial.print("failed, rc=");
// Serial.print(client.state());
// Serial.println(" try again in 5 seconds");
// delay(5000);
// }
}
}
void publishSerialData(char *serialData) {
if (!client.connected()) {
reconnect();
}
String MACaddress;
String publishTopic;
MACaddress = WiFi.macAddress();
publishTopic = MACaddress + "/result";//mac address of espe32/result
mqtt_publish_topic = publishTopic.c_str();
client.publish(mqtt_publish_topic, serialData);
}
void loop() {
AsyncElegantOTA.loop();
client.loop();
// server.handleClient();
TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed = 1;
TIMERG0.wdt_wprotect = 0;
// The loop in this example acts as a serial passthrough for manual testing
if (Serial.available() > 0)
{
inst_data = char(Serial.read());
if (inst_data == '\n') {
Serial.print(ser_read);
}
else if (inst_data == ']')
{
ser_read = "";
}
else
{
ser_read += inst_data;
}
Serial2.write(inst_data);
}
if (Serial.available()) { // If anything comes in Serial (USB),
// read it and send it out Serial2
Serial2.write(Serial.read());
}
if (Serial2.available() > 0) {
char bfr[501];
memset(bfr, 0, 501);
Serial2.readBytesUntil( '\n', bfr, 500);
publishSerialData(bfr);
}
}
|
#include <iostream>
using namespace std;
/*
Проверить истинность высказывания: «Среди трех данных целых
чисел есть хотя бы одна пара взаимно противоположных».
*/
int main ()
{
int a,b,c;
cout<<"Введите первое число : ";
cin>>a;
cout<<"Введите второе число : ";
cin>>b;
cout<<"Введите третье число : ";
cin>>c;
if(a==(-c) || (-b)==c || b==(-a)){
cout<<"Истина («Среди трех данных целых чисел есть хотя бы одна пара взаимно противоположных»)"<<endl;
}
else{
cout<<"Не истина"<<endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
double max(double x, double y)
{
if (x > y)
return x;
return y;
}
double min(double x, double y)
{
if (x > y)
return y;
return x;
}
double add(double x, double y)
{
return x + y;
}
double multiply(double x, double y)
{
return x * y;
}
double diff(double x, double y)
{
return max(x, y) - min(x, y);
}
double avg(double x, double y)
{
return (max(x, y)+min(x, y))/2;
}
void clearInput()
{
char ch;
cin.clear();
while((ch = cin.get())!='\n')
continue;
}
int main()
{
double(*pf[6])(double, double) = {add, diff, multiply, max, min, avg};
while(true)
{
cout << "What do you want to do?\n"
<< "1. Add\t2. Difference\t3. Multiply\n"
<< "4. Max\t5. Min\t6. Average\t(Q)uit\n";
char choice;
cin.get(choice);
clearInput();
if (choice == 'Q' || choice == 'q')
{
cout << "Goodbye.\n"; break;
}
else if(choice > char('6') || choice < char('1'))
{
cout << "\nInvalid. Try again.";
continue;
}
while(true)
{
cout << "Give me two numbers, please.\n";
double x, y; cin >> x >> y;
if(!cin)
{
cout << "Invalid!\n";
clearInput();
continue;
}
if (choice == '1')
cout << "Answer: " << pf[0](x, y) << endl;
else if(choice == '2')
cout << "Answer: " << pf[1](x, y) << endl;
else if(choice == '3')
cout << "Answer: " << pf[2](x, y) << endl;
else if(choice == '4')
cout << "Answer: " << pf[3](x, y) << endl;
else if(choice == '5')
cout << "Answer: " << pf[4](x, y) << endl;
else if(choice == '6')
cout << "Answer: " << pf[5](x, y) << endl;
clearInput();
break;
}
}
return 0;
}
|
#include "Principal.h"
#include "Customs.h"
int *MAP_CHECK = (int*)0x0067198C;
int *MAIN_STATE = (int*)0x0067AC98;
ptr_glEnable glEnable_Real = (ptr_glEnable)&glEnable;
ptr_glClearColor glClearColor_Real = (ptr_glClearColor)&glClearColor;
unsigned int Textures[5];
RGBAStruct FogMapColor(int Map)
{
RGBAStruct rgb;
switch (Map)
{
case 0x0: // Lorencia
{
rgb.r = 0.85f; rgb.g = 0.8025f; rgb.b = 0.2805f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1: // Dungeon
{
rgb.r = 0.83f; rgb.g = 0.7581f; rgb.b = 0.6142f; rgb.a = 1.0f; return rgb;
}
break;
case 0x2: // Devias
{
rgb.r = 0.6643f; rgb.g = 0.8158f; rgb.b = 0.91f; rgb.a = 1.0f; return rgb;
}
break;
case 0x3: // Noria
{
rgb.r = 0.3689f; rgb.g = 0.58f; rgb.b = 0.2552f; rgb.a = 1.0f; return rgb;
}
break;
case 0x4: // Losttower
{
rgb.r = 0.0f; rgb.g = 0.0f; rgb.b = 0.0f; rgb.a = 1.0f; return rgb;
}
break;
case 0x6: // Stadium
{
rgb.r = 0.56f; rgb.g = 0.4424f; rgb.b = 0.308f; rgb.a = 1.0f; return rgb;
}
case 0x7: // Atlans
{
rgb.r = 0.451f; rgb.g = 0.6478f; rgb.b = 0.82f; rgb.a = 1.0f; return rgb;
}
break;
case 0x8: // Tarkan
{
rgb.r = 0.83f; rgb.g = 0.667f; rgb.b = 0.3154f; rgb.a = 1.0f; return rgb;
}
break;
case 0xA: // Icarus
{
rgb.r = 0.2744f; rgb.g = 0.3839f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x19: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1A: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1B: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1C: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1D: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1E: // Kalima
{
rgb.r = 0.1736f; rgb.g = 0.3475f; rgb.b = 0.56f; rgb.a = 1.0f; return rgb;
}
break;
case 0x1F: // Valley of Loren
{
rgb.r = 0.39f; rgb.g = 0.3156f; rgb.b = 0.1872f; rgb.a = 1.0f; return rgb;
}
break;
case 0x20: // Land of Trial
{
rgb.r = 0.0f; rgb.g = 0.0f; rgb.b = 0.0f; rgb.a = 1.0f; return rgb;
}
break;
default:
{
rgb.r = 0.0f; rgb.g = 0.0f; rgb.b = 0.0f; rgb.a = 1.0f; return rgb;
}
break;
}
}
void APIENTRY glEnable_Hooked(GLenum cap)
{
RGBAStruct rgb = FogMapColor(*MAP_CHECK);
GLfloat rgba[4] = { rgb.r, rgb.g, rgb.b, rgb.a };
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (*MAIN_STATE == 0x4)
{
glDisable(GL_FOG);
}
if (*MAIN_STATE == 5)
{
if (cap == GL_BLEND || cap == GL_TEXTURE_2D || cap == GL_DEPTH_TEST)
{
glDisable(GL_FOG);
}
glEnable_Real(GL_FOG);
glFogi(GL_FOG_MODE, GL_LINEAR);
glFogf(GL_FOG_DENSITY, 0.85f);
glFogfv(GL_FOG_COLOR, rgba);
glFogf(GL_FOG_START, 1200.0f);
glFogf(GL_FOG_END, 1800.0f);
glHint(GL_FOG_HINT, GL_NICEST);
if (cap == GL_BLEND || cap == GL_TEXTURE_2D || cap == GL_DEPTH_TEST)
{
glDisable(GL_FOG);
}
}
glEnable_Real(cap);
}
void APIENTRY glClearColor_Hooked(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
RGBAStruct rgb = FogMapColor(*MAP_CHECK);
if (*MAIN_STATE == 2)
{
glBindTexture(GL_TEXTURE_2D, *Textures);
glClearColor_Real(0.76f, 0.76f, 0.76f, 0.0f);
}
if (*MAIN_STATE == 4)
{
glBindTexture(GL_TEXTURE_2D, *Textures);
glClearColor_Real(0.0f, 0.0f, 0.0f, 0.0f);
return;
}
if (*MAIN_STATE == 5)
{
glBindTexture(GL_TEXTURE_2D, *Textures);
glClearColor_Real(rgb.r, rgb.g, rgb.b, 0.0f);
return;
}
glClearColor_Real(red,green,blue,alpha);
}
void FogOn()
{
RunningFG = !RunningFG;
HINSTANCE hInst;
hInst = 0;
HINSTANCE hInstance;
hInstance = 0;
hInstance = hInst;
DisableThreadLibraryCalls(hInst);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)glEnable_Real, glEnable_Hooked);
DetourAttach(&(PVOID&)glClearColor_Real, glClearColor_Hooked);
DetourTransactionCommit();
}
void FogOff()
{
RunningFG = !RunningFG;
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)glEnable_Real, glEnable_Hooked);
DetourDetach(&(PVOID&)glClearColor_Real, glClearColor_Hooked);
DetourTransactionCommit();
}
|
/*
MedianFilter.cpp - Median Filter for the Arduino platform.
Copyright (c) 2013 Phillip Schmidt. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
A median filter object is created by by passing the desired filter window size on object creation.
The window size should be an odd number between 3 and 255.
New data is added to the median filter by passing the data through the in() function. The new medial value is returned.
The new data will over-write the oldest data point, then be shifted in the array to place it in the correct location.
The current median value is returned by the out() function for situations where the result is desired without passing in new data.
!!! All data must be type INT. !!!
Window Size / avg processing time [us]
5 / 22
7 / 30
9 / 40
11 / 49
21 / 99
*/
#include "MedianFilter.h"
MedianFilter::MedianFilter(const byte size, const int seed)
{
medFilterWin = max(size, 3); // number of samples in sliding median filter window - usually odd #
medDataPointer = size >> 1; // mid point of window
data = (int*) calloc (size, sizeof(int)); // array for data
sizeMap = (byte*) calloc (size, sizeof(byte)); // array for locations of data in sorted list
locationMap = (byte*) calloc (size, sizeof(byte)); // array for locations of history data in map list
oldestDataPoint = medDataPointer; // oldest data point location in data array
for(byte i = 0; i < medFilterWin; i++) // initialize the arrays
{
sizeMap[i] = i; // start map with straight run
locationMap[i] = i; // start map with straight run
data[i] = seed; // populate with seed value
}
}
int MedianFilter::in(int value)
{
// sort sizeMap
// small vaues on the left (-)
// larger values on the right (+)
boolean dataMoved = false;
const byte rightEdge = medFilterWin - 1; // adjusted for zero indexed array
data[oldestDataPoint] = value; // store new data in location of oldest data in ring buffer
// SORT LEFT (-) <======(n) (+)
if(locationMap[oldestDataPoint] > 0){ // don't check left neighbours if at the extreme left
for(byte i = locationMap[oldestDataPoint]; i > 0; i--){ //index through left adjacent data
byte n = i - 1; // neighbour location
if(data[oldestDataPoint] < data[sizeMap[n]]){ // find insertion point, move old data into position
sizeMap[i] = sizeMap[n]; // move existing data right so the new data can go left
locationMap[sizeMap[n]]++;
sizeMap[n] = oldestDataPoint; // assign new data to neighbor position
locationMap[oldestDataPoint]--;
dataMoved = true;
}
else {
break; // stop checking once a smaller value is found on the left
}
}
}
// SORT RIGHT (-) (n)======> (+)
if(!dataMoved && locationMap[oldestDataPoint] < rightEdge){ // don't check right if at right border, or the data has already moved
for(int i = locationMap[oldestDataPoint]; i < rightEdge; i++){ //index through left adjacent data
int n = i + 1; // neighbour location
if(data[oldestDataPoint] > data[sizeMap[n]]){ // find insertion point, move old data into position
sizeMap[i] = sizeMap[n]; // move existing data left so the new data can go right
locationMap[sizeMap[n]]--;
sizeMap[n] = oldestDataPoint; // assign new data to neighbor position
locationMap[oldestDataPoint]++;
}
else {
break; // stop checking once a smaller value is found on the right
}
}
}
oldestDataPoint++; // increment and wrap
if(oldestDataPoint == medFilterWin)
oldestDataPoint = 0;
return data[sizeMap[medDataPointer]];
}
int MedianFilter::out() // return the value of the median data sample
{
return data[sizeMap[medDataPointer]];
}
// *** debug fuctions ***
/*
void MedianFilter::printData() // display sorting data for debugging
{
for(int i=0; i<medFilterWin; i++)
{
Serial.print(data[i]);
Serial.print("\t");
}
Serial.println("Data in ring buffer");
}
void MedianFilter::printSizeMap()
{
for(int i=0; i<medFilterWin; i++)
{
Serial.print(sizeMap[i]);
Serial.print("\t");
}
Serial.println("Size Map, data sorted by size");
}
void MedianFilter::printLocationMap()
{
for(int i=0; i<medFilterWin; i++)
{
Serial.print(locationMap[i]);
Serial.print("\t");
}
Serial.println("Location Map, size data sorted by age");
}
void MedianFilter::printSortedData() // display data for debugging
{
for(int i=0; i<medFilterWin; i++)
{
Serial.print(data[sizeMap[i]]);
Serial.print("\t");
}
Serial.println("Data sorted by size");
}
*/
|
//
// Copyright Jason Rice 2016
// 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 NBDL_CONCEPT_STRING_HPP
#define NBDL_CONCEPT_STRING_HPP
#include <nbdl/concept/DynamicBuffer.hpp>
#include <type_traits>
namespace nbdl {
// `is_string` stipulates that the type
// is used as a container of contiguous
// bytes that are unicode characters
// terminated by null
template <typename T>
inline constexpr bool is_string = false;
template <typename T>
concept String = nbdl::DynamicBuffer<T> && is_string<std::decay_t<T>>;
}
#endif
|
#include "pushButtonMagazine.h"
#include "config.h"
//byte sendData[PACKET_SIZE];
void setupMagazineButton()
{
pinMode(pushBtnMagazine, INPUT);
}
int updateMagazineButton()
{
int value = 0;
if(digitalRead(pushBtnMagazine) == LOW){
value = 1; // bitSafety bitSafety bitMagazine(32 or 0) bitFree bitFree bitFree bitFree bitFree
//Serial.println("MAGAZIN INSERTED");
}
sendData[3] += value;
return value;
}
|
/*
* SPDX-FileCopyrightText: 2017 Rolf Eike Beer <eike@sf-mail.de>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#pragma once
#include <libxml/tree.h>
#include <memory>
#include <osm2go_stl.h>
#include <osm2go_platform.h>
struct xmlDelete {
inline void operator()(xmlChar *s) {
xmlFree(s);
}
};
class xmlString : public std::unique_ptr<xmlChar, xmlDelete> {
public:
xmlString(xmlChar *txt = nullptr)
: std::unique_ptr<xmlChar, xmlDelete>(txt) {}
operator const char *() const
{ return reinterpret_cast<const char *>(get()); }
inline bool empty() const
{ return !operator bool() || *get() == '\0'; }
};
struct xmlDocDelete {
inline void operator()(xmlDocPtr doc) {
xmlFreeDoc(doc);
}
};
typedef std::unique_ptr<xmlDoc, xmlDocDelete> xmlDocGuard;
double xml_get_prop_float(xmlNode *node, const char *prop);
bool xml_get_prop_bool(xmlNode *node, const char *prop);
static inline double xml_parse_float(const xmlChar *str)
{
return osm2go_platform::string_to_double(reinterpret_cast<const char *>(str));
}
inline double xml_parse_float(const xmlString &str)
{ return xml_parse_float(str.get()); }
void format_float_int(int val, unsigned int decimals, char *str);
/**
* @brief convert a floating point number to a integer representation
* @param val the floating point value
* @param decimals the maximum number of decimals behind the separator
* @param str the buffer to print the number to, must be big enough
*
* This assumes that a "base 10 shift left by decimals" can still be
* represented as an integer. Trailing zeroes are chopped.
*
* 16 as length of str is enough for every possible value: int needs at most
* 10 digits, '-', '.', '\0' -> 13
*
* The whole purpose of this is to avoid using Glib, which would provide
* g_ascii_formatd(). One can't simply use snprintf() or friends, as the
* decimal separator is locale dependent and changing the locale is expensive
* and not thread safe. At the end this code is twice as fast as the Glib
* code, likely because it is much less general and uses less floating point
* operations.
*/
template<typename T>
void format_float(T val, unsigned int decimals, char *str)
{
for (unsigned int k = decimals; k > 0; k--)
val *= 10;
format_float_int(round(val), decimals, str);
}
/**
* @brief remove trailing zeroes from a number string
* @param str the buffer to modify
*
* This will remove all trailing zeroes if the buffer contains a delimiter
* (i.e. any character outside [0..9]. If the last character would be that
* delimiter it will also be removed.
*/
void remove_trailing_zeroes(char *str);
|
#pragma once
namespace KoalaComponent
{
enum NotificationConst
{
UNUSED_TAG = 0
};
inline int getUniqueId()
{
static int id = NotificationConst::UNUSED_TAG + 1;
return ++id;
}
template<typename... Args>
class Notification
{
public:
Notification( int dummyInt ):
//dummyInt used only for prevent creating unused notifications you should use MAKE_NOTIFICATION
tag( getUniqueId() )
{
assert( dummyInt == 691283 );
}
Notification& operator= ( const Notification& ) = delete;
Notification& operator= ( Notification && notification )
{
tag = notification.tag;
return *this;
}
Notification( const Notification& notification ) :
tag( notification.tag )
{
}
Notification( Notification&& notification ) :
tag( notification.tag )
{
}
int tag;
};
template<typename NotificationType>
struct notification_traits;
template<typename... Args>
struct notification_traits<Notification<Args...>>
{
using callback_type = typename Utils::Callback<void ( Args... )>;
};
}
|
#ifndef PIPE_H
#define PIPE_H
class Pipe {
};
#endif // PIPE_H
|
#include <iostream>
#include<vector>
#include <algorithm>
#include <string>
using namespace std;
string i2s(int n){
if(n == 0) return "0";
string s = "";
while(n != 0){
s += (char)(n%10 + '0');
n /= 10;
}
reverse(s.begin(), s.end());
return s;
}
static bool cmp(string a, string b){ // 这个函数应该声明为static的
return a+b < b+a;
}
string PrintMinNumber(vector<int> numbers) {
vector<string> num;
for(int i = 0; i < numbers.size(); ++i){
num.push_back(i2s(numbers[i]));
}
sort(num.begin(), num.end(), cmp);
string res = "";
for(int i = 0; i < numbers.size(); ++i){
res += num[i];
} return res;
}
int main(){
int len = 3;
int a[] = {3, 32, 321};
vector<int> num = vector<int>(a, a+len);
cout << PrintMinNumber(num) << endl;
return 0;
}
|
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return 0;
int a = x, b = 0;
while(x > 0) {b = 10*b + x % 10; x /= 10;}
return (a == b);
}
};
|
#ifndef __CONDITION_H
#define __CONDITION_H
#include "file.h"
// that's the condition interface; A condtion have just to be met
class Condition {
public:
virtual bool isMet(File*) = 0;
};
class FileExtensionIs : public Condition
{
string _str;
public:
FileExtensionIs(string);
bool isMet(File*);
};
class FilenameContains : public Condition
{
string _str;
public:
FilenameContains(string);
bool isMet(File*);
};
#endif
|
#pragma once
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/filesystem.hpp>
#include <boost/asio/io_service.hpp>
namespace chainbase {
namespace bip = boost::interprocess;
namespace bfs = boost::filesystem;
class pinnable_mapped_file {
public:
typedef typename bip::managed_mapped_file::segment_manager segment_manager;
enum map_mode {
mapped,
heap,
locked
};
pinnable_mapped_file(const bfs::path& dir, bool writable, uint64_t shared_file_size, bool allow_dirty, map_mode mode, std::vector<std::string> hugepage_paths);
pinnable_mapped_file(pinnable_mapped_file&& o);
pinnable_mapped_file& operator=(pinnable_mapped_file&&);
pinnable_mapped_file(const pinnable_mapped_file&) = delete;
pinnable_mapped_file& operator=(const pinnable_mapped_file&) = delete;
~pinnable_mapped_file();
segment_manager* get_segment_manager() const { return _segment_manager;}
private:
void set_mapped_file_db_dirty(bool);
void load_database_file(boost::asio::io_service& sig_ios);
void save_database_file();
bool all_zeros(char* data, size_t sz);
bip::mapped_region get_huge_region(const std::vector<std::string>& huge_paths);
bip::file_lock _mapped_file_lock;
bfs::path _data_file_path;
std::string _database_name;
bool _writable;
bip::mapped_region _file_mapped_region;
bip::mapped_region _mapped_region;
#ifdef _WIN32
bip::permissions _db_permissions;
#else
bip::permissions _db_permissions{S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH};
#endif
segment_manager* _segment_manager = nullptr;
constexpr static unsigned _db_size_multiple_requirement = 1024*1024; //1MB
};
std::istream& operator>>(std::istream& in, pinnable_mapped_file::map_mode& runtime);
std::ostream& operator<<(std::ostream& osm, pinnable_mapped_file::map_mode m);
}
|
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <networktables/NetworkTable.h>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace std;
using namespace nt;
Mat hsvImg;
Mat binaryImg;
// color filter params
int minColor_h = 30;
int minColor_s = 50;
int minColor_v = 50;
int maxColor_h = 70;
int maxColor_s = 255;
int maxColor_v = 255;
int hue_min_slider, hue_max_slider;
int sat_min_slider, sat_max_slider;
int val_min_slider, val_max_slider;
void on_min_hue(int, void *)
{
minColor_h = hue_min_slider;
}
void on_max_hue(int, void *)
{
maxColor_h = hue_max_slider;
}
void on_min_sat(int, void *)
{
minColor_s = sat_min_slider;
}
void on_max_sat(int, void *)
{
maxColor_s = sat_max_slider;
}
void on_min_val(int, void *)
{
minColor_v = val_min_slider;
}
void on_max_val(int, void *)
{
maxColor_v = val_max_slider;
}
int main() {
VideoCapture cap(0); // get 'any' cam
//VideoCapture cap("/dev/video1"); // get second camera
// initialize frame size
if (cap.isOpened()) {
cap.set(CV_CAP_PROP_FRAME_WIDTH,320);
cap.set(CV_CAP_PROP_FRAME_HEIGHT,240);
}
int lowThreshold = 20;
int ratio = 3;
int kernel_size = 3;
const int max_lowThreshold = 100;
// initialize slider values
hue_min_slider = minColor_h;
hue_max_slider = maxColor_h;
sat_min_slider = minColor_s;
sat_max_slider = maxColor_s;
val_min_slider = minColor_v;
val_max_slider = maxColor_v;
// slider control window - named "Thresholds"
namedWindow("Thresholds", 1);
createTrackbar("Hue Min", "Thresholds", &hue_min_slider, 255, on_min_hue);
createTrackbar("Hue Max", "Thresholds", &hue_max_slider, 255, on_max_hue);
createTrackbar("Sat Min", "Thresholds", &sat_min_slider, 255, on_min_sat);
createTrackbar("Sat Max", "Thresholds", &sat_max_slider, 255, on_max_sat);
createTrackbar("Val Min", "Thresholds", &val_min_slider, 255, on_min_val);
createTrackbar("Val Max", "Thresholds", &val_max_slider, 255, on_max_val);
// capture loop - runs forever
while( cap.isOpened() )
{
Mat inputImg;
if ( ! cap.read(inputImg) )
break;
cvtColor( inputImg, hsvImg, CV_BGR2HSV );
// color threshold input image into binary image
inRange(hsvImg, Scalar(minColor_h, minColor_s, minColor_v), Scalar(maxColor_h, maxColor_s, maxColor_v), binaryImg);
//imshow("original",inputImg);
imshow("Color Threshold",binaryImg);
int k = waitKey(1);
if ( k==27 )
break;
}
return 0;
}
|
#ifndef _GPIO_H_
#define _GPIO_H_
#include "stm32f0xx.h"
#include "System.h"
#include "delay.h"
class C_GPIO
{
public:
C_GPIO(){};
C_GPIO(GPIO_TypeDef * port, U16 pin){init_pin(port, pin);};
void init_pin(GPIO_TypeDef * port, U16 pin);
void set_as_input(GPIOPuPd_TypeDef type = GPIO_PuPd_NOPULL);
void set_as_output(GPIOOType_TypeDef type = GPIO_OType_PP);
inline void set(void){_port->BSRR = _pin;};
inline void clear(void){_port->BRR = _pin;};
void set_state(UI state);
UI get_state(void){ return (_port->IDR & _pin)? 1 : 0; };
void change_state(void);
void set_mode(GPIOMode_TypeDef mode);
protected:
GPIO_TypeDef * _port;
U16 _pin;
U16 _pin_number;
};
#endif
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwon <jwon@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/22 19:15:10 by jwon #+# #+# */
/* Updated: 2021/01/22 23:35:59 by jwon ### ########.fr */
/* */
/* ************************************************************************** */
#include "ClapTrap.hpp"
ClapTrap::ClapTrap()
{
m_name = "Anonymous";
std::cout << ">>> Clap cLap clAp claP TRAP.. " << m_name << "!!! <<<" << std::endl;
}
ClapTrap::ClapTrap(std::string name):
m_name(name)
{
std::cout << ">>> Clap cLap clAp claP TRAP.. " << m_name << "!!! <<<" << std::endl;
}
ClapTrap::ClapTrap(ClapTrap const & ref)
{
*this = ref;
}
ClapTrap& ClapTrap::operator=(ClapTrap const & ref)
{
if (this != &ref)
{
this->m_name = ref.m_name;
this->m_hp = ref.m_hp;
this->m_max_hp = ref.m_max_hp;
this->m_energy = ref.m_energy;
this->m_max_energy = ref.m_max_energy;
this->m_level = ref.m_level;
this->m_melee_damage = ref.m_melee_damage;
this->m_range_damage = ref.m_range_damage;
this->m_armor_reduction = ref.m_armor_reduction;
}
return (*this);
}
ClapTrap::~ClapTrap()
{
std::cout << ">>> Clap cLap clAp claP TRAP?? Bye " << m_name << " <<<" << std::endl;
}
unsigned int ClapTrap::rangedAttack(std::string const & target)
{
std::cout << m_name
<< " attacks " << target
<< " at range, causing " << m_range_damage
<< " points of damage!" << std::endl;
return (m_range_damage);
}
unsigned int ClapTrap::meleeAttack(std::string const & target)
{
std::cout << m_name
<< " attacks " << target
<< " at melee, causing " << m_melee_damage
<< " points of damage!" << std::endl;
return (m_melee_damage);
}
void ClapTrap::takeDamage(unsigned int amount)
{
m_hp = m_hp - amount + m_armor_reduction;
if (m_hp < 0)
m_hp = 0;
std::cout << m_name
<< ": Aaaaaah... (takes " << amount - m_armor_reduction
<< " damage)" << std::endl;
playerStatus();
}
void ClapTrap::beRepaired(unsigned int amount)
{
m_hp = m_hp + amount;
if (m_hp > m_max_hp)
m_hp = m_max_hp;
std::cout << m_name
<< ": WoW, McCol is delicious."
<< " (+ " << amount
<< " HP)" << std::endl;
playerStatus();
}
void ClapTrap::playerStatus(void)
{
std::cout << ">>> " << m_name << " -> "
<< "HP : " << m_hp
<< ", Energy : " << m_energy
<< ", Armor : " << m_armor_reduction
<< " <<<" << std::endl;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClassAbstractVM.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dgonor <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/29 19:48:41 by dgonor #+# #+# */
/* Updated: 2018/11/29 19:48:45 by dgonor ### ########.fr */
/* */
/* ************************************************************************** */
#include "ClassAbstractVM.hpp"
//#include <map>
//#include <regex>
AbstractVM::AbstractVM(void): i(0), exist_error(false), exist_exit(false), esc(false) {}
AbstractVM::AbstractVM(AbstractVM const ©){
if (this != ©)
*this = copy;
}
AbstractVM& AbstractVM::operator=(AbstractVM const &vm){
exist_error = vm.getExist_error();
exist_exit = vm.getExist_exit();
esc = vm.getEsc();
return *this;
}
AbstractVM::~AbstractVM(void){}
eOperandType AbstractVM::getType(std::string const &str_type) {
std::map<std::string, eOperandType > types = {
{"int8", Int8},
{"int16", Int16},
{"int32", Int32},
{"float", Float},
{"double", Double}
};
return (types[str_type]);
}
bool AbstractVM::getExist_error(void) const {
if (!this->exist_exit)
throw NoExistExitExcept();
return this->exist_error;
}
bool AbstractVM::getExist_exit(void) const {return this->exist_exit;}
bool AbstractVM::getEsc(void) const {return this->esc;}
void AbstractVM::setExit() {this->esc = true;}
void AbstractVM::setIterLine() {this->i = 0;}
void AbstractVM::valid_data(std::string const &str){
std::regex arg("[ \t]*((push)|(assert))[ \t]+?((int8)|(int16)|(int32)|(float)|(double))[ \t]*?\\(([-]?[0-9]*.[0-9]*)\\)[ \t]*([;].*)?");
std::regex fun("[\t ]*((exit)|(print)|(delim)|(mod)|(div)|(mul)|(sub)|(add)|(dump)|(pop)|(sum)|(avrg)|(asort)|(dsort)|(min)|(max))[\t ]*([;].*)?");
std::regex comm("[\t ]*([;].*)?");
this->i++;
if (!regex_match(str, arg) && !regex_match(str, fun) && !regex_match(str, comm)){
exist_error = true;
throw LexicalErrorExcept(std::to_string(this->i), str);
}
else if (regex_match(str, fun) && str.find("exit") != std::string::npos){
if (exist_exit)
{
exist_error = true;
throw DoubExitExcept(std::to_string(this->i));
}
exist_exit = true;
}
}
void AbstractVM::data_management(std::string const &str){
std::map<std::string, void (AbstractVM::*)(std::string const &str, eOperandType type)> arg_exe ={
{"assert", &AbstractVM::Assert},
{"push", &AbstractVM::Push},
};
std::map<std::string, void (AbstractVM::*)()> fun_exe = {
{"add", &AbstractVM::Add},
{"sub", &AbstractVM::Sub},
{"mul", &AbstractVM::Mul},
{"div", &AbstractVM::Div},
{"mod", &AbstractVM::Mod},
{"dump", &AbstractVM::Dump},
{"print", &AbstractVM::Print},
{"delim", &AbstractVM::Delim},
{"sum", &AbstractVM::Sum},
{"max", &AbstractVM::Max},
{"min", &AbstractVM::Min},
{"avrg", &AbstractVM::Avrg},
{"asort", &AbstractVM::Asort},
{"dsort", &AbstractVM::Dsort},
{"pop", &AbstractVM::Pop},
{"exit", &AbstractVM::Exit}
};
std::smatch result;
std::regex arg("[ \t]*((push)|(assert))[ \t]+?((int8)|(int16)|(int32)|(float)|(double))[ \t]*?\\(([-]?[0-9]*.[0-9]*)\\)[ \t]*([;].*)?");
std::regex fun("[\t ]*((exit)|(print)|(delim)|(mod)|(div)|(mul)|(sub)|(add)|(dump)|(pop)|(sum)|(avrg)|(asort)|(dsort)|(min)|(max))[\t ]*([;].*)?");
std::regex comm("[\t ]*([;].*)?");
this->i++;
if (regex_match(str, arg))
{
std::regex_search(str.begin(), str.end(), result, arg);
(this->*arg_exe[result.str(1)])(result.str(10), getType(result.str(4)));
}
else if (regex_match(str, fun))
{
std::regex_search(str.begin(), str.end(), result, fun);
(this->*fun_exe[result.str(1)])();
}
else if (regex_match(str, comm))
NULL;
else
throw LexicalErrorExcept(std::to_string(this->i), str);
}
void AbstractVM::Push(std::string const & str, eOperandType type){
v.push_back(factory.createOperand(type, str)); }
void AbstractVM::Assert(std::string const & str, eOperandType type){
const IOperand *assert;
assert = factory.createOperand(type, str);
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
if(!(*v.back() == *assert))
throw ErrorAssertExcept(std::to_string(this->i), v.back()->toString(), str);
}
void AbstractVM::Exit(void){ esc = true; }
void AbstractVM::Pop(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
v.pop_back();
}
void AbstractVM::Add(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *a = v.back();
v.pop_back();
const IOperand *b = v.back();
v.pop_back();
const IOperand *c = *a + *b;
Push(c->toString(), c->getType());
delete a;
delete b;
delete c;
}
void AbstractVM::Sub(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *a = v.back();
v.pop_back();
const IOperand *b = v.back();
v.pop_back();
const IOperand *c = *a - *b;
Push(c->toString(), c->getType());
delete a;
delete b;
delete c;
}
void AbstractVM::Mul(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *a = v.back();
v.pop_back();
const IOperand *b = v.back();
v.pop_back();
const IOperand *c = *b * *a;
Push(c->toString(), c->getType());
delete a;
delete b;
delete c;
}
void AbstractVM::Div(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *b = v.back();
v.pop_back();
const IOperand *a = v.back();
v.pop_back();
const IOperand *c = *a / *b;
Push(c->toString(), c->getType());
delete a;
delete b;
delete c;
}
void AbstractVM::Mod(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *a = v.back();
v.pop_back();
const IOperand *b = v.back();
v.pop_back();
const IOperand *c = *a % *b;
Push(c->toString(), c->getType());
delete a;
delete b;
delete c;
}
void AbstractVM::Dump(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
for(int i = v.size() - 1 ; i >= 0; i--)
v[i]->getPrint();
}
void AbstractVM::Print(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
{
if (v.back()->getType() != Int8)
throw PrintExcept(v.back()->toString(), std::to_string(this->i));
std::cout << static_cast<char>(std::stoi(v.back()->toString()));
}
}
void AbstractVM::Delim(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
std::cout << "__________________"
<< std::endl;
}
void AbstractVM::Sum(void){
if (v.size() < 2)
throw LessThanTwoArgExcept(std::to_string(this->i));
const IOperand *a = factory.createOperand(Double, std::to_string(0));
for(unsigned long i = 0; i < v.size(); i++)
a = *a + *(v[i]);
std::cout << "SUMM ";
a->getPrint();
}
void AbstractVM::Max(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
{
const IOperand *a = factory.createOperand(Int32, std::to_string(INT32_MIN));
for(unsigned long i = 0; i < v.size(); i++)
if (*(v[i]) > *a)
a = (v[i]);
std::cout << "MAX ";
a->getPrint();
}
}
void AbstractVM::Min(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else
{
const IOperand *a = factory.createOperand(Int32, std::to_string(INT32_MAX));
for (unsigned long i = 0; i < v.size(); i++)
if (*(v[i]) < *a)
a = (v[i]);
std::cout << "MIN ";
a->getPrint();
}
}
void AbstractVM::Avrg(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else {
const IOperand *a = factory.createOperand(Int32, std::to_string(0));
for (unsigned long i = 0; i < v.size(); i++)
a = *a + *(v[i]);
a = *a / *(factory.createOperand(a->getType(), std::to_string(v.size())));
std::cout << "AVRG ";
a->getPrint();
}
}
void AbstractVM::Asort(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else {
const IOperand *tmp;
for (unsigned long i = 0; i < v.size(); i++)
for (unsigned long j = 0; j < v.size(); j++)
{
if (i != j && *(v[i]) > *(v[j]))
{
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
}
}
void AbstractVM::Dsort(void){
if (v.empty())
throw EmptyStackExcept(std::to_string(this->i));
else {
const IOperand *tmp;
for (unsigned long i = 0; i < v.size(); i++)
for (unsigned long j = 0; j < v.size(); j++)
{
if (i != j && *(v[i]) < *(v[j]))
{
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
}
}
|
// Created by wangwenjie on 2013/04
#ifndef __SPLASH_SCENE_H__
#define __SPLASH_SCENE_H__
#include "cocos2d.h"
class Splash : public cocos2d::Layer
{
private:
long long m_startTime;
cocos2d::Scene *m_nextScene;
void onCreateNextScene(float delay);
void onGotoNextScene(float t);
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init() override;
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::Scene* createScene();
virtual void onEnterTransitionDidFinish() override;
// implement the "static node()" method manually
CREATE_FUNC(Splash);
};
#endif // __SPLASH_SCENE_H__
|
#include "unManaged_USB.h"
#include <time.h>
#include <windows.h>
static int parseRaw(unsigned char *datain, unsigned char *data_buffer, int *start_address, int *end_address, size_t size);
static void printProgress(float progress);
static void printText(int code,int data1, int data2);
unsigned char dataBuffer[65792];
int flashstage = 0;
int UnManaged_USB::cpp_flash_dev(unsigned char * program, size_t p_size, int fastmode, int timeout, int run)
{
micronucleus *my_device = NULL;
printText(1, timeout, 0);
printProgress(0.0f);
time_t start_time, current_time;
time(&start_time);
while (my_device == NULL){
delay(100);
my_device = micronucleus_connect(fastmode);
time(¤t_time);
if (timeout && start_time + timeout < current_time){
break;
}
}
if (my_device == NULL){
printText(2, 0, 0);
return 0;
}
printText(3, 0, 0);
printProgress(1.0f);
if(!fastmode){
float wait = 0.0f;
while(wait < 250){
wait += 50.0f;
delay(50);
}
}
printText(4, my_device->version.major, my_device->version.minor);
if (my_device->signature1) printText(5, (int)my_device->signature1, (int)my_device->signature2);
printText(6, my_device->flash_size,0);
printText(7, my_device->write_sleep,0);
printText(8, my_device->pages,my_device->page_size);
printText(9, my_device->erase_sleep,0);
int startAddress = 1, endAddress = 0;
memset(dataBuffer, 0xFF, sizeof(dataBuffer));
parseRaw(program ,dataBuffer,&startAddress, &endAddress, p_size);// change so that data gose in
if (startAddress >= endAddress){
printText(10, 0, 0);
return 0;
}
if (endAddress > my_device->flash_size){
printText(11, endAddress - my_device->flash_size,0);
return 0;
}
printText(12,0,0);
flashstage++;
int res = micronucleus_eraseFlash(my_device, printProgress);
if (res == 1) { // erase disconnection bug workaround
my_device = NULL;
delay(250);
int deciseconds_till_reconnect_notice = 50; // notice after 5 seconds
while (my_device == NULL) {
delay(100);
my_device = micronucleus_connect(fastmode);
deciseconds_till_reconnect_notice -= 1;
if (deciseconds_till_reconnect_notice == 0) {
printText(13, 0, 0);
}
}
printText(14, 0, 0);
} else if (res != 0) {
printText(15, res,0);
return 0;
}
printText(16, 0, 0);
flashstage++;
res = micronucleus_writeFlash(my_device, endAddress, dataBuffer, printProgress);
if (res != 0) {
printText(17, res, 0);
return 0;
}
if(run){
printText(18, 0, 0);
delay(500);
res = micronucleus_startApp(my_device);
if (res != 0) {
printText(19, res, 0);
return 0;
}
}
printProgress(0);
printText(20, 0, 0);
//printf(">> Micronucleus done. Thank you!\n");
return 1;
}
/******************************************************************************/
static int parseRaw(unsigned char *datain, unsigned char *data_buffer, int *start_address, int *end_address, size_t size) {
*start_address = 0;
*end_address = 0;
memcpy(data_buffer,datain,size);
*end_address = size-1;
return 0;
}
/******************************************************************************/
extern void flashevent(float value, int stage);
static void printProgress(float progress){
/*
// progres exeption
progress+=0.01f;
progress *= 100.0f;
int p = static_cast<int>(progress);
char c = '\r';
if (p==100)c = '\n';
printf("%3d%%%c", p, c);
//*/
// rasing mcpp event
flashevent(progress, flashstage);
}
extern void mprintText(int code, int data1, int data2);
static void printText(int code, int data1, int data2)
{
mprintText(code,data1,data2);
}
|
/*
* The Akafugu Nixie Clock
* (C) 2012-13 Akafugu Corporation
*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
*/
#include "global.h"
#include "rotary.h"
#include <avr/interrupt.h>
// rotary encoder
// NOTE: PB6 and PB7 are used for the oscillator on normal Arduino boards, and are not mapped to
// I/O pin numbers, so we will use direct pin access
#define ROTARY_DDR PORTB
#define ROTARY_PORT PORTB
#define ROTARY_1 PORTB6
#define ROTARY_2 PORTB7
#define ROTARY_1_PIN PINB6
#define ROTARY_2_PIN PINB7
////// interrupt handler for rotary encoder
//// increment/decrement s_rotary_raw_pos regarding pins state at each interrupt
// hold last state of pins
uint8_t s_encoder_state;
// Raw position of rotary encoder (4 ticks per click)
volatile int32_t s_rotary_raw_pos = 0;
// moved flag : set when moved. no automatic clear
volatile bool s_rotary_moved = false;
#if defined(BOARD_STANDARD) || defined(BOARD_MK2) || defined(BOARD_MODULAR)
# define POSITION_INCREMENT(v, n) (v) += (n)
# define POSITION_DECREMENT(v, n) (v) -= (n)
#elif defined(BOARD_DIET)
# define POSITION_INCREMENT(v, n) (v) -= (n)
# define POSITION_DECREMENT(v, n) (v) += (n)
#endif // board type
// fixme: set flag to see if rotary encoder is moving or not
// Rotary encoder interrupt
// Based on code in this library http://www.pjrc.com/teensy/td_libs_Encoder.html
ISR( PCINT0_vect )
{
uint8_t s = s_encoder_state & 3;
if (PINB & _BV(ROTARY_1_PIN)) s |= 4;
if (PINB & _BV(ROTARY_2_PIN)) s |= 8;
switch (s) {
case 0: case 5: case 10: case 15:
break;
case 1: case 7: case 8: case 14:
POSITION_INCREMENT(s_rotary_raw_pos, 1); break;
case 2: case 4: case 11: case 13:
POSITION_DECREMENT(s_rotary_raw_pos, 1); break;
case 3: case 12:
POSITION_INCREMENT(s_rotary_raw_pos, 2); break;
default:
POSITION_DECREMENT(s_rotary_raw_pos, 2); break;
}
s_encoder_state = (s >> 2);
s_rotary_moved = true;
}
static int Rotary::s_from = 0;
static int Rotary::s_to = 1;
static int Rotary::s_value_base = 0;
static int Rotary::s_divider = 1;
static int Rotary::s_saved_from = 0;
static int Rotary::s_saved_to = 1;
static int Rotary::s_saved_value = 0;
static int Rotary::s_saved_divider = 1;
void Rotary::begin()
{
// rotary encoder
ROTARY_DDR &= ~(_BV(ROTARY_1));
ROTARY_DDR &= ~(_BV(ROTARY_2));
// enable pullups for all rotary encoder pins
ROTARY_PORT |= _BV(ROTARY_1) | _BV(ROTARY_2); // enable pullup
// set up interrupt for rotary encoder pins
PCICR |= (1 << PCIE0);
PCMSK0 |= (1 << PCINT6);
PCMSK0 |= (1 << PCINT7);
// Initialize rotary encoder
uint8_t s = 0;
if (PINB & _BV(ROTARY_1_PIN)) s |= 1;
if (PINB & _BV(ROTARY_2_PIN)) s |= 2;
s_encoder_state = s;
}
bool Rotary::init(int from, int to, int current_value, int divider)
{
if (from < to) { s_from = from; s_to = to; }
else if (from > to) { s_from = to; s_to = from; }
else { s_from = from; s_to = to + 1; }
s_divider = divider;
s_value_base = current_value;
s_rotary_raw_pos = 0;
return !(from == to || divider <= 0 || s_value_base < s_from || s_to <= s_value_base);
}
int Rotary::getValue()
{
return (((s_value_base + (s_rotary_raw_pos + s_divider / 2) / s_divider) - s_from) % (s_to - s_from) + (s_to - s_from)) % (s_to - s_from) + s_from;
}
void Rotary::incrementValue()
{
s_rotary_raw_pos += s_divider;
}
void Rotary::decrementValue()
{
s_rotary_raw_pos -= s_divider;
}
void Rotary::save()
{
s_saved_from = s_from;
s_saved_to = s_to;
s_saved_value = getValue();
s_saved_divider = s_divider;
}
void Rotary::restore()
{
init(s_saved_from, s_saved_to, s_saved_value, s_saved_divider);
}
bool Rotary::isMoved()
{
return s_rotary_moved;
}
void Rotary::clearMoved()
{
s_rotary_moved = false;
}
|
#include<bits/stdc++.h>
using namespace std;
bool check(vector<stack<int>>& arr1,vector<queue<int>>& arr2,int n,int e)
{
for(int i=0;i<=n;i++)
{
stack<int> s = arr1[i];
queue<int> q = arr2[i];
while(!s.empty() && !q.empty())
{
if(s.top() != q.front())
{
return false;
}
s.pop();
q.pop();
if(s.size() != q.size())
{
return false;
}
}
}
return true;
}
int main()
{
int t;
cin >> t;
while(t--)
{
int n,e;
cin >> n >> e;
vector<stack<int>> arr1(n+1);
vector<queue<int>> arr2(n+1);
for(int i=0;i<e;i++)
{
int u,v;
cin >> u >> v;
arr1[u].push(v);
}
for(int i=0;i<e;i++)
{
int u,v;
cin >> u >> v;
arr2[u].push(v);
}
cout << check(arr1,arr2,n,e) << endl;
}
}
|
#include "ccmviewcontrols.h"
#include "dtccmtest.h"
CCMLogBar::CCMLogBar(QWidget *parent)
: QDockWidget(parent)
{
setFeatures(QDockWidget::DockWidgetMovable);
setWindowTitle(tr("System Output Log"));
m_pEditBar = new QTextEdit();
m_pEditBar->setReadOnly(true);
setWidget(m_pEditBar);
}
CCMLogBar::~CCMLogBar()
{
}
void CCMLogBar::slot_addLog(QString str, QColor c) {
m_pEditBar->setTextColor(c);
m_pEditBar->append(QDateTime::currentDateTime().toString("MM-dd hh:mm:ss:zzz ")+str);
}
CCMViewBar::CCMViewBar(QWidget *parent) :QWidget(parent) {
m_pImgView = new QLabel();
m_pImgView->setObjectName("ImgView");
QVBoxLayout *vlayout = new QVBoxLayout();
vlayout->addWidget(m_pImgView);
setLayout(vlayout);
}
CCMViewBar::~CCMViewBar()
{
}
CCMConnectStatusBar::CCMConnectStatusBar(QObject *parent)
: QThread(parent), nDevNum(0xFFFF)
{
//moveToThread(this);
}
CCMConnectStatusBar::~CCMConnectStatusBar()
{
}
void CCMConnectStatusBar::run() {
while (1) {
int DevNum = 0;
char* pDeviceName[8] = { NULL };
//¶ÈÐÅ
EnumerateDevice(pDeviceName, 8, &DevNum);
/*QStringList strlistDev;
for (int i=0;i<DevNum;i++)
{
strlistDev.append(QString(pDeviceName[i]));
}*/
if (nDevNum != DevNum) {
nDevNum = DevNum;
emit sig_statuschange(DevNum);
}
::Sleep(1000);
}
}
CCMConfigSelectDlg::CCMConfigSelectDlg(QWidget *parent)
:QDialog(parent),m_pvlayMain(new QVBoxLayout()),m_pcomboRule(new QComboBox()),m_pbutAdd(new QPushButton(tr("Add"))),\
m_pbutSelect(new QPushButton(tr("select"))),m_plabRule(new QLabel(tr("Config Rule:"))), m_pConfigAddDlg(new CCMConfigAddDlg(this))
{
setLayout(m_pvlayMain);
m_pvlayMain->addWidget(m_plabRule);
m_pvlayMain->addWidget(m_pcomboRule);
m_pvlayMain->addWidget(m_pbutSelect);
m_pvlayMain->addWidget(m_pbutAdd);
m_pvlayMain->addStretch(5);
setFixedSize(300, 150);
connect(m_pbutSelect, SIGNAL(clicked()), this, SLOT(slot_butSelect()));
connect(m_pbutAdd, SIGNAL(clicked()), this, SLOT(slot_butAdd()));
}
CCMConfigSelectDlg::~CCMConfigSelectDlg() {
}
void CCMConfigSelectDlg::slot_butSelect() {
dtCCMTest *pdtCCMTest = (dtCCMTest *)parent();
QSqlQuery query(pdtCCMTest->m_configDatabase);
query.prepare("update activeconfig set name = :name where 1");
query.bindValue(0, m_pcomboRule->currentText());
if (!query.exec()) {
QMessageBox::warning(this, "fail", tr("select rule fail!"));
emit pdtCCMTest->sgl_addLog(tr("select rule fail!"));
}
}
void CCMConfigSelectDlg::slot_butAdd() {
m_pConfigAddDlg->exec();
}
CCMConfigAddDlg::CCMConfigAddDlg(QSqlDatabase *database,QWidget *parent /* = 0 */) {
}
CCMConfigAddDlg::~CCMConfigAddDlg() {
}
void CCMConfigAddDlg::slot_butCommit() {
}
void CCMConfigAddDlg::slot_butCancel() {
}
|
#include "waveview.h"
Waveview::Waveview(QWidget* parent) : QChartView(parent) {
quint8 number=0;
while(number < WAVENUMBER){
_series_AP[number] = new QLineSeries;
number++;
}
_series = new QLineSeries;
wave_init();
}
void Waveview::wave_init()
{
WAVE wave_name = INS_YAW;
while(wave_name < WAVENUMBER){
_series_AP[wave_name]->setUseOpenGL(true);//OpenGL acceleration : more fast
wave_name = (WAVE)(wave_name + 1);
}
wave_name = INS_YAW;
//OpenGL acceleration : more fast
_series->setUseOpenGL(true);
// QChartView *chartview = new QChartView;
while(wave_name < WAVENUMBER){
chart()->addSeries(_series_AP[wave_name]);
wave_name = (WAVE)(wave_name + 1);
}
wave_name = INS_YAW;
chart()->setAnimationOptions(QChart::NoAnimation);
setRenderHint(QPainter::Antialiasing);//set fan zou yang
QValueAxis *axisX = new QValueAxis;
axisX->setLabelFormat("%u"); //设置刻度的格式
axisX->setGridLineVisible(true); //网格线可见
axisX->setTickCount(2); //设置多少格
axisX->setMinorTickCount(3); //设置每格小刻度线的数目
while(wave_name < WAVENUMBER){
chart()->setAxisX(axisX, _series_AP[wave_name]);
wave_name = (WAVE)(wave_name + 1);
}
wave_name = INS_YAW;
QValueAxis *axisY = new QValueAxis;
axisY->setLabelFormat("%g"); //设置刻度的格式
axisY->setGridLineVisible(true); //网格线可见
axisY->setTickCount(2); //设置多少格
axisY->setMinorTickCount(5); //设置每格小刻度线的数目
while(wave_name < WAVENUMBER){
chart()->setAxisY(axisY, _series_AP[wave_name]);
wave_name = (WAVE)(wave_name + 1);
}
//chart()->createDefaultAxes();
chart()->axisX()->setGridLineVisible(false);
chart()->axisY()->setGridLineVisible(false);
chart()->axisX()->setRange(0, 10000);
chart()->axisY()->setRange(-90, 90);
chart()->legend()->hide();
chart()->setTheme(QChart::ChartThemeDark);//switch theme
// Important to avoid our graph to look weird when optimizing memory usage later
disconnect(_series, SIGNAL(pointRemoved(int)), this, SLOT(update()));
}
|
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int father[210];
//查找祖先节点,当节点记录的祖先是自己,则表示查找到祖先了
int findFather(int x) {
while(x!=father[x]) {
x = father[x];
}
return x;
}
//合并节点:设置共同祖先
void Union(int a,int b) {
int fa = findFather(a);
int fb = findFather(b);
if(fa!=fb) {
father[fa] = fb;
}
}
//最开始的时候,每个节点时分散的,都是自己的祖先
void init() {
for(int i=0; i<210; i++) {
father[i] = i;
}
}
//主函数
int findCircleNum(vector<vector<int> >& M) {
init();
//对N个学生两两做判断
for(int i=0; i<M.size(); i++) {
for(int j=i+1; j<M.size(); j++) {
if(M[i][j]==1) {
Union(i,j);
}
}
}
//一次遍历找到所有祖先节点,即为朋友圈的个数
int res = 0;
for(int i=0; i<M.size(); i++) {
if(i==father[i]) {
res++;
}
}
return res;
}
int main()
{
vector<vector<int> > a;
vector<int> b;
int ch;
int x;
cin >> x;
for(int i = 0; i < x; i++) {
for(int j = 0; j < x; j++) {
cin >> ch;
b.push_back(ch);
}
a.push_back(b);
b.clear();
}
cout << findCircleNum(a) << endl;
return 0;
}
|
#include "Rasterizer.h"
#include <thread>
static Vector3 sFog = Vector3(1.0f, 1.0f, 0.95f);
static float fogDecal = -0.6f;
Rasterizer::Rasterizer(uint width, uint startHeight, uint endHeight, BufferData* bufferData)
{
m_startHeight = startHeight;
m_bufferData = bufferData;
m_height = endHeight;
m_width = width;
m_run = true;
m_started = false;
std::thread t = std::thread(&Rasterizer::Run, this);
t.detach();
}
void Rasterizer::Init()
{
//m_thread = std::thread(&Rasterizer::Run, this);
//m_thread.detach();
}
void Rasterizer::Run()
{
while (m_run)
{
if (m_started)
{
Render();
m_started = false;
}
else
{
//Sleep(1);
}
}
}
void Rasterizer::Start(const Triangle* triangles, uint nbTriangles, const std::vector<Line2D>* lines, const bool wireFrame)
{
m_lines = lines;
m_triangles = triangles;
m_nbTriangles = nbTriangles;
m_wireFrame = wireFrame;
m_started = true;
}
Rasterizer::~Rasterizer()
{
}
void Rasterizer::Clear()
{
m_lines = NULL;
m_triangles = NULL;
}
void Rasterizer::Render() const
{
for (int i = 0; i < m_lines->size(); i++)
{
const Line2D l = m_lines->at(i);
DrawLine(&l);
}
for (int i = 0; i < m_nbTriangles; i++)
{
const Triangle* t = &m_triangles[i];
DrawTriangle(t);
}
}
void Rasterizer::DrawLine(const Line2D* l) const
{
float x1 = l->xa;
float x2 = l->xb;
float y1 = l->ya;
float y2 = l->yb;
uint* buffer = m_bufferData->buffer;
float* zBuffer = m_bufferData->zBuffer;
const bool steep = abs(y2 - y1) > abs(x2 - x1);
if (steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = abs(y2 - y1);
float scaleX = 1.0;
float scaleY = 1.0;
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for (int x = (int)x1; x < maxX; x++)
{
if (x >= 0 && x < m_width && y >= m_startHeight && y < m_height)
{
if (steep)
{
uint k = x * m_bufferData->width + y;
if (k < m_bufferData->size)
{
buffer[k] = l->c;
}
}
else
{
uint k = y * m_bufferData->width + x;
if (k < m_bufferData->size)
{
buffer[k] = l->c;
}
}
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}
void Rasterizer::DrawTriangle(const Triangle* t) const
{
/*Vector2 v1 = Vector2((int)t->va->x, (int)t->va->y);
Vector2 v2 = Vector2((int)t->vb->x, (int)t->vb->y);
Vector2 v3 = Vector2((int)t->vc->x, (int)t->vc->y);*/
Vector2 v1 = Vector2((int)t->pa->x, (int)t->pa->y);
Vector2 v2 = Vector2((int)t->pb->x, (int)t->pb->y);
Vector2 v3 = Vector2((int)t->pc->x, (int)t->pc->y);
/* at first sort the three vertices by y-coordinate ascending so v1 is the topmost vertice */
sortVerticesAscendingByY(&v1, &v2, &v3);
/* here we know that v1.y <= v2.y <= v3.y */
/* check for trivial case of bottom-flat triangle */
if (v2.y == v3.y)
{
FillBottomFlatTriangle2(&v1, &v2, &v3, t);
}
/* check for trivial case of top-flat triangle */
else if (v1.y == v2.y)
{
FillTopFlatTriangle2(&v1, &v2, &v3, t);
}
else
{
/* general case - split the triangle in a topflat and bottom-flat one */
Vector2 v4 = Vector2((int)(v1.x + ((float)(v2.y - v1.y) / (float)(v3.y - v1.y)) * (v3.x - v1.x)), v2.y);
FillBottomFlatTriangle2(&v1, &v2, &v4, t);
FillTopFlatTriangle2(&v2, &v4, &v3, t);
}
// m_drawnTriangles++;
}
void Rasterizer::FillBottomFlatTriangle2(Vector2* v1, Vector2* v2, Vector2* v3, const Triangle* t) const
{
uint* buffer = m_bufferData->buffer;
Vector3 p;
float invslope1 = (v2->x - v1->x) / (v2->y - v1->y);
float invslope2 = (v3->x - v1->x) / (v3->y - v1->y);
float curx1 = v1->x;
float curx2 = v1->x;
float a, b;
for (int scanlineY = v1->y; scanlineY <= v2->y; scanlineY++)
{
int k;
if (scanlineY >= m_startHeight && scanlineY < m_height)
{
if (curx1 != curx2)
{
a = fmin(curx1, curx2);
b = fmax(curx1, curx2);
b++;
a = (int)(a < 0.0f ? 0.0f : a);
b = (int)(b > m_width ? m_width : b);
if (m_wireFrame)
{
if (a < b)
{
p.x = a;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
p.x = b - 1;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
}
}
else
{
for (int i = a; i < b; i++)
{
p.x = i;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
}
}
}
}
curx1 += invslope1;
curx2 += invslope2;
}
}
void Rasterizer::FillTopFlatTriangle2(Vector2* v1, Vector2* v2, Vector2* v3, const Triangle* t) const
{
uint* buffer = m_bufferData->buffer;
Vector3 p;
float invslope1 = (v3->x - v1->x) / (v3->y - v1->y);
float invslope2 = (v3->x - v2->x) / (v3->y - v2->y);
float curx1 = v3->x;
float curx2 = v3->x;
float a, b;
for (int scanlineY = v3->y; scanlineY > v1->y; scanlineY--)
{
if (scanlineY >= m_startHeight && scanlineY < m_height)
{
if (curx1 != curx2)
{
a = fmin(curx1, curx2);
b = fmax(curx1, curx2);
b++;
a = (int)(a < 0.0f ? 0.0f : a);
b = (int)(b > m_width ? m_width : b);
if (m_wireFrame)
{
if (a < b)
{
p.x = a;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
p.x = b - 1;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
}
}
else
{
for (int i = a; i < b; i++)
{
p.x = i;
p.y = scanlineY;
p.z = -1;
FillBufferPixel(&p, t);
}
}
}
}
curx1 -= invslope1;
curx2 -= invslope2;
}
}
inline const void Rasterizer::FillBufferPixel(const Vector3* p, const Triangle* t) const
{
/*float w2 = edgeFunction(t->va, t->vb, p);
float w0 = edgeFunction(t->vb, t->vc, p);
float w1 = edgeFunction(t->vc, t->va, p);*/
float w2 = edgeFunction(t->pa, t->pb, p);
float w0 = edgeFunction(t->pb, t->pc, p);
float w1 = edgeFunction(t->pc, t->pa, p);
float su, tu, cl, r, g, b, a, z, cla, clb, clc;
uint c, k;
//if (w0 >= 0 || w1 >= 0 || w2 >= 0)
{
w0 /= t->area;
w1 /= t->area;
w2 /= t->area;
const Material* texData = t->tex;
z = m_bufferData->zNear;
z = 1.0f / (t->pa->z * w0 + t->pb->z * w1 + t->pc->z * w2);
k = p->y * m_width + p->x;
float zf = m_bufferData->zBuffer[k];
static float zmin = 1000;
static float zmax = 0;
if (!t->options.ZBuffered() || z > zf)
{
m_bufferData->oBuffer[k] = t->owner;
m_bufferData->zBuffer[k] = z;
if (zmin > z)
{
zmin = z;
}
if (zmax < z)
{
zmax = z;
}
su = w0 * t->ua->x + w1 * t->ub->x + w2 * t->uc->x;
tu = w0 * t->ua->y + w1 * t->ub->y + w2 * t->uc->y;
cl = 1.0f;
RenderOptions::eLightMode lighting = t->options.LightMode();
if (lighting != RenderOptions::eLightMode_none)
{
Vector3 v = Vector3(1, -1, 1);
if (lighting == RenderOptions::eLightMode_gouraud)
{
Vector3 c = Vector3((w0 * t->na->x + w1 * t->nb->x + w2 * t->nc->x),
(w0 * t->na->y + w1 * t->nb->y + w2 * t->nc->y),
(w0 * t->na->z + w1 * t->nb->z + w2 * t->nc->z));
cl = -Vector3::Dot(&c, &v);
}
else
{
cl = -Vector3::Dot(t->n, &v);
}
}
if (texData)
{
if (texData->GetData())
{
tu = 1.0f - tu;
su = (int)(su * texData->GetWidth());
tu = (int)(tu * texData->GetHeight());
su = (int)su % texData->GetWidth();
tu = (int)tu % texData->GetHeight();
c = (uint)(((uint)tu * (uint)texData->GetWidth() + (uint)su) * 4);
const float* d = texData->GetData();
r = d[c] * cl;
g = d[c + 1] * cl;
b = d[c + 2] * cl;
a = d[c + 3] * cl;
}
else
{
r = texData->GetDiffuseColor()->x * cl;
g = texData->GetDiffuseColor()->y * cl;
b = texData->GetDiffuseColor()->z * cl;
a = 1.0f;
}
}
else
{
r = 1.0f * cl;
g = 0.0f * cl;
b = 1.0f * cl;
a = 1.0f;
}
r = clamp2(r, 0.0f, 1.0f);
g = clamp2(g, 0.0f, 1.0f);
b = clamp2(b, 0.0f, 1.0f);
c = ((int)(r * 255) << 16) + ((int)(g * 255) << 8) + (int)(b * 255);
m_bufferData->buffer[k] = c;
}
}
}
void Rasterizer::sortVerticesAscendingByY(Vector2* v1, Vector2* v2, Vector2* v3) const
{
if (v3->y < v2->y)
{
std::swap(*v2, *v3);
}
if (v2->y < v1->y) std::swap(*v1, *v2);
if (v3->y < v2->y) std::swap(*v2, *v3);
}
void Rasterizer::sortVerticesAscendingByY(Vector2* v1, Vector2* v2, Vector2* v3, Vector2* uv1, Vector2* uv2, Vector2* uv3) const
{
if (v3->y < v2->y)
{
std::swap(*v2, *v3);
std::swap(*uv2, *uv3);
}
if (v2->y < v1->y)
{
std::swap(*v1, *v2);
std::swap(*uv1, *uv2);
}
if (v3->y < v2->y)
{
std::swap(*v2, *v3);
std::swap(*uv2, *uv3);
}
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
* Eunsoo Park (esevan.park@gmail.com)
* Injung Hwang (sinban04@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __PROTOCOL_MANAGER_H__
#define __PROTOCOL_MANAGER_H__
#include <stdint.h>
namespace sc {
/**
* This is determined by the structure ProtocolData.
* In the ProtocolData, the size except the data pointer is the kProHeaderSize.
*/
#define kProtHeaderSize 6
/**
* Do not use architecture dependent sized types in this file
* e.g. such as size_t
*/
typedef struct {
uint16_t id;
uint32_t len;
const uint8_t *data;
} ProtocolData;
class ProtocolManager {
public:
static void data_to_protocol_data(const uint8_t *data, uint32_t len,
ProtocolData *ret_pd);
static uint32_t serialize(ProtocolData *pd, const uint8_t *buf,
uint32_t offset, uint32_t payload_size,
uint8_t **ret_vector);
static int send_packet(uint8_t *serialized, uint32_t packet_size, bool is_control);
static uint32_t recv_packet(uint8_t **seralized, bool is_control);
static uint32_t parse_header(uint8_t *serialized, ProtocolData *ret_pd);
private:
static uint16_t sPacketId;
static void serialize_header(ProtocolData *pd, uint8_t *vec_ptr);
static void serialize_data(const uint8_t *dat_buf, uint32_t len,
uint8_t *vec_ptr);
};
} /* namespace sc */
#endif /* !defined(__PROTOCOL_MANAGER_H__) */
|
#pragma once
#include <array>
#include <exception>
#include "base_types.hpp"
#include "simd.hpp"
namespace simd {
#if SIMD_SUPPORTS(SIMD_AVX)
using float64x4 = vector<double, 4>;
template <>
class vector<double, 4> : public vector_base<double, 4> {
public:
static constexpr int required_version = native_vector<type, width>::required_version;
public:
vector() : vector_base() {}
explicit vector(native_type v) : vector_base(v) {}
explicit vector(type f) : vector_base(_mm256_set1_pd(f)) {}
explicit vector(type f1, type f2, type f3, type f4) : vector_base(_mm256_set_pd(f4, f3, f2, f1)) {}
explicit vector(const std::array<type, width>& arr) : vector_base(_mm256_set_pd(arr[3], arr[2], arr[1], arr[0])) {}
explicit vector(const type *vals) : vector_base(_mm256_loadu_pd(vals)) {}
explicit vector(const type *vals, aligned_load) : vector_base(_mm256_load_pd(vals)) {}
explicit vector(const vector<int, 4> &v);
explicit vector(const vector<float, 4> &v);
vector<double, 4> &operator+=(const vector<double, 4> &v);
vector<double, 4> &operator-=(const vector<double, 4> &v);
vector<double, 4> &operator*=(const vector<double, 4> &v);
vector<double, 4> &operator/=(const vector<double, 4> &v);
friend vector<double, 4> operator+(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator-(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator*(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator/(vector<double, 4> v1, const vector<double, 4> &v2);
vector<double, 4> &operator&=(const vector<double, 4> &v);
vector<double, 4> &operator|=(const vector<double, 4> &v);
vector<double, 4> &operator^=(const vector<double, 4> &v);
friend vector<double, 4> operator~(const vector<double, 4> &v);
friend vector<double, 4> operator&(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator|(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator^(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> operator==(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> operator!=(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> operator>(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> operator>=(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> operator<(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> operator<=(const vector<double, 4> &v1, const vector<double, 4> &v2);
vector<double, 4> &hadd(const vector<double, 4> &v);
vector<double, 4> &hsub(const vector<double, 4> &v);
type hadd() const;
type hsub() const;
friend vector<double, 4> hadd(vector<double, 4> v1, const vector<double, 4> &v2);
friend vector<double, 4> hsub(vector<double, 4> v1, const vector<double, 4> &v2);
vector<double, 4> &abs();
friend vector<double, 4> abs(vector<double, 4> v);
friend vector<double, 4> min(const vector<double, 4> &v1, const vector<double, 4> &v2);
friend vector<double, 4> max(const vector<double, 4> &v1, const vector<double, 4> &v2);
vector<double, 4> &ceil();
vector<double, 4> &floor();
vector<double, 4> &round(int mode);
friend vector<double, 4> ceil(vector<double, 4> v);
friend vector<double, 4> floor(vector<double, 4> v);
friend vector<double, 4> round(vector<double, 4> v, int mode);
vector<double, 4> sqrt() const;
vector<double, 4> rsqrt() const;
friend vector<double, 4> select(const vector<double, 4> &v, const vector<double, 4> &alt, const mask<double, 4> &condition);
friend std::ostream &operator<<(std::ostream &stream, const vector<double, 4> &v);
};
template <>
class mask<double, 4> : public vector_base<double, 4> {
public:
SIMD_FORCEINLINE mask() : vector_base() {}
explicit SIMD_FORCEINLINE mask(native_type v) : vector_base(v) {}
explicit SIMD_FORCEINLINE mask(bool b) : vector_base(_mm256_castsi256_pd(_mm256_set1_epi64x(-static_cast<int>(b)))) {}
explicit SIMD_FORCEINLINE mask(bool b1, bool b2, bool b3, bool b4) : vector_base(_mm256_castsi256_pd(_mm256_set_epi64x(
-static_cast<int>(b4), -static_cast<int>(b3), -static_cast<int>(b2), -static_cast<int>(b1)))) {}
explicit SIMD_FORCEINLINE mask(const std::array<bool, width>& arr) : mask(arr[3], arr[2], arr[1], arr[0]) {}
explicit SIMD_FORCEINLINE mask(const vector<double, 4> & v) : vector_base(v) {}
friend SIMD_FORCEINLINE mask<double, 4> operator==(const mask<double, 4> & v1, const mask<double, 4> & v2);
friend SIMD_FORCEINLINE mask<double, 4> operator!=(const mask<double, 4> & v1, const mask<double, 4> & v2);
SIMD_FORCEINLINE mask<double, 4> & operator&=(const mask<double, 4> & v);
SIMD_FORCEINLINE mask<double, 4> & operator|=(const mask<double, 4> & v);
SIMD_FORCEINLINE mask<double, 4> & operator^=(const mask<double, 4> & v);
friend SIMD_FORCEINLINE mask<double, 4> operator~(const mask<double, 4> & v);
friend SIMD_FORCEINLINE mask<double, 4> operator&(mask<double, 4> v1, const mask<double, 4> & v2);
friend SIMD_FORCEINLINE mask<double, 4> operator|(mask<double, 4> v1, const mask<double, 4> & v2);
friend SIMD_FORCEINLINE mask<double, 4> operator^(mask<double, 4> v1, const mask<double, 4> & v2);
friend SIMD_FORCEINLINE mask<double, 4> andnot(const mask<double, 4> & v1, const mask<double, 4> & v2);
SIMD_FORCEINLINE int get_mask() const;
SIMD_FORCEINLINE bool all() const;
SIMD_FORCEINLINE bool any() const;
SIMD_FORCEINLINE bool none() const;
};
vector<double, 4> &vector<double, 4>::operator+=(const vector<double, 4> &v) {
m_vec = _mm256_add_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::operator-=(const vector<double, 4> &v) {
m_vec = _mm256_sub_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::operator*=(const vector<double, 4> &v) {
m_vec = _mm256_mul_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::operator/=(const vector<double, 4> &v) {
m_vec = _mm256_div_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::hadd(const vector<double, 4> &v) {
#if SIMD_SUPPORTS(SIMD_SSE3)
m_vec = _mm256_hadd_pd(m_vec, v.m_vec);
#else // SIMD_SUPPORTS(SIMD_SSE3)
throw std::runtime_error("Operation not implemented");
#endif // SIMD_SUPPORTS(SIMD_SSE3)
return *this;
}
vector<double, 4> &vector<double, 4>::hsub(const vector<double, 4> &v) {
#if SIMD_SUPPORTS(SIMD_SSE3)
m_vec = _mm256_hsub_pd(m_vec, v.m_vec);
#else // SIMD_SUPPORTS(SIMD_SSE3)
throw std::runtime_error("Operation not implemented");
#endif // SIMD_SUPPORTS(SIMD_SSE3)
return *this;
}
double vector<double, 4>::hadd() const {
throw std::runtime_error("Operation not implemented");
return 0.0;
// Results in A1+A2, ..., A3+A4, ...
/*auto t1 = _mm256_hadd_pd(m_vec, m_vec);
// Permute to get A1+A2, A3+A4, ...
auto t2 = _mm256_permute2f128_pd(m_vec, m_vec, 0b000001);
// Add (A1+A2)+(A3+A4), ...
auto t3 = _mm256_hadd_ps(t1, t1);
// Grab the first entry
return _mm256_cvtsd_f64(t3);*/
}
double vector<double, 4>::hsub() const {
throw std::runtime_error("Operation not implemented");
}
vector<double, 4> hadd(vector<double, 4> v1, const vector<double, 4> &v2) {
return v1.hadd(v2);
}
vector<double, 4> hsub(vector<double, 4> v1, const vector<double, 4> &v2) {
return v1.hsub(v2);
}
vector<double, 4> operator+(vector<double, 4> v1, const vector<double, 4> &v2) {
return (v1 += v2);
}
vector<double, 4> operator-(vector<double, 4> v1, const vector<double, 4> &v2) {
return (v1 -= v2);
}
vector<double, 4> operator*(vector<double, 4> v1, const vector<double, 4> &v2) {
return (v1 *= v2);
}
vector<double, 4> operator/(vector<double, 4> v1, const vector<double, 4> &v2) {
return (v1 /= v2);
}
vector<double, 4> &vector<double, 4>::operator&=(const vector<double, 4> &v) {
m_vec = _mm256_and_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::operator|=(const vector<double, 4> &v) {
m_vec = _mm256_or_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::operator^=(const vector<double, 4> &v) {
m_vec = _mm256_xor_pd(m_vec, v.m_vec);
return *this;
}
vector<double, 4> operator~(const vector<double, 4> &v) {
return vector<double, 4>(_mm256_xor_pd(v.m_vec, _mm256_castsi256_pd(_mm256_set1_epi32(-1))));
}
vector<double, 4> operator&(vector<double, 4> v1, const vector<double, 4> &v2) {
return v1 &= v2;
}
vector<double, 4> operator|(vector<double, 4> v1, const vector<double, 4> &v2) {
return v1 |= v2;
}
vector<double, 4> operator^(vector<double, 4> v1, const vector<double, 4> &v2) {
return v1 ^= v2;
}
vector<double, 4> operator==(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_EQ_OQ));
}
vector<double, 4> operator!=(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_NEQ_OQ));
}
vector<double, 4> operator>(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_GT_OQ));
}
vector<double, 4> operator>=(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_GE_OQ));
}
vector<double, 4> operator<(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_LT_OQ));
}
vector<double, 4> operator<=(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_LE_OQ));
}
vector<double, 4> &vector<double, 4>::abs() {
// TODO: benchmark for most performant solution
m_vec = _mm256_max_pd(_mm256_sub_pd(_mm256_setzero_pd(), m_vec), m_vec);
return *this;
}
vector<double, 4> abs(vector<double, 4> v) {
return v.abs();
}
vector<double, 4> min(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_min_pd(v1.m_vec, v2.m_vec));
}
vector<double, 4> max(const vector<double, 4> &v1, const vector<double, 4> &v2) {
return vector<double, 4>(_mm256_max_pd(v1.m_vec, v2.m_vec));
}
vector<double, 4> vector<double, 4>::sqrt() const {
return vector<double, 4>(_mm256_sqrt_pd(m_vec));
}
vector<double, 4> vector<double, 4>::rsqrt() const {
return vector<double, 4>(_mm256_div_pd(_mm256_set1_pd(1.0), _mm256_sqrt_pd(m_vec)));
}
vector<double, 4> &vector<double, 4>::ceil() {
m_vec = _mm256_ceil_pd(m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::floor() {
m_vec = _mm256_floor_pd(m_vec);
return *this;
}
vector<double, 4> &vector<double, 4>::round(int mode) {
// TODO: requires constant expression?
m_vec = _mm256_round_pd(m_vec, 0);
return *this;
}
vector<double, 4> ceil(vector<double, 4> v) {
return v.ceil();
}
vector<double, 4> floor(vector<double, 4> v) {
return v.floor();
}
vector<double, 4> round(vector<double, 4> v, int mode) {
return v.round(mode);
}
vector<double, 4> select(const vector<double, 4> &v, const vector<double, 4> &alt, const mask<double, 4> &condition) {
return vector<double, 4>(_mm256_blendv_pd(alt.m_vec, v.m_vec, condition.native()));
}
std::ostream &operator<<(std::ostream &stream, const vector<double, 4> &v) {
stream << '(';
for (size_t i = 0; i < v.width - 1; ++i) {
stream << v.m_array[i] << ' ';
}
stream << v.m_array[v.width - 1] << ')';
return stream;
}
mask<double, 4> operator==(const mask<double, 4> & v1, const mask<double, 4> & v2) {
return mask<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_EQ_OQ));
}
mask<double, 4> operator!=(const mask<double, 4> & v1, const mask<double, 4> & v2) {
return mask<double, 4>(_mm256_cmp_pd(v1.m_vec, v2.m_vec, _CMP_NEQ_OQ));
}
mask<double, 4> & mask<double, 4>::operator&=(const mask<double, 4> & v) {
m_vec = _mm256_and_pd(m_vec, v.m_vec);
return *this;
}
mask<double, 4> & mask<double, 4>::operator|=(const mask<double, 4> & v) {
m_vec = _mm256_or_pd(m_vec, v.m_vec);
return *this;
}
mask<double, 4> & mask<double, 4>::operator^=(const mask<double, 4> & v) {
m_vec = _mm256_xor_pd(m_vec, v.m_vec);
return *this;
}
mask<double, 4> operator~(const mask<double, 4> & v) {
return mask<double, 4>(_mm256_xor_pd(v.m_vec, _mm256_castsi256_pd(_mm256_set1_epi64x(-1))));
}
mask<double, 4> operator&(mask<double, 4> v1, const mask<double, 4> & v2) {
return v1 &= v2;
}
mask<double, 4> operator|(mask<double, 4> v1, const mask<double, 4> & v2) {
return v1 |= v2;
}
mask<double, 4> operator^(mask<double, 4> v1, const mask<double, 4> & v2) {
return v1 ^= v2;
}
mask<double, 4> andnot(const mask<double, 4> & v1, const mask<double, 4> & v2) {
return mask<double, 4>(_mm256_andnot_pd(v1.m_vec, v2.m_vec));
}
int mask<double, 4>::get_mask() const {
return _mm256_movemask_pd(m_vec);
}
bool mask<double, 4>::all() const {
// TODO: what is faster here?
return _mm256_movemask_pd(m_vec) == 0b1111;
}
bool mask<double, 4>::any() const {
return _mm256_movemask_pd(m_vec);
}
bool mask<double, 4>::none() const {
return !_mm256_movemask_pd(m_vec);
}
#endif // SIMD_SUPPORTS(SIMD_AVX)
} // namespace simd
|
#include "type.h"
#include <iostream>
using namespace std;
Type::Type() {
type = " ";
index = 0;
}
Type::Type(string type_, uint64_t index_) {
type = type_;
index = index_;
}
void Type::insertCharacter(Character newchar) {
for (int i = 0; i < chars.size(); i++) //See if character is already in the vector
if (chars[i].name == newchar.name)
return;
chars.push_back(newchar);
}
void Type::printCharacterList() {
int i = 0;
while (i < chars.size()) { //Iterate through vector, and call printCharacter for each character
chars[i].printCharacter();
i++;
}
}
int Type::getSizeType() {
int size = 0;
for (int i = 0; i < chars.size(); i++) //Iterate through character vector, add each size together
size = size + chars[i].getSize();
return size;
}
|
#include <cstdio>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
int t=1,r,n;
while(scanf("%d %d",&r,&n)!=EOF)
{
float v=r-n;
if(r==0 && n==0)
break;
if(r<n)
{
printf("Case %d: 0\n",t++);
}
else if(v/n>26)
{
printf("Case %d: impossible\n",t++);
}
else if(v/n<v)
{
int q=ceil(v/n);
printf("Case %d: %d\n",t++,q);
}
else
{
printf("Case %d: %d\n",t++,v/n);
}
}
return 0;
}
|
// github.com/andy489
#include <iostream>
#include <string>
#include <climits>
using namespace std;
struct Stone {
Stone *prev, *next;
string color;
int number;
Stone(string color, int number, Stone *prev = nullptr,
Stone *next = nullptr); //constructor with two default arguments
};
struct Path {
Stone *head, *tail; // in our case we use head only for printing
int size = 0;
Path(); // default constructor
// utility function for creating a new Node
Stone *getNewNode(string color, int number);
void addAtTail(string color, int number);
bool eraseAtTail();
// same as print but with operator << for the List
friend ostream &operator<<(ostream &os, const Path &list);
};
int main() {
Path LillyPath;
string color;
int number, i(1),j, count;
cout << "Enter count of stones at Lilly's path: ";
cin >> count;
for (; i <= count; ++i) {
if (i == 1)
cout << "~For every stone enter color and number separated by space:\n";
cout << "Stone " << i << ": ";
cin >> color >> number;
if (color == "white")
LillyPath.addAtTail(color, number);
else {
if (color == "green") {
int sumPrev(0);
for (j = 0; j < number; ++j) {
sumPrev += LillyPath.tail->number;
LillyPath.eraseAtTail();
}
LillyPath.addAtTail("white", sumPrev);
} else if (color == "blue") {
int maxPrev(INT_MIN);
for (j = 0; j < number; ++j) {
if (LillyPath.tail->number > maxPrev)
maxPrev = LillyPath.tail->number;
LillyPath.eraseAtTail();
}
LillyPath.addAtTail("white", maxPrev);
}
}
}
cout << "~Lilly's path after her walk:\n";
return cout << LillyPath, 0;
}
Stone::Stone(string color, int number, Stone *prev, Stone *next) {
this->color = color;
this->number = number;
this->prev = prev;
this->next = next;
}
Path::Path() {
head = tail = nullptr;
}
Stone *Path::getNewNode(string color, int number) {
Stone *newNode = new Stone(color, number);
return newNode;
}
void Path::addAtTail(string color, int number) {
Stone *newNode = getNewNode(color, number);
++size;
if (head == nullptr)
head = tail = newNode;
else {
Stone *temp = tail;
tail = newNode;
newNode->prev = temp;
temp->next = tail;
tail = temp->next;
}
}
bool Path::eraseAtTail() {
if (head == nullptr) {
cout << "cannot perform erase - path is empty\n";
return false;
} else if (head->next == nullptr) {
delete head;
head = tail = nullptr;
--size;
return true;
} else {
tail = tail->prev;
delete tail->next;
tail->next = nullptr;
--size;
return true;
}
}
ostream &operator<<(ostream &os, const Path &path) {
Stone *traversal = path.head;
if (traversal == nullptr)
os << "path is empty\n";
else {
while (traversal != nullptr) {
os << traversal->color << ' ' << traversal->number << '\n';
traversal = traversal->next;
}
}
return os;
}
|
#include "LogManager.h"
#include <iostream>
LogManager::LogManager()
{
m_flag = NULL_AIM;
}
void LogManager::Init(std::string &logFileName)
{
this->m_logFile = logFileName;
if (m_logFile.empty())
{
m_flag = CONSOLE;
}
else
{
m_flag = FILE;
// TODO: file opening
}
}
void LogManager::SetFlag(LogManager::LogFlag flag) {
}
void LogManager::WriteLog(std::string tag, std::string str)
{
switch (this->m_flag)
{
case FILE:
break;
case CONSOLE:
std::cerr << tag << ": " << str << std::endl;
break;
case NULL_AIM:
default:
std::cerr << "Logger" << ": " << "aim not defined" << std::endl;
break;
}
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <dshow.h>
#include "qedit.h" // for SampleGrabber
#include <Windows.h>
#include <atlconv.h>
#include <Wincodec.h>
#include <stdio.h>
#include <fstream>
#include <vector>
#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "Windowscodecs.lib")
using namespace std;
static char * ConvertWCtoC(wchar_t* str)
{
//반환할 char* 변수 선언
char* pStr;
//입력받은 wchar_t 변수의 길이를 구함
int strSize = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
//char* 메모리 할당
pStr = new char[strSize];
//형 변환
WideCharToMultiByte(CP_ACP, 0, str, -1, pStr, strSize, 0, 0);
return pStr;
}
int cam_enum() {
// Enumerator
IMoniker* pMoniker = NULL;
ICreateDevEnum *pDevEnum = NULL;
IEnumMoniker *pEnum = NULL;
HRESULT hr;
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
// create enumerator
hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum, (void **)&pDevEnum);
hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0);
// Cam Enumerator
if (SUCCEEDED(hr)) {
ULONG cFetched;
int num = 1;
while (pEnum->Next(1, &pMoniker, &cFetched) == S_OK)
{
IPropertyBag *pPropBag;
hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
(void **)&pPropBag);
if (SUCCEEDED(hr))
{
// To retrieve the filter's friendly name, do the following:
VARIANT varName;
VariantInit(&varName);
hr = pPropBag->Read(L"FriendlyName", &varName, 0);
if (SUCCEEDED(hr))
{
// Display the name in your UI somehow.
//printf("%d : %S\n", num, varName.bstrVal);
char* name = ConvertWCtoC(varName.bstrVal);
printf("%d : %s ", num, name);
delete[] name;
VariantClear(&varName);
/*++num;*/
}
//To create an instance of the filter, do the following:
IBaseFilter *pSrc;
hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter,
(void**)&pSrc);
}
pMoniker->Release();
pPropBag->Release();
}
pEnum->Release();
pDevEnum->Release();
}
return 0;
}
|
#include <iostream>
#include "Engine/game.h"
int main()
{
std::cout << "Controls: X = SHOW / HIDE MENU, Y = CHANGE SIMULATION SPEED\n\n";
Game app({640, 480}, "WireWorld");
while(!app.getWindow()->IsDone())
{
app.HandleInput();
app.Update();
app.Render();
app.RestartClock();
}
return 0;
}
|
#ifndef BUW_LIST_HPP
#define BUW_LIST_HPP
#include <cstddef>
#include <utility>
template <typename T>
class List;
template <typename T>
struct ListNode
{
ListNode() : m_value {}, m_prev {nullptr}, m_next {nullptr} {}
ListNode(T const& v, ListNode* prev, ListNode* next) :
m_value{v}, m_prev{prev}, m_next{next} {}
T m_value;
ListNode* m_prev;
ListNode* m_next;
};
template <typename T>
struct ListIterator
{
typedef ListIterator<T> Self;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef ptrdiff_t difference_type;
typedef std::forward_iterator_tag iterator_category;
friend class List<T>;
ListIterator() : m_node {nullptr} {}
ListIterator(ListNode<T>* n) : m_node {n} {}
reference operator * () const {
return m_node -> m_value;
}
pointer operator -> () const {
return &(m_node -> m_value);
}
Self& operator ++ () {
if (m_node) {
m_node = m_node -> m_next;
}
return *this;
}
Self& operator--()
{
m_node = m_node->m_prev;
return *this;
}
Self operator ++ (int) {
Self temp = *this;
++(*this);
return temp;
}
bool operator == (const Self& x) const {
return m_node == x.m_node;
}
bool operator != (const Self& x) const {
return m_node != x.m_node;
}
Self next() const {
if (m_node)
return ListIterator(m_node -> m_next);
else
return ListIterator(nullptr);
}
Self prev() const {
if (m_node)
return ListIterator(m_node -> m_prev);
else
return ListIterator(nullptr);
}
private:
ListNode<T>* m_node = nullptr;
};
template <typename T>
struct ListConstIterator {
friend class List<T>;
private:
ListNode<T>* m_node = nullptr;
};
template <typename T>
class List {
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef ListIterator<T> iterator;
typedef ListConstIterator<T> const_iterator;
friend class ListIterator<T>;
friend class ListConstIterator<T>;
List(): m_size {0}, m_first {nullptr}, m_last {nullptr} {}
List(List<T> const& listC): m_size {0}, m_first {nullptr}, m_last {nullptr} {
for (iterator i = listC.begin(); i != listC.end(); ++i) {
push_back(*i);
}
}
List(List&& listM): m_size {listM.m_size}, m_first {listM.m_first}, m_last {listM.m_last} { // steals list elements from listM
listM.m_size = 0;
listM.m_first = nullptr;
listM.m_last = nullptr;
}
List<T>& operator = (List<T> list) {
swap(list);
return *this;
}
void swap(List<T>& list) {
std::swap(m_size, list.m_size);
std::swap(m_first, list.m_first);
std::swap(m_last, list.m_last);
}
friend void swap(List<T>& l1, List<T>& l2) {
l1.swap(l2);
}
~List() {
clear();
}
bool empty() const {
return m_size == 0;
}
std::size_t size() const {
return m_size;
}
T const& front() const {
return (*m_first).m_value;
}
T& front() {
return (*m_first).m_value;
}
void push_front(T const& a) {
if (m_size == 0) {
m_first = new ListNode<T>{a, nullptr, nullptr};
m_last = m_first;
}
else if (m_size >= 1) {
m_first = new ListNode<T>{a, nullptr, m_first};
m_first -> m_next -> m_prev = m_first;
}
++m_size;
}
void pop_front() {
if (m_size == 1) {
assert(m_first != nullptr);
delete m_first;
m_first = nullptr;
m_size = 0;
}
else if (m_size > 1) {
assert(m_first != nullptr);
delete m_first;
m_first = m_first -> m_next;
--m_size;
}
}
T const& last() const {
return (*m_last).m_value;
}
T& last() {
return (*m_last).m_value;
}
void push_back(T const& a) {
if (m_size == 0) {
m_last = new ListNode<T>{a, nullptr, nullptr};
m_first = m_last;
}
else if (m_size >= 1) {
m_last = new ListNode<T>{a, m_last, nullptr};
m_last -> m_prev -> m_next = m_last;
}
++m_size;
}
void pop_back() {
if (m_size == 1) {
assert(m_last != nullptr);
delete m_last;
m_last = nullptr;
m_size = 0;
}
else if (m_size > 1) {
assert(m_last != nullptr);
delete m_last;
m_last = m_last -> m_prev;
--m_size;
}
}
void clear() {
while (m_size > 0) {
pop_front();
}
}
iterator begin() const {
return iterator {m_first};
}
iterator end() const {
return iterator {};
}
void insert(iterator pos, T const& value) {
if (pos == begin()) {
push_front(value);
}
else if (pos == end()) {
push_back(value);
}
else {
ListNode <T>* insertNode = new ListNode<T> {value, pos.prev().m_node, pos.m_node};
pos.prev().m_node -> m_next = insertNode;
pos.m_node -> m_prev = insertNode;
++m_size;
}
}
void reverse() {
List<T> tmp{*this};
clear();
for (iterator it = tmp.begin(); it != tmp.end(); ++it) {
push_front(*it);
}
}
private:
std::size_t m_size = 0;
ListNode<T>* m_first = nullptr;
ListNode<T>* m_last = nullptr;
};
template<typename T>
bool operator == (List<T> const& xs, List<T> const& ys) {
bool result = true;
if (xs.size() != ys.size()) {
result = false;
}
else {
std::cout << "SIZE CONFIRMED. START SCANNING."<<"\n";
ListIterator<T> xs_it = xs.begin();
ListIterator<T> ys_it = ys.begin();
while (xs_it != xs.end() && ys_it != ys.end()) {
std::cout << *ys_it <<" " << *xs_it << "\n";
if (*xs_it != *ys_it) {
result = false;
break;
}
++xs_it;
++ys_it;
}
}
return result;
}
template<typename T>
bool operator != (List<T> const& xs, List<T> const& ys) {
return !(xs == ys);
}
template<typename T>
List<T> reverse (List<T> revList) {
revList.reverse();
return revList;
}
#endif // #define BUW_LIST_HPP
|
/*
* Shape.cpp
*
*/
#include "Shape.h"
namespace rt {} // namespace rt
|
#ifndef _BFS_H_INCLUDED
#define _BFS_H_INCLUDED
#include <cstring>
#include <iostream>
#include <queue>
#include <GL/glut.h>
#include <deque>
#include "../GameManager.h"
// Check if it is possible to go to (x, y) from current position. The
// function returns false if the cell has value 0 or already visited
bool isSafe(int** mat, int visited[rows][rows], int x, int y);
// if not a valid position, return false
bool isValidS(int x, int y);
int findShortestPath(int** mat, int visited[rows][rows], int i, int j,
int x, int y, int& min_dist, int dist);
#endif
|
int Led = 13; // LED on Arduino board
int Shock = 3; // sensor signal
int val; // numeric variable to store sensor status
void setup()
{
pinMode(Led, OUTPUT); // define LED as output interface
pinMode(Shock, INPUT); // define input for sensor signal
}
void loop()
{
val = digitalRead(Shock); // read and assign the value of digital interface 3 to val
if (val == HIGH) // when sensor detects a signal, the LED flashes
{
digitalWrite(Led, LOW);
}
else
{
digitalWrite(Led, HIGH);
}
}
|
#include <iostream>
#include <iomanip>
#include <windows.h>
#include <stdio.h>
using namespace std;
int g = 0, k = 0, range = 0, counte = 0;
char** mass1 = new char* [5];
char** mass2 = new char* [5];
char** mass3 = new char* [5];
void prog1(char **massi, ...)
{
char ***mass = &massi;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
int l;
for (int i = 0; i < counte; i++)
{
for (l = 0; l < 5; l++)
{
for (int j = l + 1; j < 5; j++)
if (strcmp(mass[i][l], mass[i][j]) > 0)
{
char *tmp = mass[i][l];
mass[i][l] = mass[i][j];
mass[i][j] = tmp;
}
}
printf("Слова в алфавитном порядке:\n");
for (int k = 0; k < 5; k++)
{
cout << k << "." << mass[i][k] << endl;
}
printf("\n");
}
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
printf("Введите слова в первый массив:\n");
for (int i = 0; i < 5; i++)
{
mass1[i] = new char[20];
cin >> mass1[i];
}
counte++;
printf("Введите слова во второй массив:\n");
for (int i = 0; i < 5; i++)
{
mass2[i] = new char[20];
cin >> mass2[i];
}
counte++;
printf("Введите слова в третий массив:\n");
for (int i = 0; i < 5; i++)
{
mass3[i] = new char[20];
cin >> mass3[i];
}
counte++;
prog1(mass1,mass2,mass3,counte);
delete[] mass1;
delete[] mass2;
char** mass1 = new char* [5];
char** mass2 = new char* [5];
counte = 0;
printf("Введите слова в первый массив:\n");
for (int i = 0; i < 5; i++)
{
mass1[i] = new char[20];
cin >> mass1[i];
}
counte++;
printf("Введите слова во второй массив:\n");
for (int i = 0; i < 5; i++)
{
mass2[i] = new char[20];
cin >> mass2[i];
}
counte++;
prog1(mass1, mass2, counte);
return 0;
}
|
//
// hwGLLight.cpp
// HamsterWheel
//
// Created by OilyFing3r on 2014. 9. 2..
// Copyright (c) 2014년 OilyFing3rWorks. All rights reserved.
//
#include "hwGLLight.h"
const glm::vec4 & GLLight::getPosition (void) const { return position; }
const glm::vec4 & GLLight::getAmbient (void) const { return ambient; }
const glm::vec4 & GLLight::getDiffuse (void) const { return diffuse; }
const glm::vec4 & GLLight::getSpecular (void) const { return specular; }
const glm::vec3 & GLLight::getDirection (void) const { return direction; }
GLfloat GLLight::getCutoff (void) const { return cutoff; }
GLfloat GLLight::getExponent (void) const { return exponent; }
void GLLight::setPosition(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
position.x = x;
position.y = y;
position.z = z;
position.w = w;
}
void GLLight::setAmbient(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
{
ambient.x = r;
ambient.y = g;
ambient.z = b;
ambient.w = a;
}
void GLLight::setDiffuse(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
{
diffuse.x = r;
diffuse.y = g;
diffuse.z = b;
diffuse.w = a;
}
void GLLight::setSpecular(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
{
specular.x = r;
specular.y = g;
specular.z = b;
specular.w = a;
}
void GLLight::setDirection(GLfloat x, GLfloat y, GLfloat z)
{
direction.x = x;
direction.y = y;
direction.z = z;
glm::normalize(direction); // 수정?
}
void GLLight::setCutoff(GLfloat cutoff)
{
this->cutoff = cutoff;
}
void GLLight::setExponent(GLfloat exponent)
{
this->exponent = exponent;
}
|
#define TYPE_WHEEL 0x02
#define TYPE_DOOR 0x04
#define TYPE_BUMPER 0x06
bool saving = 0, opening = 0;
void savescene(){
saving = 1;
SDL_WM_SetCaption("SAVING FILE...",NULL);
int ib;//integer buffer
float fb;//float buffer
//creating file
std::ofstream file_out("models/out.hmdl");
file_out.close();
std::fstream scene("models/out.hmdl",std::ios::binary|std::ios::in|std::ios::out);
//writing version
ib = 204;
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
//writing numbers of
//points
ib = np;
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
//lines
ib = nl;
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
//meshes
ib = nm;
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
//printing points
for(int i=0;i<np;i++){
fb = p[i].c.x;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = p[i].c.y;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = p[i].c.z;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
}
//printing lines
for(int i=0;i<nl;i++){
ib = l[i].p[0];
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
ib = l[i].p[1];
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
}
//printing meshes
for(int i=0;i<nm;i++){
ib = m[i].p[0];
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
ib = m[i].p[1];
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
ib = m[i].p[2];
scene.write(reinterpret_cast<char*>(&ib),sizeof(int));
//normals
fb = m[i].n[0].x;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[0].y;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[0].z;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[1].x;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[1].y;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[1].z;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[2].x;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[2].y;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].n[2].z;
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
//texture
fb = m[i].tx[0];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].ty[0];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].tx[1];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].ty[1];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].tx[2];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
fb = m[i].ty[2];
scene.write(reinterpret_cast<char*>(&fb),sizeof(float));
}
//closing file
scene.close();
saving = 0;
SDL_WM_SetCaption("SAVED!",NULL);
}
void openscene(){
opening = 1;
SDL_WM_SetCaption("OPENING FILE...",NULL);
int ib;//integer buffer
float fb;//float buffer
//opening file
std::fstream scene("models/in.hmdl",std::ios::binary|std::ios::in|std::ios::out);
removeall();
//reading version
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
if(ib != 204){SDL_WM_SetCaption("FAILED! UNKNOWN VERSION!",NULL);return;}
//reading numbers of
//points
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
np = ib;
p = new point[np];
//lines
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
nl = ib;
l = new line[nl];
//meshes
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
nm = ib;
m = new mesh[nm];
//printing points
for(int i=0;i<np;i++){
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
p[i].c.x = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
p[i].c.y = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
p[i].c.z = fb;
}
//printing lines
for(int i=0;i<nl;i++){
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
l[i].p[0] = ib;
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
l[i].p[1] = ib;
}
//printing meshes
for(int i=0;i<nm;i++){
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
m[i].p[0] = ib;
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
m[i].p[1] = ib;
scene.read(reinterpret_cast<char*>(&ib),sizeof(int));
m[i].p[2] = ib;
//normals
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[0].x = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[0].y = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[0].z = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[1].x = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[1].y = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[1].z = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[2].x = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[2].y = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].n[2].z = fb;
//texture
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].tx[0] = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].ty[0] = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].tx[1] = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].ty[1] = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].tx[2] = fb;
scene.read(reinterpret_cast<char*>(&fb),sizeof(float));
m[i].ty[2] = fb;
}
//closing file
scene.close();
opening = 0;
SDL_WM_SetCaption("OPENED!",NULL);
}
|
#include <list>
#include <map>
#include <stack>
#include <stdlib.h>
using namespace std;
int* condense(list<int> * cg_stripped, int count, int &SCC_count);
|
//$Id$
//------------------------------------------------------------------------------
// TestAbsoluteDate
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Author: Wendy Shoan
// Created: 2016.05.11
//
/**
* Unit-test driver for the AbsoluteDate
*/
//------------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <ctime>
#include <cmath>
#include "gmatdefs.hpp"
#include "GmatConstants.hpp"
#include "Rvector6.hpp"
#include "RealUtilities.hpp"
#include "MessageInterface.hpp"
#include "ConsoleMessageReceiver.hpp"
#include "AbsoluteDate.hpp"
#include "TimeTypes.hpp"
using namespace std;
//------------------------------------------------------------------------------
// int main(int argc, char *argv[])
//------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
std::string outFormat = "%16.9f ";
Real tolerance = 1e-15;
ConsoleMessageReceiver *consoleMsg = ConsoleMessageReceiver::Instance();
MessageInterface::SetMessageReceiver(consoleMsg);
std::string outPath = "./";
MessageInterface::SetLogFile(outPath + "GmatLog.txt");
MessageInterface::ShowMessage("%s\n",
GmatTimeUtil::FormatCurrentTime().c_str());
// Set global format setting
GmatGlobal *global = GmatGlobal::Instance();
global->SetActualFormat(false, false, 16, 1, false);
char *buffer = NULL;
buffer = getenv("OS");
if (buffer != NULL)
{
MessageInterface::ShowMessage("Current OS is %s\n", buffer);
}
else
{
MessageInterface::ShowMessage("Buffer is NULL\n");
}
MessageInterface::ShowMessage("*** START TEST ***\n");
try
{
// Test the AbsoluteDate
MessageInterface::ShowMessage("*** TEST*** AbsoluteDate\n");
// Create the AbsoluteDate
AbsoluteDate date;
// Set the Gregorian date and test conversion to Julian Date
date.SetGregorianDate(2017, 1, 15, 22, 30, 20.111);
Real jd = date.GetJulianDate();
Real truthDate = 27769.4377327662 + 2430000;
if (GmatMathUtil::IsEqual(truthDate, jd))
MessageInterface::ShowMessage("OK - gregorian to julian date is correct!!\n");
else
MessageInterface::ShowMessage("*** ERROR - julian date is incorrect!!\n");
// Set the julian date and test conversion to Gregorian date
date.SetJulianDate(2457269.123456789);
Rvector6 greg = date.GetGregorianDate();
Integer yr = 2015;
Integer mon = 9;
Integer day = 3;
Integer hr = 14;
Integer min = 57;
Real sec = 46.6665852069856;
bool gregOK = true;
if ((Integer) greg[0] != yr)
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (year) is incorrect!!\n");
}
if ((Integer) greg[1] != mon)
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (month) is incorrect!!\n");
}
if ((Integer) greg[2] != day)
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (day) is incorrect!!\n");
}
if ((Integer) greg[3] != hr)
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (hour) (%d) is incorrect!!\n",
greg[3]);
}
if ((Integer) greg[4] != min)
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (minute) (%d) is incorrect!!\n",
greg[4]);
}
if (!GmatMathUtil::IsEqual(sec, greg[5], 1.0e-13))
{
gregOK = false;
MessageInterface::ShowMessage("*** ERROR - gregorian (second) (%16.14f) (%16.14f) is incorrect!!\n",
greg[5], sec);
}
if (gregOK)
MessageInterface::ShowMessage("OK - julian to gregorian date is correct!!\n");
cout << endl;
cout << "Hit enter to end" << endl;
cin.get();
MessageInterface::ShowMessage("*** END TEST ***\n");
}
catch (BaseException &be)
{
MessageInterface::ShowMessage("Exception caught: %s\n", be.GetFullMessage().c_str());
}
}
|
class Solution {
public:
int pivotIx(vector<int>& dict, int s, int e, int pivot){
/*
return the first index larger than pivot
smaller on the left and larger on the right
*/
int i = s, j = e-1;
while (i <= j){
if (dict[i] < pivot){
i += 1;
} else {
int temp = dict[i];
dict[i] = dict[j];
dict[j] = temp;
j -= 1;
}
}
return i;
}
int findKthSmallest(vector<int>& dict, int s, int e, int k){
if (e-s == 1){
return dict[s];
} else if (e-s == 2){
return (k==1) ? min(dict[s], dict[e-1]): max(dict[s], dict[e-1]);
} else {
int mid = (s+2*(e-1))/3;
int ix = pivotIx(dict, s, e, dict[mid]);
if (ix < s+k){
return findKthSmallest(dict, ix, e, k-(ix-s));
} else {
return findKthSmallest(dict, s, ix, k);
}
}
}
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
vector<int> dist;
int n = points.size();
if (K == n){
return points;
}
vector<vector<int>> res;
for (int i=0; i<n; i++){
vector<int> point = points[i];
dist.push_back( point[0]*point[0] + point[1]*point[1] );
}
int pivot = findKthSmallest(dist, 0, n, K);
for (int i=0; i<n; i++){
if (points[i][0]*points[i][0] + points[i][1]*points[i][1] <= pivot){
res.push_back( points[i] );
}
}
return res;
}
};
|
// $Id: UnaryExpression.h,v 1.9 2013/02/09 19:00:34 david Exp $ -*- c++ -*-
#ifndef __CDK8_NODE_EXPRESSION_UNARYEXPRESSION_H__
#define __CDK8_NODE_EXPRESSION_UNARYEXPRESSION_H__
#include <cdk/nodes/expressions/Expression.h>
#include "SemanticProcessor.h"
namespace cdk {
namespace node {
namespace expression {
//!
//! Class for describing unary operators.
//!
class UnaryExpression: public Expression {
Expression *_argument;
public:
inline UnaryExpression(int lineno, Expression *arg) :
Expression(lineno), _argument(arg) {
}
inline Expression *argument() {
return _argument;
}
};
} // expression
} // node
} // cdk
#endif
// $Log: UnaryExpression.h,v $
// Revision 1.9 2013/02/09 19:00:34 david
// First CDK8 commit. Major code simplification.
// Starting C++11 implementation.
//
// Revision 1.8 2012/04/10 19:01:05 david
// Removed initialization-dependent static members in factories.
// Handling of ProgramNodes is now better encapsulated by visitors (not done
// by evaluators, as before). Major cleanup (comments).
//
// Revision 1.7 2012/03/06 15:07:45 david
// Added subtype to ExpressionType. This allows for more expressiveness in
// type description.
//
|
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
int N,M; ll S;
ll MAX_S = 2505;
struct edge {
int to;
ll cost, t;
edge(int to, ll cost, ll t):to(to), cost(cost), t(t) {}
};
struct Data {
int v; ll s;
ll x;
Data(int v, ll s, ll x): v(v), s(s), x(x) {}
bool operator<(const Data& a) const {
return x > a.x;
}
};
int main() {
cin >> N>>M>>S;
vector<ll> c(N);
vector<ll> d(N);
vector<vector<edge>> g(N, vector<edge>());
rep(i,M) {
int u,v; ll a,b; cin>>u>>v>>a>>b;
u--;v--;
g[u].emplace_back(v,a,b);
g[v].emplace_back(u,a,b);
// g[u].push_back(edge{v,a,b});
// g[v].push_back(edge{u,a,b});
}
rep(i, N) {
cin >> c[i] >> d[i];
}
S = min(S, MAX_S);
priority_queue<Data> q;
vector<vector<ll>> dp(N, vector<ll>(MAX_S+5, LINF));
auto push = [&] (int v, ll s, ll x) {
if (s<0) return;
// if (s>MAX_S) return ;
if (dp[v][s] <= x) return ;
dp[v][s] = x;
// Data foo = Data(v,s,x);
// q.push(Data{v,s,x});
q.emplace(v,s,x);
// q.push(foo);
};
push(0,S,0);
while(q.size()) {
Data foo = q.top(); q.pop();
int v = foo.v;
S=foo.s;
ll x = foo.x;
if (dp[v][S] != x) continue;
ll ns = min(S+c[v], MAX_S);
push(v, ns , x+d[v]);
rep(i, g[v].size()) {
edge e = g[v][i];
int nv = e.to;
push(nv, S-e.cost, x+e.t);
}
}
for (int i=1; i<dp.size();i++) {
ll ans = LINF;
rep(j, dp[i].size()) {
ans = min(ans, dp[i][j]);
}
cout << ans << endl;
}
return 0;
}
|
//
// Created by artim on 15.06.2020.
//
#include "Server.h"
#include "Client.h"
#include <smmintrin.h>
#include <iostream>
using std::cout;
Server::Server() :
listeningThread(this),
receiveThread(this)
{
this->socket.bind(5000);
this->exit_flag = true;
listeningThread.init_passed = true;
receiveThread.init_passed = true;
listeningThread.detach();
receiveThread.detach();
}
void Server::close()
{
list_mutex.lock();
exit_flag = false;
list_mutex.unlock();
Client mock_client("127.0.0.1"); // to unlock listening thread
while(listeningThread.is_running) {
cout << "await stop of listening thread" << std::endl;
cout.flush();
}
while(receiveThread.is_running) {
cout << "await stop of receiving thread" << std::endl;
cout.flush();
}
}
void Server::ListeningThread::run()
{
while(!init_passed);
while(parentServer->exit_flag)
{
parentServer->socket.listen();
Socket * client = parentServer->socket.accept();
cout << "launched";
parentServer->list_mutex.lock();
if (!parentServer->exit_flag)
{
is_running = false;
parentServer->list_mutex.unlock();
return;
}
parentServer->sockets.push_front(client);
parentServer->messages.push_front(Message());
parentServer->list_mutex.unlock();
}
is_running = false;
}
Server::ListeningThread::ListeningThread(Server *parent)
: init_passed(false), thread(&Server::ListeningThread::run, this), is_running(true)
{
this->parentServer = parent;
}
void Server::SendReceiveThread::run()
{
while(!init_passed);
while(parentServer->exit_flag)
{
parentServer->list_mutex.lock();
if (!parentServer->exit_flag) {
is_running = false;
parentServer->list_mutex.unlock();
return;
}
auto clientPtr = parentServer->sockets.begin();
auto messagePtr = parentServer->messages.begin();
for(;messagePtr != parentServer->messages.end(); clientPtr++, messagePtr++)
{
if ((*clientPtr)->receive(reinterpret_cast<char*>(&*messagePtr),
sizeof(Message)) == -1)
{
messagePtr->call = false;
messagePtr->sending = false;
messagePtr->disconnect = true;
messagePtr->frequency = -1;
}
}
clientPtr = parentServer->sockets.begin();
messagePtr = parentServer->messages.begin();
for(;messagePtr != parentServer->messages.end(); clientPtr++, messagePtr++)
{
if(!messagePtr->sending && !messagePtr->disconnect)
{
memset(messagePtr->audio_data, '\0', MESSAGE_SIZE);
for (auto &message : parentServer->messages)
{
if (message.sending && !message.disconnect &&
message.frequency == messagePtr->frequency)
{
/*
for (int i = 0; i < MESSAGE_SIZE / 8; i++)
{
reinterpret_cast<long long *>(messagePtr->audio_data)[i] +=
reinterpret_cast<long long *>(message.audio_data)[i];
}
*/
auto* destiny = reinterpret_cast<__m128i*>(messagePtr->audio_data);
auto* source = reinterpret_cast<__m128i*>(message.audio_data);
for (int i = 0; i < MESSAGE_SIZE / 16; i++)
{
destiny[i] = _mm_hadd_epi32(destiny[i], source[i]);
}
if (message.call)
messagePtr->call = true;
}
}
}
}
clientPtr = parentServer->sockets.begin();
messagePtr = parentServer->messages.begin();
for(;messagePtr != parentServer->messages.end(); clientPtr++, messagePtr++)
{
if(messagePtr->disconnect)
{
cout << "disconnect";
parentServer->messages.remove(*messagePtr);
parentServer->sockets.remove(*clientPtr);
messagePtr = parentServer->messages.begin();
clientPtr = parentServer->sockets.begin();
}
}
clientPtr = parentServer->sockets.begin();
messagePtr = parentServer->messages.begin();
for(;messagePtr != parentServer->messages.end(); clientPtr++, messagePtr++)
{
(*clientPtr)->send(reinterpret_cast<char*>(&*messagePtr), sizeof(Message));
}
parentServer->list_mutex.unlock();
}
is_running = false;
}
Server::SendReceiveThread::SendReceiveThread(Server *parent)
: init_passed(false), std::thread(&Server::SendReceiveThread::run, this), is_running(true)
{
this->parentServer = parent;
}
|
#include "Line.h"
Line::Line() :
origin(Vector2D(0, 0)),
destiny(Vector2D(0, 0))
{
CalculateVectorArrows();
setColor(255, 255, 255);
}
Line::Line(const Vector2D& orig, const Vector2D& dest) :
origin(orig),
destiny(dest)
{
setColor(255, 255, 255);
CalculateVectorArrows();
}
Line::~Line() {}
void Line::CalculateVectorArrows() {
Vector2D pointDifference = destiny - origin;
if (pointDifference.x == 0 && pointDifference.y == 0) {
pointDifference.x = 0.01f;
}
float arrowsAngle = 30;
float angle = atan(pointDifference.y / pointDifference.x);
if (destiny.x >= origin.x) {
vectorArrowRight.x = cos(angle - (180 - arrowsAngle) * DEG2RAD) * 20 + destiny.x;
vectorArrowRight.y = sin(angle - (180 - arrowsAngle) * DEG2RAD) * 20 + destiny.y;
vectorArrowLeft.x = cos(angle + (180 - arrowsAngle) * DEG2RAD) * 20 + destiny.x;
vectorArrowLeft.y = sin(angle + (180 - arrowsAngle) * DEG2RAD) * 20 + destiny.y;
}
else {
vectorArrowRight.x = cos(angle + arrowsAngle * DEG2RAD) * 20 + destiny.x;
vectorArrowRight.y = sin(angle + arrowsAngle * DEG2RAD) * 20 + destiny.y;
vectorArrowLeft.x = cos(angle - arrowsAngle * DEG2RAD) * 20 + destiny.x;
vectorArrowLeft.y = sin(angle - arrowsAngle * DEG2RAD) * 20 + destiny.y;
}
}
void Line::drawLine() {
SDL_SetRenderDrawColor(TheApp::Instance()->getRenderer(), red, green, blue, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(TheApp::Instance()->getRenderer(), origin.x, origin.y, destiny.x, destiny.y);
}
void Line::drawVector() {
SDL_SetRenderDrawColor(TheApp::Instance()->getRenderer(), red, green, blue, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(TheApp::Instance()->getRenderer(), origin.x, origin.y, destiny.x, destiny.y);
SDL_RenderDrawLine(TheApp::Instance()->getRenderer(), destiny.x, destiny.y, vectorArrowRight.x, vectorArrowRight.y);
SDL_RenderDrawLine(TheApp::Instance()->getRenderer(), destiny.x, destiny.y, vectorArrowLeft.x, vectorArrowLeft.y);
}
|
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string curstr = "";
genpar(n, 0, 0, result, curstr);
return result;
}
void genpar(int n, int left, int right, vector<string>& result, string curstr) {
if(left == n) {
int diff = n - right;
for(int i=0; i < diff; i++) curstr += ")";
result.push_back(curstr); return;
}
if(left == right) {
curstr += "(";
genpar(n, left + 1, right, result, curstr); return;
}
genpar(n, left + 1, right, result, curstr + "(");
genpar(n, left, right + 1, result, curstr + ")");
return;
}
};
|
#include "Array.hpp"
template<typename T>
Array<T>::Array():
_length(0), _array(nullptr)
{}
template<typename T>
Array<T>::Array(unsigned int n):
_length(n)
{
this->_array = new T[n]();
}
template<typename T>
Array<T>::Array(const Array& copy):
_length(copy._length)
{
if (copy._length > 0)
{
this->_array = new T[copy._length]();
for (int i = 0; i < (int)copy._length; i++)
this->_array[i] = copy._array[i];
}
}
template<typename T>
Array<T>::~Array()
{
if (this->_length > 0)
delete[] this->_array;
}
template<typename T>
Array<T> &Array<T>::operator=(Array<T> const &op)
{
if (this->_length > 0)
delete[] this->_array;
this->_array = nullptr;
if (op._length > 0)
{
this->_array = new T[op._length]();
for (int i = 0; i < op._length; i++)
this->_array[i] = op._array[i];
}
this->_length = op._length;
return (*this);
}
template<typename T>
T &Array<T>::operator[](unsigned int index)
{
if (index >= this->_length)
throw Array::OutOfBoundsException();
return (this->_array[index]);
}
template<typename T>
T const &Array<T>::operator[](unsigned int index) const
{
return (operator[](index));
}
template<typename T>
unsigned int Array<T>::size(void) const
{
return (this->_length);
}
template<typename T>
const char* Array<T>::OutOfBoundsException::what() const throw()
{
return "Exception: index error";
}
|
#ifndef DIALOGSAVEAS_H
#define DIALOGSAVEAS_H
#include <QDialog>
namespace Ui {
class dialogsaveas;
}
class dialogsaveas : public QDialog
{
Q_OBJECT
public:
explicit dialogsaveas(QWidget *parent = 0);
~dialogsaveas();
private slots:
void on_buttonBox_accepted();
private:
Ui::dialogsaveas *ui;
};
#endif // DIALOGSAVEAS_H
|
#pragma once
#include<string>
using namespace std;
class Fahrzeug
{
public:
Fahrzeug();
Fahrzeug(string namestr);
Fahrzeug(string namestr, double MaxGeschwindigkeit);
Fahrzeug(const Fahrzeug& fahrzeug);
virtual ~Fahrzeug();
void virtual vostreamAusgabe(ostream &out);
void virtual vAusgabe();
void virtual vAbfertigung();
double virtual dTanken(double menge);
bool operator<(const Fahrzeug& comp);
Fahrzeug& operator=(const Fahrzeug& cpyfahrzeug);
private:
static int p_iMaxID;
protected:
int p_iID;
string p_sName;
double p_dMaxGeschwindigkeit;
double p_dGesamtStrecke;
double p_dGesamtZeit;
double p_dZeit;
double p_dGeschwindigkeit;
void vInitialisierung();
};
ostream& operator <<(ostream& out, Fahrzeug&fahrzeug);
|
#ifndef VIEWERS_EMPTY_VIEWER_HEADER
#define VIEWERS_EMPTY_VIEWER_HEADER
#include "Viewer.h"
namespace solar
{
//Does nothing
class EmptyViewer :public Viewer
{
public:
void operator()() override final {}
};
}
#endif
|
//
// document_collection.cpp
// TextRetrieval
//
// Created by Joseph Canero on 11/15/15.
// Copyright © 2015 jcanero. All rights reserved.
//
#include "document_collection.hpp"
size_t DocumentCollection::get_avg_doc_length() {
if (shouldComputeDocLengths()) {
size_t res = accumulate(m_Documents.begin(), m_Documents.end(), 0,
[](int sum, const Document& d) {
return d.get_doc_length() + sum;
});
m_AvgDocLength = res / m_Documents.size();
}
return m_AvgDocLength;
}
void DocumentCollection::compute_freqs() {
if (shouldComputeDocFreqs()) {
map<string, bool> shouldIncrementMap;
for (const Document& d : m_Documents) {
shouldIncrementMap.clear();
for (string word : d.get_words()) {
if (shouldAddWord(shouldIncrementMap, word)) {
auto item = m_DocFreqs.find(word);
if (item == m_DocFreqs.end())
m_DocFreqs.insert(make_pair(word, 1));
else
item->second++;
shouldIncrementMap.insert(make_pair(word, false));
}
}
}
}
}
int DocumentCollection::get_doc_frequency(const string& word) {
if (shouldComputeDocFreqs())
compute_freqs();
auto item = m_DocFreqs.find(word);
return item != m_DocFreqs.end() ? item->second : 0;
}
double DocumentCollection::get_idf(const string& word) {
if (shouldComputeDocFreqs())
compute_freqs();
double frequency = get_doc_frequency(word);
return frequency != 0 ?
log10((get_num_docs() + 1) / frequency) :
frequency;
}
|
#include <stdio.h>
int main(const int argc, const char* const argv[])
{
printf_s("hello");
return 0;
}
|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.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.
*/
//-----------------------------------------------------------------------------
#include "opencl_library.h"
#include "distributedcl_internal.h"
//-----------------------------------------------------------------------------
namespace dcl {
namespace single {
//-----------------------------------------------------------------------------
opencl_library::opencl_library() :
clGetPlatformIDs( NULL ),
clGetPlatformInfo( NULL ),
clGetDeviceIDs( NULL ),
clGetDeviceInfo( NULL ),
clCreateContext( NULL ),
clCreateContextFromType( NULL ),
clRetainContext( NULL ),
clReleaseContext( NULL ),
clGetContextInfo( NULL ),
clCreateCommandQueue( NULL ),
clRetainCommandQueue( NULL ),
clReleaseCommandQueue( NULL ),
clGetCommandQueueInfo( NULL ),
clSetCommandQueueProperty( NULL ),
clCreateBuffer( NULL ),
clCreateImage2D( NULL ),
clCreateImage3D( NULL ),
clRetainMemObject( NULL ),
clReleaseMemObject( NULL ),
clGetSupportedImageFormats( NULL ),
clGetMemObjectInfo( NULL ),
clGetImageInfo( NULL ),
clCreateSampler( NULL ),
clRetainSampler( NULL ),
clReleaseSampler( NULL ),
clGetSamplerInfo( NULL ),
clCreateProgramWithSource( NULL ),
clCreateProgramWithBinary( NULL ),
clRetainProgram( NULL ),
clReleaseProgram( NULL ),
clBuildProgram( NULL ),
clUnloadCompiler( NULL ),
clGetProgramInfo( NULL ),
clGetProgramBuildInfo( NULL ),
clCreateKernel( NULL ),
clCreateKernelsInProgram( NULL ),
clRetainKernel( NULL ),
clReleaseKernel( NULL ),
clSetKernelArg( NULL ),
clGetKernelInfo( NULL ),
clGetKernelWorkGroupInfo( NULL ),
clWaitForEvents( NULL ),
clGetEventInfo( NULL ),
clRetainEvent( NULL ),
clReleaseEvent( NULL ),
clGetEventProfilingInfo( NULL ),
clFlush( NULL ),
clFinish( NULL ),
clEnqueueReadBuffer( NULL ),
clEnqueueWriteBuffer( NULL ),
clEnqueueCopyBuffer( NULL ),
clEnqueueReadImage( NULL ),
clEnqueueWriteImage( NULL ),
clEnqueueCopyImage( NULL ),
clEnqueueCopyImageToBuffer( NULL ),
clEnqueueCopyBufferToImage( NULL ),
clEnqueueMapBuffer( NULL ),
clEnqueueMapImage( NULL ),
clEnqueueUnmapMemObject( NULL ),
clEnqueueNDRangeKernel( NULL ),
clEnqueueTask( NULL ),
clEnqueueNativeKernel( NULL ),
clEnqueueMarker( NULL ),
clEnqueueWaitForEvents( NULL ),
clEnqueueBarrier( NULL ),
clCreateSubBuffer( NULL ),
clCreateUserEvent( NULL ),
clEnqueueCopyBufferRect( NULL ),
clEnqueueReadBufferRect( NULL ),
clEnqueueWriteBufferRect( NULL ),
clSetEventCallback( NULL ),
clSetMemObjectDestructorCallback( NULL ),
clSetUserEventStatus( NULL ),
clLib_( NULL ),
libpath_( "" )
{
}
//-----------------------------------------------------------------------------
opencl_library::opencl_library( const opencl_library& opencl ) :
clGetPlatformIDs( NULL ),
clGetPlatformInfo( NULL ),
clGetDeviceIDs( NULL ),
clGetDeviceInfo( NULL ),
clCreateContext( NULL ),
clCreateContextFromType( NULL ),
clRetainContext( NULL ),
clReleaseContext( NULL ),
clGetContextInfo( NULL ),
clCreateCommandQueue( NULL ),
clRetainCommandQueue( NULL ),
clReleaseCommandQueue( NULL ),
clGetCommandQueueInfo( NULL ),
clSetCommandQueueProperty( NULL ),
clCreateBuffer( NULL ),
clCreateImage2D( NULL ),
clCreateImage3D( NULL ),
clRetainMemObject( NULL ),
clReleaseMemObject( NULL ),
clGetSupportedImageFormats( NULL ),
clGetMemObjectInfo( NULL ),
clGetImageInfo( NULL ),
clCreateSampler( NULL ),
clRetainSampler( NULL ),
clReleaseSampler( NULL ),
clGetSamplerInfo( NULL ),
clCreateProgramWithSource( NULL ),
clCreateProgramWithBinary( NULL ),
clRetainProgram( NULL ),
clReleaseProgram( NULL ),
clBuildProgram( NULL ),
clUnloadCompiler( NULL ),
clGetProgramInfo( NULL ),
clGetProgramBuildInfo( NULL ),
clCreateKernel( NULL ),
clCreateKernelsInProgram( NULL ),
clRetainKernel( NULL ),
clReleaseKernel( NULL ),
clSetKernelArg( NULL ),
clGetKernelInfo( NULL ),
clGetKernelWorkGroupInfo( NULL ),
clWaitForEvents( NULL ),
clGetEventInfo( NULL ),
clRetainEvent( NULL ),
clReleaseEvent( NULL ),
clGetEventProfilingInfo( NULL ),
clFlush( NULL ),
clFinish( NULL ),
clEnqueueReadBuffer( NULL ),
clEnqueueWriteBuffer( NULL ),
clEnqueueCopyBuffer( NULL ),
clEnqueueReadImage( NULL ),
clEnqueueWriteImage( NULL ),
clEnqueueCopyImage( NULL ),
clEnqueueCopyImageToBuffer( NULL ),
clEnqueueCopyBufferToImage( NULL ),
clEnqueueMapBuffer( NULL ),
clEnqueueMapImage( NULL ),
clEnqueueUnmapMemObject( NULL ),
clEnqueueNDRangeKernel( NULL ),
clEnqueueTask( NULL ),
clEnqueueNativeKernel( NULL ),
clEnqueueMarker( NULL ),
clEnqueueWaitForEvents( NULL ),
clEnqueueBarrier( NULL ),
clCreateSubBuffer( NULL ),
clCreateUserEvent( NULL ),
clEnqueueCopyBufferRect( NULL ),
clEnqueueReadBufferRect( NULL ),
clEnqueueWriteBufferRect( NULL ),
clSetEventCallback( NULL ),
clSetMemObjectDestructorCallback( NULL ),
clSetUserEventStatus( NULL ),
clLib_( NULL ),
libpath_( opencl.libpath_ )
{
load();
}
//-----------------------------------------------------------------------------
opencl_library::opencl_library( const std::string& libpath ) :
clGetPlatformIDs( NULL ),
clGetPlatformInfo( NULL ),
clGetDeviceIDs( NULL ),
clGetDeviceInfo( NULL ),
clCreateContext( NULL ),
clCreateContextFromType( NULL ),
clRetainContext( NULL ),
clReleaseContext( NULL ),
clGetContextInfo( NULL ),
clCreateCommandQueue( NULL ),
clRetainCommandQueue( NULL ),
clReleaseCommandQueue( NULL ),
clGetCommandQueueInfo( NULL ),
clSetCommandQueueProperty( NULL ),
clCreateBuffer( NULL ),
clCreateImage2D( NULL ),
clCreateImage3D( NULL ),
clRetainMemObject( NULL ),
clReleaseMemObject( NULL ),
clGetSupportedImageFormats( NULL ),
clGetMemObjectInfo( NULL ),
clGetImageInfo( NULL ),
clCreateSampler( NULL ),
clRetainSampler( NULL ),
clReleaseSampler( NULL ),
clGetSamplerInfo( NULL ),
clCreateProgramWithSource( NULL ),
clCreateProgramWithBinary( NULL ),
clRetainProgram( NULL ),
clReleaseProgram( NULL ),
clBuildProgram( NULL ),
clUnloadCompiler( NULL ),
clGetProgramInfo( NULL ),
clGetProgramBuildInfo( NULL ),
clCreateKernel( NULL ),
clCreateKernelsInProgram( NULL ),
clRetainKernel( NULL ),
clReleaseKernel( NULL ),
clSetKernelArg( NULL ),
clGetKernelInfo( NULL ),
clGetKernelWorkGroupInfo( NULL ),
clWaitForEvents( NULL ),
clGetEventInfo( NULL ),
clRetainEvent( NULL ),
clReleaseEvent( NULL ),
clGetEventProfilingInfo( NULL ),
clFlush( NULL ),
clFinish( NULL ),
clEnqueueReadBuffer( NULL ),
clEnqueueWriteBuffer( NULL ),
clEnqueueCopyBuffer( NULL ),
clEnqueueReadImage( NULL ),
clEnqueueWriteImage( NULL ),
clEnqueueCopyImage( NULL ),
clEnqueueCopyImageToBuffer( NULL ),
clEnqueueCopyBufferToImage( NULL ),
clEnqueueMapBuffer( NULL ),
clEnqueueMapImage( NULL ),
clEnqueueUnmapMemObject( NULL ),
clEnqueueNDRangeKernel( NULL ),
clEnqueueTask( NULL ),
clEnqueueNativeKernel( NULL ),
clEnqueueMarker( NULL ),
clEnqueueWaitForEvents( NULL ),
clEnqueueBarrier( NULL ),
clCreateSubBuffer( NULL ),
clCreateUserEvent( NULL ),
clEnqueueCopyBufferRect( NULL ),
clEnqueueReadBufferRect( NULL ),
clEnqueueWriteBufferRect( NULL ),
clSetEventCallback( NULL ),
clSetMemObjectDestructorCallback( NULL ),
clSetUserEventStatus( NULL ),
clLib_( NULL ),
libpath_( libpath )
{
load();
}
//-----------------------------------------------------------------------------
opencl_library::~opencl_library()
{
free();
}
//-----------------------------------------------------------------------------
#define LOAD_FUNCTION(x) x=(dcl::info::x##_t)load_function(#x)
void opencl_library::load()
{
clLib_ = LOAD_LIBRARY( libpath_.c_str() );
if( clLib_ == null_library_handle )
{
#if defined(WIN32)
throw dcl::library_exception( "LoadLibrary error", GetLastError() );
#else
throw dcl::library_exception( dlerror() );
#endif // WIN32
}
LOAD_FUNCTION(clGetPlatformIDs);
LOAD_FUNCTION(clGetPlatformInfo);
LOAD_FUNCTION(clGetDeviceIDs);
LOAD_FUNCTION(clGetDeviceInfo);
LOAD_FUNCTION(clCreateContext);
LOAD_FUNCTION(clCreateContextFromType);
LOAD_FUNCTION(clRetainContext);
LOAD_FUNCTION(clReleaseContext);
LOAD_FUNCTION(clGetContextInfo);
LOAD_FUNCTION(clCreateCommandQueue);
LOAD_FUNCTION(clRetainCommandQueue);
LOAD_FUNCTION(clReleaseCommandQueue);
LOAD_FUNCTION(clGetCommandQueueInfo);
LOAD_FUNCTION(clSetCommandQueueProperty);
LOAD_FUNCTION(clCreateBuffer);
LOAD_FUNCTION(clCreateImage2D);
LOAD_FUNCTION(clCreateImage3D);
LOAD_FUNCTION(clRetainMemObject);
LOAD_FUNCTION(clReleaseMemObject);
LOAD_FUNCTION(clGetSupportedImageFormats);
LOAD_FUNCTION(clGetMemObjectInfo);
LOAD_FUNCTION(clGetImageInfo);
LOAD_FUNCTION(clCreateSampler);
LOAD_FUNCTION(clRetainSampler);
LOAD_FUNCTION(clReleaseSampler);
LOAD_FUNCTION(clGetSamplerInfo);
LOAD_FUNCTION(clCreateProgramWithSource);
LOAD_FUNCTION(clCreateProgramWithBinary);
LOAD_FUNCTION(clRetainProgram);
LOAD_FUNCTION(clReleaseProgram);
LOAD_FUNCTION(clBuildProgram);
LOAD_FUNCTION(clUnloadCompiler);
LOAD_FUNCTION(clGetProgramInfo);
LOAD_FUNCTION(clGetProgramBuildInfo);
LOAD_FUNCTION(clCreateKernel);
LOAD_FUNCTION(clCreateKernelsInProgram);
LOAD_FUNCTION(clRetainKernel);
LOAD_FUNCTION(clReleaseKernel);
LOAD_FUNCTION(clSetKernelArg);
LOAD_FUNCTION(clGetKernelInfo);
LOAD_FUNCTION(clGetKernelWorkGroupInfo);
LOAD_FUNCTION(clWaitForEvents);
LOAD_FUNCTION(clGetEventInfo);
LOAD_FUNCTION(clRetainEvent);
LOAD_FUNCTION(clReleaseEvent);
LOAD_FUNCTION(clGetEventProfilingInfo);
LOAD_FUNCTION(clFlush);
LOAD_FUNCTION(clFinish);
LOAD_FUNCTION(clEnqueueReadBuffer);
LOAD_FUNCTION(clEnqueueWriteBuffer);
LOAD_FUNCTION(clEnqueueCopyBuffer);
LOAD_FUNCTION(clEnqueueReadImage);
LOAD_FUNCTION(clEnqueueWriteImage);
LOAD_FUNCTION(clEnqueueCopyImage);
LOAD_FUNCTION(clEnqueueCopyImageToBuffer);
LOAD_FUNCTION(clEnqueueCopyBufferToImage);
LOAD_FUNCTION(clEnqueueMapBuffer);
LOAD_FUNCTION(clEnqueueMapImage);
LOAD_FUNCTION(clEnqueueUnmapMemObject);
LOAD_FUNCTION(clEnqueueNDRangeKernel);
LOAD_FUNCTION(clEnqueueTask);
LOAD_FUNCTION(clEnqueueNativeKernel);
LOAD_FUNCTION(clEnqueueMarker);
LOAD_FUNCTION(clEnqueueWaitForEvents);
LOAD_FUNCTION(clEnqueueBarrier);
// OpenCL 1.1
//LOAD_FUNCTION(clCreateSubBuffer);
//LOAD_FUNCTION(clCreateUserEvent);
//LOAD_FUNCTION(clEnqueueCopyBufferRect);
//LOAD_FUNCTION(clEnqueueReadBufferRect);
//LOAD_FUNCTION(clEnqueueWriteBufferRect);
//LOAD_FUNCTION(clSetEventCallback);
//LOAD_FUNCTION(clSetMemObjectDestructorCallback);
//LOAD_FUNCTION(clSetUserEventStatus);
}
#undef LOAD_FUNCTION
//-----------------------------------------------------------------------------
void opencl_library::free()
{
if( clLib_ != null_library_handle )
{
FREE_LIBRARY( clLib_ );
clLib_ = null_library_handle;
}
}
//-----------------------------------------------------------------------------
#if defined(WIN32)
void* opencl_library::load_function( const char* function )
{
void* ret = GetProcAddress( clLib_, function );
if( ret == NULL )
{
throw dcl::library_exception( "GetProcAddress error", GetLastError() );
}
return( ret );
}
#else // WIN32
void* opencl_library::load_function( const char* function )
{
void *ret = dlsym( clLib_, function );
const char *error;
if( (error = dlerror()) != NULL )
{
throw dcl::library_exception( error );
}
return( ret );
}
#endif // WIN32
//-----------------------------------------------------------------------------
}} // namespace dcl::single
//-----------------------------------------------------------------------------
|
#ifndef INPUT_BUFFER_H
#define INPUT_BUFFER_H
#include "Global.h"
class InputBuffer {
public:
InputBuffer(FILE* inputFile);
int getNextBit();
ull getBunchOfBits(int howMany);
void close();
private:
ull* buffer;
int maxSize;
int size;
int curPos;
ull nextBit;
int nextBitPos;
FILE* file;
void fillBuffer();
void fillIfEmpty();
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
// refer notes
int main()
{
int t;
cin >> t;
int arr[8] = {0,1,1,2,0,2,2,1};
int sum_arr[8] = {0,1,2,4,4,6,8,9};
int sum = 9;
while(t--)
{
int n;
cin >> n;
int total = 0;
// total = previous groups sum + current fibonacci number
// to get the previous groups n/8 period in case of mod3 is 8
// after 8 fibonacci numbers starting from 0 the sequence repeats itself
total += (n/8)*sum;
// getting the current position int current groups
int cur_pos = n%8;
total += sum_arr[cur_pos];
cout << total << endl;
}
return 0;
}
|
#include <iostream>
#include "calc.h"
extern int yylex();
extern int yylineno;
extern char* yytext;
int main(void)
{
int ntoken;
ntoken = yylex();
while(ntoken)
{
printf("\nToken : %d Value : %s Line : %d",ntoken,yytext,yylineno);
ntoken = yylex();
}
/*while(ntoken)
{
printf("\nToken : %d",ntoken);
if(ntoken == KEYWORD)
{
ntoken = yylex();
printf("\nPrinting %s",yytext);
ntoken = yylex();
continue;
}
printf("\nIdentifier %s is : ",yytext);
ntoken = yylex();
if(ntoken != EQU_OP)
{
printf("\nError : Undefined Syntax at line %d",yylineno);
break;
}
ntoken = yylex();
if(ntoken == DIGIT)
{
printf("%s",yytext);
}
else
{
printf(" %s ",yytext);
ntoken = yylex();
printf(" %s ",yytext);
ntoken = yylex();
printf(" %s ",yytext);
}
ntoken = yylex();
}*/
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<int, char> ic;
typedef pair<long, char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) {
return a * (b / gcd(a, b));
}
vector<vi> adj;
int T, N, maxDepth, vis[10010];
vi maxi, maxi2;
queue<int> q;
void dfs(int u, int depth, int v) {
vis[u] = v;
if (depth == maxDepth)
maxi.push_back(u);
if (depth > maxDepth) {
maxDepth = depth;
maxi.clear();
maxi.push_back(u);
}
for (int i = 0; i < adj[u].size(); i++)
if (vis[adj[u][i]] != v)
dfs(adj[u][i], depth + 1, v);
}
void dfs2(int u, int depth, int v) {
vis[u] = v;
if (depth == maxDepth)
maxi2.push_back(u);
if (depth > maxDepth) {
maxDepth = depth;
maxi2.clear();
maxi2.push_back(u);
}
for (int i = 0; i < adj[u].size(); i++)
if (vis[adj[u][i]] != v)
dfs2(adj[u][i], depth + 1, v);
}
int main() {
cin >> T;
while (T--) {
cin >> N;
adj.assign(N + 1, vi());
for (int c = 1; c < N; c++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
maxi.clear();
maxi2.clear();
maxDepth = 0;
MEM(vis, 0);
int v = 1;
dfs(1, 0, v);
int mini = INF;
vi visited(N+1, 0);
// cout << N+1 << " " << maxi[0] << endl;
for (int i = 0; i < maxi.size(); i++) {
if (visited[maxi[i]])
continue;
// cout << "maxi[i]: " << maxi[i] << endl;
visited[maxi[i]] = 1;
dfs2(maxi[i], 0, ++v);
// cout << maxi2.size() << endl;
mini = min(mini, maxi2.size());
if (mini == 1)
break;
for (int j = 0; j < maxi2.size(); j++)
maxi.push_back(maxi2[j]);
maxi2.clear();
}
if (mini == 1 && maxDepth > 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
|
//
// CCEditboxLoader.cpp
// cocos2d_libs
//
// Created by xuruoji on 14-4-12.
//
//
#include "CCEditboxLoader.h"
namespace cocosbuilder {
cocos2d::ui::EditBox * EditBoxLoader::createNode(cocos2d::Node * pParent, cocosbuilder::CCBReader * ccbReader)
{
cocos2d::ui::EditBox* pNode = cocos2d::ui::EditBox::create(cocos2d::Size::ZERO, nullptr);
//pNode->setAnchorPoint(cocos2d::Point(0.5,0.5));
return pNode;
}
void EditBoxLoader::onHandlePropTypeBlock(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * ccbReader) {
NodeLoader::onHandlePropTypeBlockControl(pNode, pParent, pPropertyName, (BlockControlData*)pBlockData, ccbReader);
}
void EditBoxLoader::onHandlePropTypeSpriteFrame(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::SpriteFrame * pSpriteFrame, CCBReader * ccbReader)
{
if (strcmp(pPropertyName, "backgroundSpriteFrame") == 0) {
//save pos
const cocos2d::Point pos = pNode->getPosition();
if (pSpriteFrame != nullptr)
{
//((cocos2d::ui::EditBox*)pNode)->setBackgroundSprite(cocos2d::ui::Scale9Sprite::createWithSpriteFrame(pSpriteFrame));
}
//pNode->setPosition(pos);
} else {
NodeLoader::onHandlePropTypeSpriteFrame(pNode, pParent, pPropertyName, pSpriteFrame, ccbReader);
}
}
void EditBoxLoader::onHandlePropTypeSize(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Size pSize, CCBReader * ccbReader)
{
if (strcmp(pPropertyName, "preferredSize") == 0) {
//((cocos2d::ui::EditBox*)pNode)->setPreferredSize(pSize);
} else {
NodeLoader::onHandlePropTypeSize(pNode, pParent, pPropertyName, pSize, ccbReader);
}
}
void EditBoxLoader::onHandlePropTypeFloatScale(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader)
{
if (strcmp(pPropertyName, "padding") == 0) {
} else {
NodeLoader::onHandlePropTypeFloatScale(pNode, pParent, pPropertyName, pFloatScale, ccbReader);
}
}
void EditBoxLoader::onHandlePropTypeFloat(cocos2d::Node * pNode, cocos2d::Node * pParent, const char* pPropertyName, float theFloat, CCBReader * ccbReader)
{
if (strcmp(pPropertyName, "fontSize") == 0) {
((cocos2d::ui::EditBox*)pNode)->setFontSize(theFloat);
} else {
NodeLoader::onHandlePropTypeFloat(pNode, pParent, pPropertyName, theFloat, ccbReader);
}
}
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <flux/Singleton>
#include <flux/Process>
#include <flux/Bundle>
#include "LogPrototype.h"
#include "NodeConfigProtocol.h"
namespace fluxnode {
class NodePrototype: public MetaObject
{
public:
static Ref<NodePrototype> create(MetaProtocol *protocol = 0, String className = "Node")
{
return new NodePrototype(className, protocol);
}
protected:
NodePrototype(String className, MetaProtocol *protocol):
MetaObject(className, protocol)
{
insert("address", "*");
insert("port", Process::isSuperUser() ? 80 : 8080);
insert("protocol", "");
insert("user", "");
insert("version", "fluxnode/" FLUX_BUNDLE_VERSION);
insert("daemon", false);
insert("service_window", 30);
insert("error_log", LogPrototype::create());
insert("access_log", LogPrototype::create());
}
};
NodeConfigProtocol::NodeConfigProtocol():
nodeProtocol_(MetaProtocol::create())
{
Ref<NodePrototype> nodePrototype = NodePrototype::create(nodeProtocol_);
define(nodePrototype);
}
void NodeConfigProtocol::registerService(MetaObject *configPrototype)
{
nodeProtocol_->define(configPrototype);
}
NodeConfigProtocol *configProtocol() { return Singleton<NodeConfigProtocol>::instance(); }
} // namespace fluxnode
|
/* Multi-neighborhood tabu search for the maximum weight clique problem
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This program demonstrates the use of the heuristic algorithm for solving
* the problem of the maximum weight clique problem. For more information about this algorithm,
* please visit the website http://www.info.univ-angers.fr/pub/hao/mnts_clique.html or email to: wu@info-univ.angers.fr.
*/
#pragma warning(disable : 4996)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <time.h>
#include <ctime>
#include <vector>
#include <random>
#include <string.h>
using namespace std;
char * File_Name;
int **adjacencyMatrix; // adjacent matrix
int *inCurrSolution;
int *numOfVerticesInSolutionNotConnectedTo; //funch
int *indices;
int *tabuin;
int numVertices;
int *notConnectedLength;
int **notConnected;
int *currSolution; //cruset
int currSolutionLength; //len
int *localBestSolution;
int numVerticesTimesSizeOfInt; //tm1
int *adders;
int *swappers;
int *weights;
int *swapBuddy;
int addersLength;
int swappersLength;
int *tiedCandidatesTabuIndex;
int iterationCtr;
int TABUL = 7;
int currSolutionQuality; //Wf
int localBestSolutionQuality; //WBest
int *tiedCandidateIndex;
int bestKnownSolutionQuality; //Waim
int iterationSolutionWasFoundOn;
double starting_time, finishing_time, avg_time;
int localBestSolutionLength = 0; //len_best
int runBestLength;
int Iteration[100];
double time_used[100];
int len_used[100];
int solutionQuality[100];
char outfilename[30];
int maxUnimproved;
int maxIterationsDividedByMaxUnimproved;
int weightMod;
int prIterations[100];
double prTimeUsed[100];
int prLenUsed[100];
int prSolutionQuality[100];
int prBestQuality = 0;
int prBestLength = 0;
double prStartTime = 0, prFinishTime = 0;
int prIterationSolutionWasFoundOn = 0;
const int ELITE_SET_CAPACITY = 20;
int** eliteSet;
int eliteSetSize = 0;
int* eliteSetSizes;
int * eliteSetWeights;
int eliteSetMinWeight = INT32_MIN;
int * initialSolution;
int initialSolutionSize = 0;
int * guidingSolution;
int guidingSolutionSize = 0;
bool * guidingContains;
int * workingSolution;
int workingSolutionSize = 0;
bool * workingContains;
int * tempWorkingSolution;
int tempWorkingSolutionSize = 0;
int * workingMinusGuiding;
int workingMinusGuidingSize = 0;
bool * workingMinusGuidingContains;
int * setDifferenceIndexMap;
int * guidingMinusWorking;
int guidingMinusWorkingSize = 0;
bool * guidingMinusWorkingContains;
int * tiedPRSwapIns;
int tiedPRSwapInsSize = 0;
int * s2Contains;
long long totalOperations = 0;
unsigned int pathLengthSum = 0;
double pathsTraversed = 0;
int prStrategy = -1;
int nextStepMode = -1;
const int GREATEST_DELTA = 0, SMALLEST_CLIQUE = 1, RANDOM = 2;
const int FORWARD_AND_BACKWARD = 0, FORWARD = 1, BACKWARD = 2;
random_device rd;
mt19937 mersenneTwister(rd());
bool isClique(int * list, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i != j) {
if (list[i] == list[j]) {
cout << "oops" << endl;
}
if (adjacencyMatrix[list[i]][list[j]] == 1) {
return false;
}
}
}
}
return true;
}
// section 0, initiaze
void Initializing()
{
ifstream FIC;
FIC.open(File_Name);
if (FIC.fail())
{
cout << "### Erreur open, File_Name " << File_Name << endl;
getchar();
exit(0);
}
char StrReading[100];
FIC >> StrReading;
if (FIC.eof())
{
cout << "### Error open, File_Name " << File_Name << endl;
exit(0);
}
int nb_vtx = 0, nb_edg = -1, max_edg = 0;
int x1, x2;
while (!FIC.eof())
{
if (strcmp(StrReading, "p") == 0)
{
FIC >> StrReading;
FIC >> numVertices >> nb_edg;
cout << "Number of vertexes = " << numVertices << endl;
cout << "Number of edges = " << nb_edg << endl;
inCurrSolution = new int[numVertices];
numOfVerticesInSolutionNotConnectedTo = new int[numVertices];
indices = new int[numVertices];
tabuin = new int[numVertices];
notConnectedLength = new int[numVertices];
adders = new int[numVertices];
swappers = new int[numVertices];
tiedCandidatesTabuIndex = new int[numVertices];
weights = new int[numVertices];
swapBuddy = new int[numVertices];
tiedCandidateIndex = new int[numVertices];
notConnected = new int*[numVertices];
eliteSet = new int*[ELITE_SET_CAPACITY];
eliteSetSizes = new int[ELITE_SET_CAPACITY];
eliteSetWeights = new int[ELITE_SET_CAPACITY];
currSolution = new int[2000];
localBestSolution = new int[2000];
initialSolution = new int[2000];
guidingSolution = new int[2000];
workingSolution = new int[2000];
tempWorkingSolution = new int[2000];
workingMinusGuiding = new int[2000];
guidingMinusWorking = new int[2000];
workingMinusGuidingContains = new bool[numVertices];
guidingMinusWorkingContains = new bool[numVertices];
setDifferenceIndexMap = new int[numVertices];
workingContains = new bool[numVertices];
guidingContains = new bool[numVertices];
tiedPRSwapIns = new int[numVertices];
s2Contains = new int[numVertices];
for (int x = 0; x < ELITE_SET_CAPACITY; x++) {
eliteSet[x] = new int[numVertices];
}
for (int x = 0; x < numVertices; x++)
{
inCurrSolution[x] = x;
indices[x] = x;
}
adjacencyMatrix = new int*[numVertices];
for (int x = 0; x < numVertices; x++)
{
adjacencyMatrix[x] = new int[numVertices];
notConnected[x] = new int[numVertices];
}
for (int x = 0; x < numVertices; x++)
for (int y = 0; y < numVertices; y++)
adjacencyMatrix[x][y] = 0;
}
if (strcmp(StrReading, "e") == 0)
{
FIC >> x1 >> x2;
x1--; x2--;
if (x1 < 0 || x2 < 0 || x1 >= numVertices || x2 >= numVertices)
{
cout << "### Error of node : x1="
<< x1 << ", x2=" << x2 << endl;
exit(0);
}
adjacencyMatrix[x1][x2] = adjacencyMatrix[x2][x1] = 1;
max_edg++;
}
FIC >> StrReading;
}
cout << "Density = " << (float)max_edg / (numVertices*(numVertices - 1)) << endl;
if (0 && max_edg != nb_edg)
{
cout << "### Error de lecture du graphe, nbre aretes : annonce="
<< nb_edg << ", lu=" << max_edg << endl;
exit(0);
}
for (int x = 0; x < numVertices; x++)
for (int y = 0; y < numVertices; y++)
adjacencyMatrix[x][y] = 1 - adjacencyMatrix[x][y]; //flipping values from 0 to 1 and vice versa. now 0 == connected, 1 == disconnected
for (int x = 0; x < numVertices; x++)
adjacencyMatrix[x][x] = 0; //connected to self
for (int x = 0; x < numVertices; x++)
{
notConnectedLength[x] = 0;
for (int y = 0; y < numVertices; y++)
{
if (adjacencyMatrix[x][y] == 1)
{
notConnected[x][notConnectedLength[x]] = y;
notConnectedLength[x]++;
}
}
}
for (int x = 0; x < numVertices; x++)
{
weights[x] = (x + 1) % weightMod + 1;
swapBuddy[x] = 0;
}
FIC.close();
}
int randomInt(int n, bool pr)
{
if (!pr) {
int randomInt = rand() % n;
return randomInt;
}
else {
uniform_int_distribution<int> dist(0, n - 1);
int randomInt = dist(mersenneTwister);
return randomInt;
}
}
void resetLists()
{
int i;
memset(inCurrSolution, 0, numVerticesTimesSizeOfInt);
memset(numOfVerticesInSolutionNotConnectedTo, 0, numVerticesTimesSizeOfInt);
memset(indices, 0, numVerticesTimesSizeOfInt);
memset(tabuin, 0, numVerticesTimesSizeOfInt);
for (i = 0; i < numVertices; i++)
{
adders[i] = i;
indices[i] = i;
}
addersLength = numVertices;
swappersLength = 0;
currSolutionLength = 0;
currSolutionQuality = 0;
localBestSolutionQuality = 0;
}
int selectNextVertexForInitialSolution()
{
int i, k, numNonTabu;
numNonTabu = 0;
if (addersLength > 30)
{
k = randomInt(addersLength, false);
return k;
}
for (i = 0; i < addersLength; i++)
{
k = adders[i];
if (tabuin[k] <= iterationCtr)
tiedCandidatesTabuIndex[numNonTabu++] = i;
}
if (numNonTabu == 0)
return -1;
else
{
k = randomInt(numNonTabu, false);
k = tiedCandidatesTabuIndex[k];
return k;
}
}
int WSelectBestFromAdd(bool pr)
{
int i, k, tiedCandidatesLength, tiedCandidatesTabuLength, greatestDelta, greatestTabuDelta;
tiedCandidatesLength = 0;
tiedCandidatesTabuLength = 0;
greatestDelta = 0;
greatestTabuDelta = 0;
for (i = 0; i < addersLength; i++)
{
k = adders[i];
if (tabuin[k] <= iterationCtr)
{
if (weights[k] > greatestDelta)
{
tiedCandidatesLength = 0;
greatestDelta = weights[k];
tiedCandidateIndex[tiedCandidatesLength++] = i;
}
else if (weights[k] >= greatestDelta)
{
tiedCandidateIndex[tiedCandidatesLength++] = i;
}
}
else
{
if (weights[k] > greatestTabuDelta)
{
tiedCandidatesTabuLength = 0;
greatestTabuDelta = weights[k];
tiedCandidatesTabuIndex[tiedCandidatesTabuLength++] = i;
}
else if (weights[k] >= greatestTabuDelta)
{
tiedCandidatesTabuIndex[tiedCandidatesTabuLength++] = i;
}
}
}
if ((tiedCandidatesTabuLength > 0) && (greatestTabuDelta > greatestDelta) && ((greatestTabuDelta + currSolutionQuality) > localBestSolutionQuality))
{
k = randomInt(tiedCandidatesTabuLength, pr);
k = tiedCandidatesTabuIndex[k];
return k;
}
else if (tiedCandidatesLength > 0)
{
k = randomInt(tiedCandidatesLength, pr);
k = tiedCandidateIndex[k];
return k;
}
else
{
return -1;
}
}
int addToCurrSolution(int SelN)
{
totalOperations++;
int i, nIndex, m, n, last;
m = adders[SelN];
currSolution[currSolutionLength++] = m;
inCurrSolution[m] = 1;
currSolutionQuality = currSolutionQuality + weights[m];
addersLength--;
last = adders[addersLength];
nIndex = indices[m];
adders[nIndex] = last;
indices[last] = nIndex;
for (i = 0; i < notConnectedLength[m]; i++)
{
n = notConnected[m][i];
numOfVerticesInSolutionNotConnectedTo[n]++;
if (numOfVerticesInSolutionNotConnectedTo[n] == 1)
{
nIndex = indices[n];
addersLength--;
last = adders[addersLength];
adders[nIndex] = last;
indices[last] = nIndex; //swap to remove
swappers[swappersLength] = n;
indices[n] = swappersLength;
swappersLength++;
swapBuddy[n] = m;
}
else if (numOfVerticesInSolutionNotConnectedTo[n] == 2)
{
swappersLength--;
last = swappers[swappersLength];
nIndex = indices[n];
swappers[nIndex] = last;
indices[last] = nIndex;
}
}
if (currSolutionQuality > localBestSolutionQuality)
{
localBestSolutionQuality = currSolutionQuality;
localBestSolutionLength = currSolutionLength;
for (int i = 0; i < currSolutionLength; i++) {
localBestSolution[i] = currSolution[i];
}
}
return 1;
}
int WSelectBestFromSwappy(bool pr)
{
int i, j, k, l, tiedCandidatesLength, tiedCandidatesTabuLength, swapDelta, greatestDelta, tabuGreatestDelta, swapIn, swapOut;
tiedCandidatesLength = 0;
tiedCandidatesTabuLength = 0;
greatestDelta = -1000000;
tabuGreatestDelta = -1000000;
l = 0;
for (i = 0; i < swappersLength; i++)
{
swapIn = swappers[i];
swapOut = swapBuddy[swapIn];
if ((inCurrSolution[swapOut] == 1) && (adjacencyMatrix[swapIn][swapOut] == 1))
l++;
else
{
for (j = 0; j < currSolutionLength; j++)
{
k = currSolution[j];
if (adjacencyMatrix[swapIn][k] == 1)
break;
}
swapBuddy[swapIn] = k;
}
}
for (i = 0; i < swappersLength; i++)
{
swapIn = swappers[i];
swapOut = swapBuddy[swapIn];
swapDelta = weights[swapIn] - weights[swapOut];
if (tabuin[swapIn] <= iterationCtr)
{
if (swapDelta > greatestDelta)
{
tiedCandidatesLength = 0;
greatestDelta = swapDelta;
tiedCandidateIndex[tiedCandidatesLength++] = i;
}
else if (swapDelta >= greatestDelta)
{
tiedCandidateIndex[tiedCandidatesLength++] = i;
}
}
else
{
if (swapDelta > tabuGreatestDelta)
{
tiedCandidatesTabuLength = 0;
tabuGreatestDelta = swapDelta;
tiedCandidatesTabuIndex[tiedCandidatesTabuLength++] = i;
}
else if (swapDelta >= tabuGreatestDelta)
{
tiedCandidatesTabuIndex[tiedCandidatesTabuLength++] = i;
}
}
}
if ((tiedCandidatesTabuLength > 0) && (tabuGreatestDelta > greatestDelta) && ((tabuGreatestDelta + currSolutionQuality) > localBestSolutionQuality))
{
k = randomInt(tiedCandidatesTabuLength, pr);
k = tiedCandidatesTabuIndex[k];
return k;
}
else if (tiedCandidatesLength > 0)
{
k = randomInt(tiedCandidatesLength, pr);
k = tiedCandidateIndex[k];
return k;
}
else
{
return -1;
}
}
int doTheSwappy(int SelN, bool pr)
{
totalOperations++;
int i, swapIndexIn, vertexIn, vertexOut, disconnectedVertex, lastElementOfSwappers, indexOut;
vertexIn = swappers[SelN];
for (indexOut = 0; indexOut < currSolutionLength; indexOut++)
{
vertexOut = currSolution[indexOut];
if (adjacencyMatrix[vertexOut][vertexIn] == 1)
break;
}
currSolutionQuality = currSolutionQuality + weights[vertexIn] - weights[vertexOut];
//the expand process, put m into the current independent set
inCurrSolution[vertexIn] = 1;
currSolution[currSolutionLength++] = vertexIn;
//delete m from C1
swapIndexIn = indices[vertexIn];
swappersLength--;
lastElementOfSwappers = swappers[swappersLength];
swappers[swapIndexIn] = lastElementOfSwappers;
indices[lastElementOfSwappers] = swapIndexIn;
for (i = 0; i < notConnectedLength[vertexIn]; i++)
{
disconnectedVertex = notConnected[vertexIn][i];
numOfVerticesInSolutionNotConnectedTo[disconnectedVertex]++;
if ((numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 1) && (inCurrSolution[disconnectedVertex] == 0))
{
swapIndexIn = indices[disconnectedVertex];
addersLength--;
lastElementOfSwappers = adders[addersLength];
adders[swapIndexIn] = lastElementOfSwappers;
indices[lastElementOfSwappers] = swapIndexIn;
swappers[swappersLength] = disconnectedVertex;
indices[disconnectedVertex] = swappersLength;
swappersLength++;
swapBuddy[disconnectedVertex] = vertexIn;
}
if (numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 2)
{
swappersLength--;
lastElementOfSwappers = swappers[swappersLength];
swapIndexIn = indices[disconnectedVertex];
swappers[swapIndexIn] = lastElementOfSwappers;
indices[lastElementOfSwappers] = swapIndexIn;
}
}
//the backtrack process, delete m1 from the current independent set
inCurrSolution[vertexOut] = 0;
tabuin[vertexOut] = iterationCtr + TABUL + randomInt(swappersLength + 2, pr);
currSolutionLength--;
currSolution[indexOut] = currSolution[currSolutionLength];
swappers[swappersLength] = vertexOut;
indices[vertexOut] = swappersLength;
swappersLength++;
for (i = 0; i < notConnectedLength[vertexOut]; i++)
{
disconnectedVertex = notConnected[vertexOut][i];
numOfVerticesInSolutionNotConnectedTo[disconnectedVertex]--;
if ((numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 0) && (inCurrSolution[disconnectedVertex] == 0))
{
swapIndexIn = indices[disconnectedVertex];
swappersLength--;
lastElementOfSwappers = swappers[swappersLength];
swappers[swapIndexIn] = lastElementOfSwappers;
indices[lastElementOfSwappers] = swapIndexIn;
adders[addersLength] = disconnectedVertex;
indices[disconnectedVertex] = addersLength;
addersLength++;
}
else if (numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 1)
{
swappers[swappersLength] = disconnectedVertex;
indices[disconnectedVertex] = swappersLength;
swappersLength++;
}
}
if (currSolutionQuality > localBestSolutionQuality)
{
localBestSolutionQuality = currSolutionQuality;
localBestSolutionLength = currSolutionLength;
for (int i = 0; i < currSolutionLength; i++) {
localBestSolution[i] = currSolution[i];
}
}
return 1;
}
int findMinWeightInCurrSolution(bool pr)
{
int i, k, tiedCounter;
int minWeight = 5000000;
tiedCounter = 0;
for (i = 0; i < currSolutionLength; i++)
{
k = currSolution[i];
if (weights[k] < minWeight)
{
tiedCounter = 0;
minWeight = weights[k];
tiedCandidateIndex[tiedCounter++] = i;
}
else if (weights[k] <= minWeight)
{
tiedCandidateIndex[tiedCounter++] = i;
}
}
if (tiedCounter == 0)
return -1;
k = randomInt(tiedCounter, pr);
k = tiedCandidateIndex[k];
return k;
}
int removeFromSolution(bool pr)
{
totalOperations++;
int i, minVertex, disconnectedVertex, minIndex, swapIndex, last;
minIndex = findMinWeightInCurrSolution(pr);
if (minIndex == -1)
return -1;
minVertex = currSolution[minIndex];
currSolutionQuality = currSolutionQuality - weights[minVertex];
inCurrSolution[minVertex] = 0;
tabuin[minVertex] = iterationCtr + TABUL;
currSolutionLength--;
currSolution[minIndex] = currSolution[currSolutionLength];
adders[addersLength] = minVertex;
indices[minVertex] = addersLength;
addersLength++;
for (i = 0; i < notConnectedLength[minVertex]; i++)
{
disconnectedVertex = notConnected[minVertex][i];
numOfVerticesInSolutionNotConnectedTo[disconnectedVertex]--;
if ((numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 0) && (inCurrSolution[disconnectedVertex] == 0))
{
swapIndex = indices[disconnectedVertex];
swappersLength--;
last = swappers[swappersLength];
swappers[swapIndex] = last;
indices[last] = swapIndex;
adders[addersLength] = disconnectedVertex;
indices[disconnectedVertex] = addersLength;
addersLength++;
}
else if (numOfVerticesInSolutionNotConnectedTo[disconnectedVertex] == 1)
{
swappers[swappersLength] = disconnectedVertex;
indices[disconnectedVertex] = swappersLength;
swappersLength++;
}
}
}
int setInitialSolution() {
int mysteriousL, bestToAdd;
iterationCtr = 0;
resetLists();
while (1)
{
bestToAdd = selectNextVertexForInitialSolution();
if (bestToAdd != -1)
{
mysteriousL = addToCurrSolution(bestToAdd);
iterationCtr++;
if (localBestSolutionQuality == bestKnownSolutionQuality)
return localBestSolutionQuality;
}
else
return localBestSolutionQuality;
}
}
int performLocalSearch(int maxUnimproved, bool pathRelinking)
{
int k, mysteriousL, bestToAdd, bestToSwap, addDelta, swapDelta, deleteDelta, bestDeleteIndex, bestToDelete;
int restartThreshold = INT32_MIN;
int tmpMaxUnimproved = maxUnimproved;
while (iterationCtr < maxUnimproved)
{
bestToAdd = WSelectBestFromAdd(pathRelinking);
bestToSwap = WSelectBestFromSwappy(pathRelinking);
if ((bestToAdd != -1) && (bestToSwap != -1))
{
addDelta = weights[adders[bestToAdd]];
swapDelta = weights[swappers[bestToSwap]] - weights[swapBuddy[swappers[bestToSwap]]];
if (addDelta > swapDelta)
{
mysteriousL = addToCurrSolution(bestToAdd);
iterationCtr++;
if (localBestSolutionQuality == bestKnownSolutionQuality && !pathRelinking)
return localBestSolutionQuality;
}
else
{
mysteriousL = doTheSwappy(bestToSwap, pathRelinking);
if (localBestSolutionQuality == bestKnownSolutionQuality && !pathRelinking)
return localBestSolutionQuality;
iterationCtr++;
}
}
else if ((bestToAdd != -1) && (bestToSwap == -1))
{
mysteriousL = addToCurrSolution(bestToAdd);
if (localBestSolutionQuality == bestKnownSolutionQuality && !pathRelinking)
return localBestSolutionQuality;
iterationCtr++;
}
else if ((bestToAdd == -1) && (bestToSwap != -1))
{
bestDeleteIndex = findMinWeightInCurrSolution(pathRelinking);
bestToDelete = currSolution[bestDeleteIndex];
swapDelta = weights[swappers[bestToSwap]] - weights[swapBuddy[swappers[bestToSwap]]];
deleteDelta = -weights[bestToDelete];
if (swapDelta > deleteDelta)
{
mysteriousL = doTheSwappy(bestToSwap, pathRelinking);
if (localBestSolutionQuality == bestKnownSolutionQuality && !pathRelinking)
return localBestSolutionQuality;
iterationCtr++;
}
else
{
k = removeFromSolution(pathRelinking);
if (k == -1)
return localBestSolutionQuality;
iterationCtr++;
}
}
else if ((bestToAdd == -1) && (bestToSwap == -1))
{
k = removeFromSolution(pathRelinking);
if (k == -1)
return localBestSolutionQuality;
iterationCtr++;
}
if (pathRelinking && localBestSolutionQuality > restartThreshold) {
//maxUnimproved = iterationCtr + tmpMaxUnimproved;
restartThreshold = localBestSolutionQuality;
}
}
return localBestSolutionQuality;
}
bool isEqual(int * s1, int size1, int * s2, int size2) {
if (size1 != size2) {
return false;
}
memset(s2Contains, false, numVertices * sizeof(bool));
for (int i = 0; i < size2; i++) {
s2Contains[s2[i]] = true;
}
for (int i = 0; i < size1; i++) {
if (!s2Contains[s1[i]]) {
return false;
}
}
return true;
}
bool isUnique(int solution[], int size) {
for (int i = 0; i < eliteSetSize; i++) {
if (isEqual(eliteSet[i], eliteSetSizes[i], solution, size)) {
return false;
}
}
return true;
}
void printResultsToFile()
{
int i;
FILE *fp;
int len = strlen(File_Name);
strcpy(outfilename, File_Name);
outfilename[len] = '.';
outfilename[len + 1] = 'o';
outfilename[len + 2] = 'u';
outfilename[len + 3] = 't';
outfilename[len + 4] = '\0';
fp = fopen(outfilename, "a+");
for (i = 0; i < 100; i++)
{
fprintf(fp, "sum = %6d, iter = %6d, len = %5d, time = %8lf \n", solutionQuality[i], Iteration[i], len_used[i], time_used[i]);
fprintf(fp, "PR: sum = %6d, iter = %6d, len = %5d, time = %8lf \n", prSolutionQuality[i], prIterations[i], prLenUsed[i], prTimeUsed[i]);
}
fprintf(fp, "\n\n the total information: \n");
int wavg, tiedIterationAvg, lenbb;
wavg = tiedIterationAvg = lenbb = 0;
int bestSolutionQuality = 0;
double tiedTimeAvg = 0;
for (i = 0; i < 100; i++)
if (solutionQuality[i] > bestSolutionQuality)
{
bestSolutionQuality = solutionQuality[i];
lenbb = len_used[i];
}
int numTiedForBest = 0;
fprintf(fp, "\n The best weight value for the maximum weighted problem is %6d \n", bestSolutionQuality);
for (i = 0; i < 100; i++)
{
wavg = wavg + solutionQuality[i];
}
double twavg = (double(wavg)) / 100;
for (i = 0; i < 100; i++)
if (solutionQuality[i] >= bestSolutionQuality)
{
numTiedForBest++;
tiedIterationAvg = tiedIterationAvg + Iteration[i];
tiedTimeAvg = tiedTimeAvg + time_used[i];
}
tiedIterationAvg = int((double(tiedIterationAvg)) / numTiedForBest);
tiedTimeAvg = tiedTimeAvg / (numTiedForBest * 1000);
fprintf(fp, "avg_sum = %10lf, succes = %6d, len = %5d, avg_iter = %6d, time = %8lf \n", twavg, numTiedForBest, lenbb, tiedIterationAvg, tiedTimeAvg);
double totalImprovement = 0;
double totalIterationsTaken = 0;
int numImproved = 0;
int successesAfterPr = 0;
double prAvg = 0;
for (int i = 0; i < 100; i++) {
totalImprovement += prSolutionQuality[i] - solutionQuality[i];
totalIterationsTaken += prIterations[i];
prAvg += prSolutionQuality[i];
if (prSolutionQuality[i] > solutionQuality[i]) {
numImproved++;
}
if (prSolutionQuality[i] >= bestKnownSolutionQuality) {
successesAfterPr++;
}
}
prAvg /= 100.0;
fprintf(fp, "Strategy: ");
if (prStrategy == FORWARD) {
fprintf(fp, " forward");
}
else if (prStrategy == BACKWARD) {
fprintf(fp, " backward");
}
else {
fprintf(fp, "forward-and-backward");
}
fprintf(fp, " NextStep: ");
if (nextStepMode == GREATEST_DELTA) {
fprintf(fp, " greatest delta");
}
else if (nextStepMode == SMALLEST_CLIQUE) {
fprintf(fp, " smallest clique");
}
else {
fprintf(fp, " random");
}
fprintf(fp, "\n");
fprintf(fp, "Avg Sum: %10lf, Avg improvment = %10lf, Num Improved = %6d, Successes after pr = %6d, Iterations/Improvement = %10lf \n", prAvg,totalImprovement / 100.0, numImproved,
successesAfterPr,totalIterationsTaken/totalImprovement);
fprintf(fp, "Total number of operations : %6lld, Avg: %10lf, Avg Path Length: %10lf \n", totalOperations, totalOperations / 100.0, pathLengthSum / pathsTraversed);
fprintf(fp, "\n");
fclose(fp);
return;
}
void addLocalBestToEliteSet() {
if (!isUnique(localBestSolution, localBestSolutionLength)) {
return;
}
if (eliteSetSize >= ELITE_SET_CAPACITY) {
int min = INT32_MAX;
int minIndex = 0;
for (int i = 0; i < eliteSetSize; i++) {
if (eliteSetWeights[i] < min) {
min = eliteSetWeights[i];
minIndex = i;
}
}
for (int j = 0; j < localBestSolutionLength; j++) {
eliteSet[minIndex][j] = localBestSolution[j];
}
eliteSetSizes[minIndex] = localBestSolutionLength;
eliteSetWeights[minIndex] = localBestSolutionQuality;
eliteSetMinWeight = INT32_MAX;
for (int i = 0; i < eliteSetSize; i++) {
if (eliteSetWeights[i] < eliteSetMinWeight) {
eliteSetMinWeight = eliteSetWeights[i];
}
}
}
else {
for (int j = 0; j < localBestSolutionLength; j++) {
eliteSet[eliteSetSize][j] = localBestSolution[j];
}
eliteSetSizes[eliteSetSize] = localBestSolutionLength;
eliteSetWeights[eliteSetSize] = localBestSolutionQuality;
eliteSetSize++;
}
}
void calculateDifferences() {
workingMinusGuidingSize = 0;
guidingMinusWorkingSize = 0;
memset(workingMinusGuidingContains, false, sizeof(bool) * numVertices);
memset(guidingMinusWorkingContains, false, sizeof(bool) * numVertices);
for (int i = 0; i < workingSolutionSize; i++) {
if (!guidingContains[workingSolution[i]]) {
workingMinusGuiding[workingMinusGuidingSize] = workingSolution[i];
setDifferenceIndexMap[workingSolution[i]] = workingMinusGuidingSize;
workingMinusGuidingContains[workingSolution[i]] = true;
workingMinusGuidingSize++;
}
}
for (int i = 0; i < guidingSolutionSize; i++) {
if (!workingContains[guidingSolution[i]]) {
guidingMinusWorking[guidingMinusWorkingSize] = guidingSolution[i];
setDifferenceIndexMap[guidingSolution[i]] = guidingMinusWorkingSize;
guidingMinusWorkingContains[guidingSolution[i]] = true;
guidingMinusWorkingSize++;
}
}
}
void moveWorkingTowardsGuidingSmallestSize() {
int minDisconnected = INT32_MAX;
tiedPRSwapInsSize = 0;
for (int i = 0; i < guidingMinusWorkingSize; i++) {
int guidingVertex = guidingMinusWorking[i];
int numDisconnected = 0;
for (int j = 0; j < workingMinusGuidingSize; j++) {
int workingVertex = workingMinusGuiding[j];
if (adjacencyMatrix[guidingVertex][workingVertex] == 1) {
numDisconnected++;
}
}
if (numDisconnected < minDisconnected) {
numDisconnected = minDisconnected;
tiedPRSwapInsSize = 0;
tiedPRSwapIns[tiedPRSwapInsSize] = guidingVertex;
tiedPRSwapInsSize++;
}
else if (numDisconnected == minDisconnected) {
tiedPRSwapIns[tiedPRSwapInsSize] = guidingVertex;
tiedPRSwapInsSize++;
}
}
int randomIndex = randomInt(tiedPRSwapInsSize, true);
int swapInVertex = tiedPRSwapIns[randomIndex];
tempWorkingSolutionSize = 0;
for (int i = 0; i < workingSolutionSize; i++) {
int vertex = workingSolution[i];
if (workingMinusGuidingContains[vertex]) {
if (adjacencyMatrix[swapInVertex][vertex] == 0) {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
else {
workingMinusGuidingContains[vertex] = false;
int index = setDifferenceIndexMap[vertex];
swap(workingMinusGuiding[index], workingMinusGuiding[workingMinusGuidingSize - 1]);
setDifferenceIndexMap[workingMinusGuiding[index]] = index;
workingMinusGuidingSize--;
}
}
else {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
}
tempWorkingSolution[tempWorkingSolutionSize] = swapInVertex;
tempWorkingSolutionSize++;
guidingMinusWorkingContains[swapInVertex] = false;
int index = setDifferenceIndexMap[swapInVertex];
swap(guidingMinusWorking[index], guidingMinusWorking[guidingMinusWorkingSize - 1]);
setDifferenceIndexMap[guidingMinusWorking[index]] = index;
guidingMinusWorkingSize--;
memset(workingContains, false, sizeof(bool) * numVertices);
for (int i = 0; i < tempWorkingSolutionSize; i++) {
workingSolution[i] = tempWorkingSolution[i];
workingContains[tempWorkingSolution[i]] = true;
}
workingSolutionSize = tempWorkingSolutionSize;
}
void moveWorkingTowardsGuidingGreatestDelta() {
int maxDelta = INT32_MIN;
tiedPRSwapInsSize = 0;
for (int i = 0; i < guidingMinusWorkingSize; i++) {
int delta = weights[guidingMinusWorking[i]];
int guidingVertex = guidingMinusWorking[i];
for (int j = 0; j < workingMinusGuidingSize; j++) {
int workingVertex = workingMinusGuiding[j];
if (adjacencyMatrix[guidingVertex][workingVertex] == 1) {
delta -= weights[workingVertex];
}
}
if (delta > maxDelta) {
maxDelta = delta;
tiedPRSwapInsSize = 0;
tiedPRSwapIns[tiedPRSwapInsSize] = guidingVertex;
tiedPRSwapInsSize++;
}
else if (delta == maxDelta) {
tiedPRSwapIns[tiedPRSwapInsSize] = guidingVertex;
tiedPRSwapInsSize++;
}
}
int randomIndex = randomInt(tiedPRSwapInsSize, true);
int swapInVertex = tiedPRSwapIns[randomIndex];
tempWorkingSolutionSize = 0;
for (int i = 0; i < workingSolutionSize; i++) {
int vertex = workingSolution[i];
if (workingMinusGuidingContains[vertex]) {
if (adjacencyMatrix[swapInVertex][vertex] == 0) {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
else {
workingMinusGuidingContains[vertex] = false;
int index = setDifferenceIndexMap[vertex];
swap(workingMinusGuiding[index], workingMinusGuiding[workingMinusGuidingSize - 1]);
setDifferenceIndexMap[workingMinusGuiding[index]] = index;
workingMinusGuidingSize--;
}
}
else {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
}
tempWorkingSolution[tempWorkingSolutionSize] = swapInVertex;
tempWorkingSolutionSize++;
guidingMinusWorkingContains[swapInVertex] = false;
int index = setDifferenceIndexMap[swapInVertex];
swap(guidingMinusWorking[index], guidingMinusWorking[guidingMinusWorkingSize - 1]);
setDifferenceIndexMap[guidingMinusWorking[index]] = index;
guidingMinusWorkingSize--;
memset(workingContains, false, sizeof(bool) * numVertices);
for (int i = 0; i < tempWorkingSolutionSize; i++) {
workingSolution[i] = tempWorkingSolution[i];
workingContains[tempWorkingSolution[i]] = true;
}
workingSolutionSize = tempWorkingSolutionSize;
}
void moveWorkingTowardsGuidingRandom() {
int randomIndex = randomInt(guidingMinusWorkingSize, true);
int swapInVertex = guidingMinusWorking[randomIndex];
tempWorkingSolutionSize = 0;
for (int i = 0; i < workingSolutionSize; i++) {
int vertex = workingSolution[i];
if (workingMinusGuidingContains[vertex]) {
if (adjacencyMatrix[swapInVertex][vertex] == 0) {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
else {
workingMinusGuidingContains[vertex] = false;
int index = setDifferenceIndexMap[vertex];
swap(workingMinusGuiding[index], workingMinusGuiding[workingMinusGuidingSize - 1]);
setDifferenceIndexMap[workingMinusGuiding[index]] = index;
workingMinusGuidingSize--;
}
}
else {
tempWorkingSolution[tempWorkingSolutionSize] = vertex;
tempWorkingSolutionSize++;
}
}
tempWorkingSolution[tempWorkingSolutionSize] = swapInVertex;
tempWorkingSolutionSize++;
guidingMinusWorkingContains[swapInVertex] = false;
int index = setDifferenceIndexMap[swapInVertex];
swap(guidingMinusWorking[index], guidingMinusWorking[guidingMinusWorkingSize - 1]);
setDifferenceIndexMap[guidingMinusWorking[index]] = index;
guidingMinusWorkingSize--;
memset(workingContains, false, sizeof(bool) * numVertices);
for (int i = 0; i < tempWorkingSolutionSize; i++) {
workingSolution[i] = tempWorkingSolution[i];
workingContains[tempWorkingSolution[i]] = true;
}
workingSolutionSize = tempWorkingSolutionSize;
}
void setCurrentToWorking() {
resetLists();
for (int i = 0; i < workingSolutionSize; i++) {
int addIndex = indices[workingSolution[i]];
addToCurrSolution(addIndex);
}
iterationCtr = 0;
}
void performPathRelinking(int runBest) {
prStartTime = (double)clock();
prFinishTime = prStartTime;
prBestLength = runBestLength;
prBestQuality = runBest;
prIterationSolutionWasFoundOn = 0;
int min = runBest;
long iterationsUsed = 0;
long iterationFound = 0;
for (int i = 0; i < eliteSetSize - 1; i++) {
memset(workingContains, false, sizeof(bool) * numVertices);
for (int m = 0; m < eliteSetSizes[i]; m++) {
initialSolution[m] = eliteSet[i][m];
workingSolution[m] = eliteSet[i][m];
workingContains[eliteSet[i][m]] = true;
}
workingSolutionSize = eliteSetSizes[i];
initialSolutionSize = eliteSetSizes[i];
for (int j = 0; j < eliteSetSize; j++) {
if (j == i ) {
continue;
}
if (prStrategy == FORWARD && eliteSetWeights[i] > eliteSetWeights[j]) {
continue;
}
if (prStrategy == BACKWARD && eliteSetWeights[j] < eliteSetWeights[i]) {
continue;
}
pathsTraversed++;
memset(guidingContains, false, sizeof(bool) * numVertices);
for (int m = 0; m < eliteSetSizes[j]; m++) {
guidingSolution[m] = eliteSet[j][m];
guidingContains[eliteSet[j][m]] = true;
}
guidingSolutionSize = eliteSetSizes[j];
calculateDifferences();
int steps = 0;
while (guidingMinusWorkingSize > 0) {
if (nextStepMode == GREATEST_DELTA) {
moveWorkingTowardsGuidingGreatestDelta();
}
else if (nextStepMode == SMALLEST_CLIQUE) {
moveWorkingTowardsGuidingSmallestSize();
}
else {
moveWorkingTowardsGuidingRandom();
}
setCurrentToWorking();
steps++;
pathLengthSum++;
int currQual = currSolutionQuality;
int afterPr = performLocalSearch(maxUnimproved, true);
iterationsUsed += iterationCtr;
if (afterPr > min) {
min = afterPr;
iterationFound = iterationsUsed;
prFinishTime = (double)clock();
prIterationSolutionWasFoundOn = iterationFound;
prBestLength = currSolutionLength;
prBestQuality = afterPr;
}
}
if (steps == 0) {
cout << "danger" << endl;
}
}
}
cout << "Before PR: " << runBest << " After: " << min << " Iterations: " << iterationFound << endl;
eliteSetSize = 0;
eliteSetMinWeight = INT32_MIN;
}
int runHeuristic()
{
int i, improvedSolutionQuality, runBest;
runBest = 0;
iterationSolutionWasFoundOn = 0;
int totalIterations = 0;
starting_time = (double)clock();
for (i = 0; i < maxIterationsDividedByMaxUnimproved; i++)
{
improvedSolutionQuality = setInitialSolution();
improvedSolutionQuality = performLocalSearch(maxUnimproved, false);
if (localBestSolutionQuality >= eliteSetMinWeight) { //local best solution
addLocalBestToEliteSet();
}
totalIterations = totalIterations + iterationCtr;
if (improvedSolutionQuality > runBest)
{
runBest = improvedSolutionQuality;
finishing_time = (double)clock();
iterationSolutionWasFoundOn = totalIterations;
runBestLength = localBestSolutionLength;
}
if (runBest >= bestKnownSolutionQuality)
break;
}
performPathRelinking(runBest);
return runBest;
}
int main(int argc, char **argv)
{
if (argc == 7)
{
File_Name = argv[1];
bestKnownSolutionQuality = atoi(argv[2]);
weightMod = atoi(argv[3]);
maxUnimproved = atoi(argv[4]);
prStrategy = atoi(argv[5]);
nextStepMode = atoi(argv[6]);
}
else
{
for (int i = 0; i < argc; i++) {
cout << argv[i] << "\n";
}
cout << "Error : the user should input six parameters to run the program." << endl;
exit(0);
}
srand((unsigned)time(NULL));
Initializing();
numVerticesTimesSizeOfInt = numVertices * sizeof(int);
cout << "finish reading data" << endl;
int i, l;
maxIterationsDividedByMaxUnimproved = (int(100000000 / maxUnimproved)) + 1;
cout << "len_time = " << maxIterationsDividedByMaxUnimproved << endl;
for (i = 0; i < 100; i++)
{
l = runHeuristic();
solutionQuality[i] = l;
len_used[i] = runBestLength;
time_used[i] = finishing_time - starting_time;
Iteration[i] = iterationSolutionWasFoundOn;
prSolutionQuality[i] = prBestQuality;
prLenUsed[i] = prBestLength;
prTimeUsed[i] = prFinishTime - prStartTime;
prIterations[i] = prIterationSolutionWasFoundOn;
cout << "i = " << i << " l = " << l <<
"time: " << time_used[i] << " iterations: " << Iteration[i] <<endl;
}
printResultsToFile();
cout << "finished" << endl;
getchar();
}
|
/*
Name : Toroid Calculator
Author: Ben Rockhold
Date: 02/20/15
Description: Calculate the volume and surface area for each toroid in a given set.
Expected input is a text file "toroids.txt," each line of which contains
a pair of decimal numbers representing first the radius of the tube,
and then the major radius of the torus.
e.g.
1.0 4.0
0.5 1.5
The program will terminate when presented with either an empty line,
or an invalid torus. (radius of zero or negative)
A file named "toroid_report" will be created, with information on the
volume and surface area of each torus.
*/
#include <math.h> // Definition of pi
#include <stdlib.h> // string to double with atof
#include <fstream> // fileIO
#include <iostream> // cin/cout
#include <string> // string operations
using namespace std;
// Identify if a pair of data points makes a valid torus
bool valid_torus(double r,double R){
if((r <= 0.0) | (R <= 0.0) | (R<r)){
return false;
}
return true;
}
// Function accepts r,R for a torus, and returns its volume
double torus_volume(double r,double R){
return 2*pow(M_PI,2)*R*r*r;
}
// Function accepts r,R for a torus, and returns the surface area
double torus_area(double r,double R){
return 4*pow(M_PI,2)*R*r;
}
// Function accepts r,R for a torus, and returns the area of the hole
double hole_area(double r,double R){
return M_PI*(R-r)*(R-r);
}
// Write information about the toroid r,R to the file passed
void write_report(ofstream& file,double r, double R){
file << "\nWhen the radius of the torus (R) is " << R << "cm ";
file << "and the radius of the tube (r) is\n" << r << "cm ";
file << "the volume is " << torus_volume(r,R) << "cm squared";
file << " and its surface area is\n" << torus_area(r, R) << "cc. ";
file << "The area of the hole is " << hole_area(r, R) << "cm squared.\n";
}
// Read the "toroid_data" file and create "toroid_report" file
int main(int argc, char *argv[]) {
// a and b are extracted from each line in the toroid_data file
char a[256],b[256];
ifstream toroid_data("toroids.txt");
ofstream toroid_report("toroid_report.txt");
if((toroid_data.is_open())&(toroid_report.is_open())){
while(toroid_data >> a >> b){
// cout << "r= " << a << " and R= " << b << endl;
double r = atof(a);
double R = atof(b);
if(valid_torus(r,R)){
write_report(toroid_report,r,R);
}
else return 1; // The data read is not valid, terminate with error
}
toroid_data.close();
toroid_report.close();
}
return 0;
} // End Main
/* Unused functions for replacing the main function with a variant based on user input rather than file reading
// Prompt user for 'r,' the toroid's minor radius
double get_minor_radius(){
double r;
cout << "Enter Minor radius (0 to exit): ";
cin >> r;
return r;
}
// Prompt user for 'R,' the toroid's major radius
double get_major_radius(){
double R;
cout << "Enter Major radius: ";
cin >> R;
return R;
}
int main(){
double r, R;
ofstream toroid_report("toroid_report.txt");
if(toroid_report.is_open()){
while((r < 0.0)&(R < 0.0)){
r = get_minor_radius();
R = get_major_radius();
if(valid_torus(r,R)){
write_report(toroid_report,r,R);
}
else return 1; // The data read is not valid, terminate with error
}
toroid_report.close();
}
return 0;
}
*/
|
/**
* Copyright (C) Mellanox Technologies Ltd. 2017. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include <common/test.h>
#include <uct/uct_test.h>
extern "C" {
#include <uct/api/uct.h>
#include <ucs/sys/sys.h>
#include <ucs/sys/string.h>
#include <ucs/arch/atomic.h>
}
#include <queue>
class test_uct_sockaddr : public uct_test {
public:
struct completion : public uct_completion_t {
volatile bool m_flag;
completion() : m_flag(false), m_status(UCS_INPROGRESS) {
count = 1;
func = completion_cb;
}
ucs_status_t status() const {
return m_status;
}
private:
static void completion_cb(uct_completion_t *self, ucs_status_t status)
{
completion *c = static_cast<completion*>(self);
c->m_status = status;
c->m_flag = true;
}
ucs_status_t m_status;
};
test_uct_sockaddr() : server(NULL), client(NULL), err_count(0),
server_recv_req(0), delay_conn_reply(false) {
}
void check_md_usability() {
uct_md_attr_t md_attr;
uct_md_config_t *md_config;
ucs_status_t status;
uct_md_h md;
status = uct_md_config_read(GetParam()->component, NULL, NULL, &md_config);
EXPECT_TRUE(status == UCS_OK);
status = uct_md_open(GetParam()->component, GetParam()->md_name.c_str(),
md_config, &md);
EXPECT_TRUE(status == UCS_OK);
uct_config_release(md_config);
status = uct_md_query(md, &md_attr);
ASSERT_UCS_OK(status);
uct_md_close(md);
if (!(md_attr.cap.flags & UCT_MD_FLAG_SOCKADDR)) {
UCS_TEST_SKIP_R(GetParam()->md_name.c_str() +
std::string(" does not support client-server "
"connection establishment via sockaddr "
"without a cm"));
}
}
void init() {
check_md_usability();
uct_iface_params_t server_params, client_params;
uint16_t port;
uct_test::init();
/* This address is accessible, as it was tested at the resource creation */
m_listen_addr = GetParam()->listen_sock_addr;
m_connect_addr = GetParam()->connect_sock_addr;
port = ucs::get_port();
m_listen_addr.set_port(port);
m_connect_addr.set_port(port);
/* open iface for the server side */
server_params.field_mask = UCT_IFACE_PARAM_FIELD_OPEN_MODE |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_ARG |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_FLAGS |
UCT_IFACE_PARAM_FIELD_SOCKADDR;
server_params.open_mode = UCT_IFACE_OPEN_MODE_SOCKADDR_SERVER;
server_params.err_handler = err_handler;
server_params.err_handler_arg = reinterpret_cast<void*>(this);
server_params.err_handler_flags = 0;
server_params.mode.sockaddr.listen_sockaddr = m_listen_addr.to_ucs_sock_addr();
server_params.mode.sockaddr.cb_flags = UCT_CB_FLAG_ASYNC;
server_params.mode.sockaddr.conn_request_cb = conn_request_cb;
server_params.mode.sockaddr.conn_request_arg = reinterpret_cast<void*>(this);
/* if origin port is busy, create_entity will retry with another one */
server = uct_test::create_entity(server_params);
m_entities.push_back(server);
check_skip_test();
port = ucs::sock_addr_storage(server->iface_params().mode.sockaddr
.listen_sockaddr)
.get_port();
m_listen_addr.set_port(port);
m_connect_addr.set_port(port);
/* open iface for the client side */
client_params.field_mask = UCT_IFACE_PARAM_FIELD_OPEN_MODE |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_ARG |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_FLAGS;
client_params.open_mode = UCT_IFACE_OPEN_MODE_SOCKADDR_CLIENT;
client_params.err_handler = err_handler;
client_params.err_handler_arg = reinterpret_cast<void*>(this);
client_params.err_handler_flags = 0;
client = uct_test::create_entity(client_params);
m_entities.push_back(client);
/* initiate the client's private data callback argument */
client->max_conn_priv = server->iface_attr().max_conn_priv;
UCS_TEST_MESSAGE << "Testing " << m_listen_addr
<< " Interface: " << GetParam()->dev_name;
}
static ssize_t client_iface_priv_data_cb(void *arg, const char *dev_name,
void *priv_data)
{
size_t *max_conn_priv = (size_t*)arg;
size_t priv_data_len;
priv_data_len = uct_test::entity::priv_data_do_pack(priv_data);
EXPECT_LE(priv_data_len, (*max_conn_priv));
return priv_data_len;
}
static void conn_request_cb(uct_iface_h iface, void *arg,
uct_conn_request_h conn_request,
const void *conn_priv_data, size_t length)
{
test_uct_sockaddr *self = reinterpret_cast<test_uct_sockaddr*>(arg);
EXPECT_EQ(std::string(reinterpret_cast<const char *>
(uct_test::entity::client_priv_data.c_str())),
std::string(reinterpret_cast<const char *>(conn_priv_data)));
EXPECT_EQ(1 + uct_test::entity::client_priv_data.length(), length);
if (self->delay_conn_reply) {
self->delayed_conn_reqs.push(conn_request);
} else {
uct_iface_accept(iface, conn_request);
}
ucs_memory_cpu_store_fence();
self->server_recv_req++;
}
static ucs_status_t err_handler(void *arg, uct_ep_h ep, ucs_status_t status)
{
test_uct_sockaddr *self = reinterpret_cast<test_uct_sockaddr*>(arg);
ucs_atomic_add32(&self->err_count, 1);
return UCS_OK;
}
protected:
entity *server, *client;
ucs::sock_addr_storage m_listen_addr, m_connect_addr;
volatile uint32_t err_count;
volatile int server_recv_req;
std::queue<uct_conn_request_h> delayed_conn_reqs;
bool delay_conn_reply;
};
UCS_TEST_P(test_uct_sockaddr, connect_client_to_server)
{
client->connect(0, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
/* wait for the server to connect */
while (server_recv_req == 0) {
progress();
}
ASSERT_TRUE(server_recv_req == 1);
/* since the transport may support a graceful exit in case of an error,
* make sure that the error handling flow wasn't invoked (there were no
* errors) */
EXPECT_EQ(0ul, err_count);
/* the test may end before the client's ep got connected.
* it should also pass in this case as well - the client's
* ep shouldn't be accessed (for connection reply from the server) after the
* test ends and the client's ep was destroyed */
}
UCS_TEST_P(test_uct_sockaddr, connect_client_to_server_with_delay)
{
delay_conn_reply = true;
client->connect(0, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
/* wait for the server to connect */
while (server_recv_req == 0) {
progress();
}
ASSERT_EQ(1, server_recv_req);
ucs_memory_cpu_load_fence();
ASSERT_EQ(1ul, delayed_conn_reqs.size());
EXPECT_EQ(0ul, err_count);
while (!delayed_conn_reqs.empty()) {
uct_iface_accept(server->iface(), delayed_conn_reqs.front());
delayed_conn_reqs.pop();
}
completion comp;
ucs_status_t status = uct_ep_flush(client->ep(0), 0, &comp);
if (status == UCS_INPROGRESS) {
wait_for_flag(&comp.m_flag);
EXPECT_EQ(UCS_OK, comp.status());
} else {
EXPECT_EQ(UCS_OK, status);
}
EXPECT_EQ(0ul, err_count);
}
UCS_TEST_P(test_uct_sockaddr, connect_client_to_server_reject_with_delay)
{
delay_conn_reply = true;
client->connect(0, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
/* wait for the server to connect */
while (server_recv_req == 0) {
progress();
}
ASSERT_EQ(1, server_recv_req);
ucs_memory_cpu_load_fence();
ASSERT_EQ(1ul, delayed_conn_reqs.size());
EXPECT_EQ(0ul, err_count);
while (!delayed_conn_reqs.empty()) {
uct_iface_reject(server->iface(), delayed_conn_reqs.front());
delayed_conn_reqs.pop();
}
while (err_count == 0) {
progress();
}
EXPECT_EQ(1ul, err_count);
}
UCS_TEST_P(test_uct_sockaddr, many_clients_to_one_server)
{
int num_clients = ucs_max(2, 100 / ucs::test_time_multiplier());
uct_iface_params_t client_params;
entity *client_test;
/* multiple clients, each on an iface of its own, connecting to the same server */
for (int i = 0; i < num_clients; ++i) {
/* open iface for the client side */
client_params.field_mask = UCT_IFACE_PARAM_FIELD_OPEN_MODE |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_ARG |
UCT_IFACE_PARAM_FIELD_ERR_HANDLER_FLAGS;
client_params.open_mode = UCT_IFACE_OPEN_MODE_SOCKADDR_CLIENT;
client_params.err_handler = err_handler;
client_params.err_handler_arg = reinterpret_cast<void*>(this);
client_params.err_handler_flags = 0;
client_test = uct_test::create_entity(client_params);
m_entities.push_back(client_test);
client_test->max_conn_priv = server->iface_attr().max_conn_priv;
client_test->connect(i, *server, 0, m_connect_addr,
client_iface_priv_data_cb, NULL, NULL,
&client_test->max_conn_priv);
}
while (server_recv_req < num_clients){
progress();
}
ASSERT_TRUE(server_recv_req == num_clients);
EXPECT_EQ(0ul, err_count);
}
UCS_TEST_P(test_uct_sockaddr, many_conns_on_client)
{
int num_conns_on_client = ucs_max(2, 100 / ucs::test_time_multiplier());
/* multiple clients, on the same iface, connecting to the same server */
for (int i = 0; i < num_conns_on_client; ++i) {
client->connect(i, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
}
while (server_recv_req < num_conns_on_client) {
progress();
}
ASSERT_TRUE(server_recv_req == num_conns_on_client);
EXPECT_EQ(0ul, err_count);
}
UCS_TEST_SKIP_COND_P(test_uct_sockaddr, err_handle,
!check_caps(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE))
{
client->connect(0, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
scoped_log_handler slh(wrap_errors_logger);
/* kill the server */
m_entities.remove(server);
/* If the server didn't receive a connection request from the client yet,
* test error handling */
if (server_recv_req == 0) {
wait_for_flag(&err_count);
/* Double check for server_recv_req if it's not delivered from NIC to
* host memory under hight load */
EXPECT_TRUE((err_count == 1) || (server_recv_req == 1));
}
}
UCS_TEST_SKIP_COND_P(test_uct_sockaddr, conn_to_non_exist_server,
!check_caps(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE))
{
m_connect_addr.set_port(htons(1));
err_count = 0;
/* wrap errors now since the client will try to connect to a non existing port */
{
scoped_log_handler slh(wrap_errors_logger);
/* client - try to connect to a non-existing port on the server side */
client->connect(0, *server, 0, m_connect_addr, client_iface_priv_data_cb,
NULL, NULL, &client->max_conn_priv);
completion comp;
ucs_status_t status = uct_ep_flush(client->ep(0), 0, &comp);
if (status == UCS_INPROGRESS) {
wait_for_flag(&comp.m_flag);
EXPECT_EQ(UCS_ERR_UNREACHABLE, comp.status());
} else {
EXPECT_EQ(UCS_ERR_UNREACHABLE, status);
}
/* destroy the client's ep. this ep shouldn't be accessed anymore */
client->destroy_ep(0);
}
}
UCT_INSTANTIATE_SOCKADDR_TEST_CASE(test_uct_sockaddr)
class test_uct_cm_sockaddr : public uct_test {
friend class uct_test::entity;
protected:
enum {
TEST_CM_STATE_CONNECT_REQUESTED = UCS_BIT(0),
TEST_CM_STATE_CLIENT_CONNECTED = UCS_BIT(1),
TEST_CM_STATE_SERVER_CONNECTED = UCS_BIT(2),
TEST_CM_STATE_CLIENT_DISCONNECTED = UCS_BIT(3),
TEST_CM_STATE_SERVER_DISCONNECTED = UCS_BIT(4),
TEST_CM_STATE_SERVER_REJECTED = UCS_BIT(5),
TEST_CM_STATE_CLIENT_GOT_REJECT = UCS_BIT(6),
TEST_CM_STATE_CLIENT_GOT_ERROR = UCS_BIT(7)
};
public:
test_uct_cm_sockaddr() : m_cm_state(0), m_server(NULL), m_client(NULL),
m_server_recv_req_cnt(0), m_client_connect_cb_cnt(0),
m_server_connect_cb_cnt(0),
m_server_disconnect_cnt(0), m_client_disconnect_cnt(0),
m_reject_conn_request(false),
m_server_start_disconnect(false),
m_delay_conn_reply(false) {
}
void init() {
uct_test::init();
/* This address is accessible, as it was tested at the resource creation */
m_listen_addr = GetParam()->listen_sock_addr;
m_connect_addr = GetParam()->connect_sock_addr;
uint16_t port = ucs::get_port();
m_listen_addr.set_port(port);
m_connect_addr.set_port(port);
m_server = uct_test::create_entity();
m_entities.push_back(m_server);
m_client = uct_test::create_entity();
m_entities.push_back(m_client);
/* initiate the client's private data callback argument */
m_client->max_conn_priv = m_client->cm_attr().max_conn_priv;
UCS_TEST_MESSAGE << "Testing " << m_listen_addr
<< " Interface: " << GetParam()->dev_name;
}
protected:
void skip_tcp_sockcm() {
uct_component_attr_t cmpt_attr = {0};
ucs_status_t status;
cmpt_attr.field_mask = UCT_COMPONENT_ATTR_FIELD_NAME;
/* coverity[var_deref_model] */
status = uct_component_query(GetParam()->component, &cmpt_attr);
ASSERT_UCS_OK(status);
if (!strcmp(cmpt_attr.name, "tcp")) {
UCS_TEST_SKIP_R("tcp cm is not fully implemented");
}
}
void cm_start_listen() {
uct_listener_params_t params;
params.field_mask = UCT_LISTENER_PARAM_FIELD_CONN_REQUEST_CB |
UCT_LISTENER_PARAM_FIELD_USER_DATA;
params.conn_request_cb = cm_conn_request_cb;
params.user_data = static_cast<test_uct_cm_sockaddr *>(this);
/* if origin port set in init() is busy, listen() will retry with another one */
m_server->listen(m_listen_addr, params);
/* the listen function may have changed the initial port on the listener's
* address. update this port for the address to connect to */
m_connect_addr.set_port(m_listen_addr.get_port());
}
static ssize_t client_cm_priv_data_cb(void *arg, const char *dev_name,
void *priv_data)
{
test_uct_cm_sockaddr *self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
size_t priv_data_len;
priv_data_len = uct_test::entity::priv_data_do_pack(priv_data);
EXPECT_LE(priv_data_len, self->m_client->max_conn_priv);
return priv_data_len;
}
void cm_listen_and_connect() {
skip_tcp_sockcm();
cm_start_listen();
m_client->connect(0, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
wait_for_bits(&m_cm_state, TEST_CM_STATE_CONNECT_REQUESTED);
EXPECT_TRUE(m_cm_state & TEST_CM_STATE_CONNECT_REQUESTED);
}
virtual void server_accept(entity *server, uct_conn_request_h conn_request,
uct_ep_server_connect_cb_t connect_cb,
uct_ep_disconnect_cb_t disconnect_cb,
void *user_data)
{
server->accept(server->cm(), conn_request, connect_cb, disconnect_cb,
user_data);
}
static void
cm_conn_request_cb(uct_listener_h listener, void *arg,
const char *local_dev_name,
uct_conn_request_h conn_request,
const uct_cm_remote_data_t *remote_data) {
test_uct_cm_sockaddr *self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
ucs_status_t status;
EXPECT_EQ(entity::client_priv_data.length() + 1, remote_data->conn_priv_data_length);
EXPECT_EQ(entity::client_priv_data,
std::string(static_cast<const char *>(remote_data->conn_priv_data)));
self->m_cm_state |= TEST_CM_STATE_CONNECT_REQUESTED;
if (self->m_delay_conn_reply) {
self->m_delayed_conn_reqs.push(conn_request);
} else if (self->m_reject_conn_request) {
status = uct_listener_reject(listener, conn_request);
ASSERT_UCS_OK(status);
self->m_cm_state |= TEST_CM_STATE_SERVER_REJECTED;
} else {
self->server_accept(self->m_server, conn_request,
server_connect_cb, server_disconnect_cb, self);
}
ucs_memory_cpu_store_fence();
self->m_server_recv_req_cnt++;
}
static void
server_connect_cb(uct_ep_h ep, void *arg, ucs_status_t status) {
test_uct_cm_sockaddr *self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
EXPECT_EQ(UCS_OK, status);
self->m_cm_state |= TEST_CM_STATE_SERVER_CONNECTED;
self->m_server_connect_cb_cnt++;
}
static void
server_disconnect_cb(uct_ep_h ep, void *arg) {
test_uct_cm_sockaddr *self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
if (!(self->m_server_start_disconnect)) {
self->m_server->disconnect(ep);
}
self->m_cm_state |= TEST_CM_STATE_SERVER_DISCONNECTED;
self->m_server_disconnect_cnt++;
}
static void
client_connect_cb(uct_ep_h ep, void *arg,
const uct_cm_remote_data_t *remote_data,
ucs_status_t status) {
test_uct_cm_sockaddr *self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
if (status == UCS_ERR_REJECTED) {
self->m_cm_state |= TEST_CM_STATE_CLIENT_GOT_REJECT;
} else if (status != UCS_OK) {
self->m_cm_state |= TEST_CM_STATE_CLIENT_GOT_ERROR;
} else {
EXPECT_TRUE(ucs_test_all_flags(remote_data->field_mask,
(UCT_CM_REMOTE_DATA_FIELD_CONN_PRIV_DATA_LENGTH |
UCT_CM_REMOTE_DATA_FIELD_CONN_PRIV_DATA)));
EXPECT_EQ(entity::server_priv_data.length() + 1, remote_data->conn_priv_data_length);
EXPECT_EQ(entity::server_priv_data,
std::string(static_cast<const char *>(remote_data->conn_priv_data)));
self->m_cm_state |= TEST_CM_STATE_CLIENT_CONNECTED;
self->m_client_connect_cb_cnt++;
}
}
static void
client_disconnect_cb(uct_ep_h ep, void *arg) {
test_uct_cm_sockaddr *self;
self = reinterpret_cast<test_uct_cm_sockaddr *>(arg);
if (self->m_server_start_disconnect) {
/* if the server was the one who initiated the disconnect flow,
* the client should also disconnect its ep from the server in
* its disconnect cb */
self->m_client->disconnect(ep);
}
self->m_cm_state |= TEST_CM_STATE_CLIENT_DISCONNECTED;
self->m_client_disconnect_cnt++;
}
void cm_disconnect(entity *ent) {
size_t i;
/* Disconnect all the existing endpoints */
for (i = 0; i < ent->num_eps(); ++i) {
ent->disconnect(ent->ep(i));
}
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_DISCONNECTED |
TEST_CM_STATE_SERVER_DISCONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_DISCONNECTED |
TEST_CM_STATE_CLIENT_DISCONNECTED)));
}
void wait_for_client_server_counters(volatile int *server_cnt,
volatile int *client_cnt, int val,
double timeout = 10 * DEFAULT_TIMEOUT_SEC) {
ucs_time_t deadline;
deadline = ucs_get_time() + ucs_time_from_sec(timeout) *
ucs::test_time_multiplier();
while (((*server_cnt < val) || (*client_cnt < val)) &&
(ucs_get_time() < deadline)) {
progress();
}
}
void test_delayed_server_response(bool reject)
{
ucs_status_t status;
ucs_time_t deadline;
m_delay_conn_reply = true;
cm_listen_and_connect();
EXPECT_FALSE(m_cm_state &
(TEST_CM_STATE_SERVER_CONNECTED | TEST_CM_STATE_CLIENT_CONNECTED |
TEST_CM_STATE_CLIENT_GOT_REJECT | TEST_CM_STATE_CLIENT_GOT_ERROR));
deadline = ucs_get_time() + ucs_time_from_sec(DEFAULT_TIMEOUT_SEC) *
ucs::test_time_multiplier();
while ((m_server_recv_req_cnt == 0) && (ucs_get_time() < deadline)) {
progress();
}
ASSERT_EQ(1, m_server_recv_req_cnt);
ucs_memory_cpu_load_fence();
if (reject) {
/* wrap errors since a reject is expected */
scoped_log_handler slh(detect_reject_error_logger);
status = uct_listener_reject(m_server->listener(),
m_delayed_conn_reqs.front());
ASSERT_UCS_OK(status);
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_GOT_REJECT);
EXPECT_TRUE(m_cm_state & TEST_CM_STATE_CLIENT_GOT_REJECT);
} else {
server_accept(m_server, m_delayed_conn_reqs.front(),
server_connect_cb, server_disconnect_cb, this);
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED));
}
m_delayed_conn_reqs.pop();
}
static ucs_log_func_rc_t
detect_addr_route_error_logger(const char *file, unsigned line, const char *function,
ucs_log_level_t level, const char *message, va_list ap)
{
if (level == UCS_LOG_LEVEL_ERROR) {
std::string err_str = format_message(message, ap);
if ((strstr(err_str.c_str(), "client: got error event RDMA_CM_EVENT_ADDR_ERROR")) ||
(strstr(err_str.c_str(), "client: got error event RDMA_CM_EVENT_ROUTE_ERROR")) ||
(strstr(err_str.c_str(), "rdma_resolve_route(to addr=240.0.0.0"))) {
UCS_TEST_MESSAGE << err_str;
return UCS_LOG_FUNC_RC_STOP;
}
}
return UCS_LOG_FUNC_RC_CONTINUE;
}
static ucs_log_func_rc_t
detect_reject_error_logger(const char *file, unsigned line, const char *function,
ucs_log_level_t level, const char *message, va_list ap)
{
if (level == UCS_LOG_LEVEL_ERROR) {
std::string err_str = format_message(message, ap);
if (strstr(err_str.c_str(), "client: got error event RDMA_CM_EVENT_REJECTED")) {
UCS_TEST_MESSAGE << err_str;
return UCS_LOG_FUNC_RC_STOP;
}
}
return UCS_LOG_FUNC_RC_CONTINUE;
}
static ucs_log_func_rc_t
detect_double_disconnect_error_logger(const char *file, unsigned line,
const char *function, ucs_log_level_t level,
const char *message, va_list ap)
{
if (level == UCS_LOG_LEVEL_ERROR) {
std::string err_str = format_message(message, ap);
if (err_str.find("duplicate call of uct_ep_disconnect") !=
std::string::npos) {
UCS_TEST_MESSAGE << err_str;
return UCS_LOG_FUNC_RC_STOP;
}
}
return UCS_LOG_FUNC_RC_CONTINUE;
}
protected:
ucs::sock_addr_storage m_listen_addr, m_connect_addr;
uint64_t m_cm_state;
entity *m_server;
entity *m_client;
volatile int m_server_recv_req_cnt, m_client_connect_cb_cnt,
m_server_connect_cb_cnt;
volatile int m_server_disconnect_cnt, m_client_disconnect_cnt;
bool m_reject_conn_request;
bool m_server_start_disconnect;
bool m_delay_conn_reply;
std::queue<uct_conn_request_h> m_delayed_conn_reqs;
};
UCS_TEST_P(test_uct_cm_sockaddr, cm_query)
{
ucs_status_t status;
size_t i;
for (i = 0; i < m_entities.size(); ++i) {
uct_cm_attr_t attr;
attr.field_mask = UCT_CM_ATTR_FIELD_MAX_CONN_PRIV;
status = uct_cm_query(m_entities.at(i).cm(), &attr);
ASSERT_UCS_OK(status);
EXPECT_LT(0ul, attr.max_conn_priv);
}
}
UCS_TEST_P(test_uct_cm_sockaddr, listener_query)
{
uct_listener_attr_t attr;
ucs_status_t status;
uint16_t port;
char m_listener_ip_port_str[UCS_SOCKADDR_STRING_LEN];
char attr_addr_ip_port_str[UCS_SOCKADDR_STRING_LEN];
cm_start_listen();
attr.field_mask = UCT_LISTENER_ATTR_FIELD_SOCKADDR;
status = uct_listener_query(m_server->listener(), &attr);
ASSERT_UCS_OK(status);
ucs_sockaddr_str(m_listen_addr.get_sock_addr_ptr(), m_listener_ip_port_str,
UCS_SOCKADDR_STRING_LEN);
ucs_sockaddr_str((struct sockaddr*)&attr.sockaddr, attr_addr_ip_port_str,
UCS_SOCKADDR_STRING_LEN);
EXPECT_EQ(strcmp(m_listener_ip_port_str, attr_addr_ip_port_str), 0);
status = ucs_sockaddr_get_port((struct sockaddr*)&attr.sockaddr, &port);
ASSERT_UCS_OK(status);
EXPECT_EQ(m_listen_addr.get_port(), port);
}
UCS_TEST_P(test_uct_cm_sockaddr, cm_open_listen_close)
{
cm_listen_and_connect();
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED)));
cm_disconnect(m_client);
}
UCS_TEST_P(test_uct_cm_sockaddr, cm_open_listen_kill_server)
{
cm_listen_and_connect();
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED)));
EXPECT_EQ(1ul, m_entities.remove(m_server));
m_server = NULL;
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_DISCONNECTED);
EXPECT_TRUE(m_cm_state & TEST_CM_STATE_CLIENT_DISCONNECTED);
}
UCS_TEST_P(test_uct_cm_sockaddr, cm_server_reject)
{
m_reject_conn_request = true;
/* wrap errors since a reject is expected */
scoped_log_handler slh(detect_reject_error_logger);
cm_listen_and_connect();
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_REJECTED |
TEST_CM_STATE_CLIENT_GOT_REJECT);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_REJECTED |
TEST_CM_STATE_CLIENT_GOT_REJECT)));
EXPECT_FALSE((m_cm_state &
(TEST_CM_STATE_SERVER_CONNECTED | TEST_CM_STATE_CLIENT_CONNECTED)));
}
UCS_TEST_P(test_uct_cm_sockaddr, many_clients_to_one_server)
{
int num_clients = ucs_max(2, 100 / ucs::test_time_multiplier());;
entity *client_test;
skip_tcp_sockcm();
/* Listen */
cm_start_listen();
/* Connect */
/* multiple clients, each on a cm of its own, connecting to the same server */
for (int i = 0; i < num_clients; ++i) {
client_test = uct_test::create_entity();
m_entities.push_back(client_test);
client_test->max_conn_priv = client_test->cm_attr().max_conn_priv;
client_test->connect(0, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
}
/* wait for the server to connect to all the clients */
wait_for_client_server_counters(&m_server_connect_cb_cnt,
&m_client_connect_cb_cnt, num_clients);
EXPECT_EQ(num_clients, m_server_recv_req_cnt);
EXPECT_EQ(num_clients, m_client_connect_cb_cnt);
EXPECT_EQ(num_clients, m_server_connect_cb_cnt);
EXPECT_EQ(num_clients, (int)m_server->num_eps());
/* Disconnect */
for (int i = 0; i < num_clients; ++i) {
/* first 2 entities are m_server and m_client */
client_test = &m_entities.at(2 + i);
ASSERT_TRUE(client_test != m_client);
cm_disconnect(client_test);
}
/* don't remove the ep, i.e. don't call uct_ep_destroy on the client's ep,
* before the client finished disconnecting so that a disconnect event won't
* arrive on a destroyed endpoint on the client side */
wait_for_client_server_counters(&m_server_disconnect_cnt,
&m_client_disconnect_cnt, num_clients);
EXPECT_EQ(num_clients, m_server_disconnect_cnt);
EXPECT_EQ(num_clients, m_client_disconnect_cnt);
for (int i = 0; i < num_clients; ++i) {
client_test = m_entities.back();
m_entities.remove(client_test);
}
}
UCS_TEST_P(test_uct_cm_sockaddr, many_conns_on_client)
{
int num_conns_on_client = ucs_max(2, 100 / ucs::test_time_multiplier());
m_server_start_disconnect = true;
skip_tcp_sockcm();
/* Listen */
cm_start_listen();
/* Connect */
/* multiple clients, on the same cm, connecting to the same server */
for (int i = 0; i < num_conns_on_client; ++i) {
m_client->connect(i, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
}
/* wait for the server to connect to all the endpoints on the cm */
wait_for_client_server_counters(&m_server_connect_cb_cnt,
&m_client_connect_cb_cnt,
num_conns_on_client);
EXPECT_EQ(num_conns_on_client, m_server_recv_req_cnt);
EXPECT_EQ(num_conns_on_client, m_client_connect_cb_cnt);
EXPECT_EQ(num_conns_on_client, m_server_connect_cb_cnt);
EXPECT_EQ(num_conns_on_client, (int)m_client->num_eps());
EXPECT_EQ(num_conns_on_client, (int)m_server->num_eps());
/* Disconnect */
cm_disconnect(m_server);
/* wait for disconnect to complete */
wait_for_client_server_counters(&m_server_disconnect_cnt,
&m_client_disconnect_cnt,
num_conns_on_client);
EXPECT_EQ(num_conns_on_client, m_server_disconnect_cnt);
EXPECT_EQ(num_conns_on_client, m_client_disconnect_cnt);
}
UCS_TEST_P(test_uct_cm_sockaddr, err_handle)
{
skip_tcp_sockcm();
/* wrap errors since a reject is expected */
scoped_log_handler slh(detect_reject_error_logger);
/* client - try to connect to a server that isn't listening */
m_client->connect(0, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
EXPECT_FALSE(m_cm_state & TEST_CM_STATE_CONNECT_REQUESTED);
/* with the TCP port space (which is currently tested with rdmacm),
* in this case, a REJECT event will be generated on the client side */
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_GOT_REJECT);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, TEST_CM_STATE_CLIENT_GOT_REJECT));
}
UCS_TEST_P(test_uct_cm_sockaddr, conn_to_non_exist_server_port)
{
skip_tcp_sockcm();
/* Listen */
cm_start_listen();
m_connect_addr.set_port(htons(1));
/* wrap errors since a reject is expected */
scoped_log_handler slh(detect_reject_error_logger);
/* client - try to connect to a non-existing port on the server side. */
m_client->connect(0, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
/* with the TCP port space (which is currently tested with rdmacm),
* in this case, a REJECT event will be generated on the client side */
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_GOT_REJECT);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, TEST_CM_STATE_CLIENT_GOT_REJECT));
}
UCS_TEST_P(test_uct_cm_sockaddr, conn_to_non_exist_ip)
{
struct sockaddr_in addr;
ucs_status_t status;
size_t size;
skip_tcp_sockcm();
/* Listen */
cm_start_listen();
/* 240.0.0.0/4 - This block, formerly known as the Class E address
space, is reserved for future use; see [RFC1112], Section 4.
therefore, this value can be used as a non-existing IP for this test */
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("240.0.0.0");
addr.sin_port = m_listen_addr.get_port();
status = ucs_sockaddr_sizeof((struct sockaddr*)&addr, &size);
ASSERT_UCS_OK(status);
m_connect_addr.set_sock_addr(*(struct sockaddr*)&addr, size);
/* wrap errors now since the client will try to connect to a non existing IP */
{
scoped_log_handler slh(detect_addr_route_error_logger);
/* client - try to connect to a non-existing IP */
m_client->connect(0, *m_server, 0, m_connect_addr, client_cm_priv_data_cb,
client_connect_cb, client_disconnect_cb, this);
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_GOT_ERROR);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, TEST_CM_STATE_CLIENT_GOT_ERROR));
EXPECT_FALSE(m_cm_state & TEST_CM_STATE_CONNECT_REQUESTED);
EXPECT_FALSE(m_cm_state &
(TEST_CM_STATE_SERVER_CONNECTED | TEST_CM_STATE_CLIENT_CONNECTED));
}
}
UCS_TEST_P(test_uct_cm_sockaddr, connect_client_to_server_with_delay)
{
test_delayed_server_response(false);
cm_disconnect(m_client);
}
UCS_TEST_P(test_uct_cm_sockaddr, connect_client_to_server_reject_with_delay)
{
test_delayed_server_response(true);
}
UCS_TEST_P(test_uct_cm_sockaddr, ep_disconnect_err_codes)
{
bool disconnecting = false;
cm_listen_and_connect();
{
entity::scoped_async_lock lock(*m_client);
if (m_cm_state & TEST_CM_STATE_CLIENT_CONNECTED) {
UCS_TEST_MESSAGE << "EXP: " << ucs_status_string(UCS_OK);
EXPECT_EQ(UCS_OK, uct_ep_disconnect(m_client->ep(0), 0));
disconnecting = true;
} else {
UCS_TEST_MESSAGE << "EXP: " << ucs_status_string(UCS_ERR_BUSY);
EXPECT_EQ(UCS_ERR_BUSY, uct_ep_disconnect(m_client->ep(0), 0));
}
}
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED)));
{
entity::scoped_async_lock lock(*m_client);
if (disconnecting) {
scoped_log_handler slh(detect_double_disconnect_error_logger);
if (m_cm_state & TEST_CM_STATE_CLIENT_DISCONNECTED) {
UCS_TEST_MESSAGE << "EXP: "
<< ucs_status_string(UCS_ERR_NOT_CONNECTED);
EXPECT_EQ(UCS_ERR_NOT_CONNECTED,
uct_ep_disconnect(m_client->ep(0), 0));
} else {
UCS_TEST_MESSAGE << "EXP: "
<< ucs_status_string(UCS_INPROGRESS);
EXPECT_EQ(UCS_INPROGRESS,
uct_ep_disconnect(m_client->ep(0), 0));
}
} else {
UCS_TEST_MESSAGE << "EXP: " << ucs_status_string(UCS_OK);
ASSERT_UCS_OK(uct_ep_disconnect(m_client->ep(0), 0));
disconnecting = true;
}
}
ASSERT_TRUE(disconnecting);
wait_for_bits(&m_cm_state, TEST_CM_STATE_CLIENT_DISCONNECTED);
EXPECT_TRUE(m_cm_state & TEST_CM_STATE_CLIENT_DISCONNECTED);
/* wrap errors since the client will call uct_ep_disconnect the second time
* on the same endpoint. this ep may not be disconnected yet */
{
scoped_log_handler slh(detect_double_disconnect_error_logger);
UCS_TEST_MESSAGE << "EXP: " << ucs_status_string(UCS_ERR_NOT_CONNECTED);
EXPECT_EQ(UCS_ERR_NOT_CONNECTED, uct_ep_disconnect(m_client->ep(0), 0));
}
}
UCT_INSTANTIATE_SOCKADDR_TEST_CASE(test_uct_cm_sockaddr)
class test_uct_cm_sockaddr_multiple_cms : public test_uct_cm_sockaddr {
public:
void init() {
ucs_status_t status;
test_uct_cm_sockaddr::init();
status = ucs_async_context_create(UCS_ASYNC_MODE_THREAD_SPINLOCK,
&m_test_async);
ASSERT_UCS_OK(status);
status = uct_cm_config_read(GetParam()->component, NULL, NULL, &m_test_config);
ASSERT_UCS_OK(status);
UCS_TEST_CREATE_HANDLE(uct_worker_h, m_test_worker, uct_worker_destroy,
uct_worker_create, m_test_async,
UCS_THREAD_MODE_SINGLE)
UCS_TEST_CREATE_HANDLE(uct_cm_h, m_test_cm, uct_cm_close,
uct_cm_open, GetParam()->component,
m_test_worker, m_test_config);
}
void cleanup() {
m_test_cm.reset();
uct_config_release(m_test_config);
m_test_worker.reset();
ucs_async_context_destroy(m_test_async);
test_uct_cm_sockaddr::cleanup();
}
void server_accept(entity *server, uct_conn_request_h conn_request,
uct_ep_server_connect_cb_t connect_cb,
uct_ep_disconnect_cb_t disconnect_cb,
void *user_data)
{
server->accept(m_test_cm, conn_request, connect_cb, disconnect_cb,
user_data);
}
protected:
ucs::handle<uct_worker_h> m_test_worker;
ucs::handle<uct_cm_h> m_test_cm;
ucs_async_context_t *m_test_async;
uct_cm_config_t *m_test_config;
};
UCS_TEST_P(test_uct_cm_sockaddr_multiple_cms, server_switch_cm)
{
cm_listen_and_connect();
wait_for_bits(&m_cm_state, TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED);
EXPECT_TRUE(ucs_test_all_flags(m_cm_state, (TEST_CM_STATE_SERVER_CONNECTED |
TEST_CM_STATE_CLIENT_CONNECTED)));
cm_disconnect(m_client);
/* destroy the server's ep here so that it would be destroyed before the cm
* it is using */
m_server->destroy_ep(0);
}
UCT_INSTANTIATE_SOCKADDR_TEST_CASE(test_uct_cm_sockaddr_multiple_cms)
|
//#include "names.hpp"
#include "world.hpp"
unsigned Identifiable::nextID = 0;
void connectIslands(Island* a, Island* b) {
a->addNeighbour(b);
b->addNeighbour(a);
}
BattleSide* getBattleSideFromFaction(std::list<BattleSide>& sides, Faction* faction) {
if(faction == NULL) {
std::cerr << "Error in getBattleSideFromFaction(): NULL pointer given as faction argument!\n";
return NULL;
}
for( auto it = sides.begin(); it != sides.end(); it++ ) {
if( (*it).owner == faction ) {
return &(*it);
}
}
std::cerr << "Error in getBattleSideFromFaction(): No faction '" << faction->getName() << "'was among battleSides\n";
return NULL;
}
Island* Island::searchNextNeighbour(IslandList blackList, bool adjacent, bool following, bool previous) {
for(IslandIterator it = linkedIslands.begin(); it != linkedIslands.end(); it++) {
//not on a black list to this search
bool onBlackList = false;
for(IslandIterator ct = blackList.begin(); ct != blackList.end(); ct++ ) {
if(*ct == *it) {
onBlackList = true;
break;
}
}
if(onBlackList) {
continue;
}
if(adjacent) {
if((*it)->getRimNumber() == rimNumber) {
return *it;
}
}
if(following) {
if((*it)->getRimNumber() == rimNumber+1) {
return *it;
}
}
if(previous) {
if((*it)->getRimNumber() == rimNumber-1) {
return *it;
}
}
}
return NULL;
}
Island* Rim::getNextIsland(unsigned connectionsAmount) {
for(std::list<Island>::iterator it = islands.begin(); it != islands.end(); it++) {
if( (*it).getLinkedIslands().size() != connectionsAmount ) {
continue;
}
return &*it;
}
return NULL;
}
void Rim::debugPrint() {
std::cout << getName() << " has " << islands.size() << " islands. They are listed below with neighbour information.\n";
for(std::list<Island>::iterator it = islands.begin(); it != islands.end(); it++) {
IslandList neighbourList = (*it).getLinkedIslands();
std::cout << "Island '" << (*it).getName() << "' has ";
for(IslandIterator ct = neighbourList.begin(); ct != neighbourList.end(); ct++) {
std::cout << "'" << (*ct)->getName() << "' ";
}
std::cout << " as it's neighbours and it belongs to ";
if( (*it).getOwner() == NULL) {
std::cout << "no one.\n";
}
else {
std::cout << (*it).getOwner()->getName() << ".\n";
}
}
}
void Rim::setAdjacentIslands() {
if (islands.size() < 2) {
return;
}
//std::cout << "setting adjacent islands\n";
std::list<Island>::iterator startIterator = islands.begin();
//std::cout << "This rim has " << islands.size() << " islands!\n";
//previousIsland is the first and currentIsland the second island in the list
Island* previousIsland = &*startIterator;
startIterator++;
Island* currentIsland = &*startIterator;
startIterator--;
connectIslands(currentIsland, previousIsland);
if(islands.size() == 2) {
return;
}
while(true) {
previousIsland = currentIsland;
currentIsland = getNextIsland(0);
if( currentIsland == NULL) {
break;
}
connectIslands(previousIsland, currentIsland);
}
//std::cout << "last island being inserted!\n";
connectIslands(previousIsland, &*startIterator);
//std::cout << "adjacent islands set\n";
}
void World::setFollowingRims() {
//this for loop covers all except the first rim and the nuke island rim, which will be handled seperately.
std::list<Rim>::iterator curr = rims.begin();
curr++;
std::list<Rim>::iterator prev = rims.begin();
std::list<Rim>::iterator next = rims.begin();
next++;
next++;
std::list<Rim>::iterator lastRim = rims.end();
lastRim--;
//iterate rims
for(; curr != lastRim; curr++) {
//std::cout << "new rim\n";
//get ratios for islands of the previous and next rims of the current rim
float previousToCurrentRatio = ((float)(*prev).islands.size())/((float)(*curr).islands.size());
//float currentToNextRatio = ((float)(*curr).islands.size())/((float)(*next).islands.size());
//std::cout << "previousToCurrentRatio: " << previousToCurrentRatio << "\n"; //<< "\ncurrentToNextRatio " << currentToNextRatio << "\n";
///int currIslandAmount = (float)(*curr).islands.size();
//int nextIslandAmount = (float)(*next).islands.size();
///int prevIslandAmount = (float)(*prev).islands.size();
//std::list<Island>::iterator nt = (*next).islands.begin();
//std::list<Island>::iterator pt = (*prev).islands.begin();
//std::list<Island>::iterator ct1 = (*curr).islands.begin();
//std::list<Island>::iterator ct2 = (*curr).islands.begin();
std::list<Island>::iterator pt = (*prev).islands.begin();
//std::list<Island>::iterator nt = (*next).islands.begin();
float prevCounter = 0.0f;
//float nextCounter = 0.0f;
//connect islands
for(std::list<Island>::iterator it = (*curr).islands.begin(); it != (*curr).islands.end(); it++) {
//float prevCounter = 0.0f;
//float nextCounter = 0.0f;
//float currCounter2 = 0.0f;
//std::cout << "Iterating island\n";
if( previousToCurrentRatio >= 1.0f) {
int swapper = 1;
//std::cout << "previousToCurrentRatio >= 1.0f\n";
for(float aprevCounter = previousToCurrentRatio; aprevCounter > 0; aprevCounter-=1.0f) {
//std::cout << "connected '" << (*it).getName() << "' to '" << (*pt).getName() << "'\n";
connectIslands(&*it, &*pt);
//concerns a special case of 12 islands on the previous rim and 8 islands on current rim
if(previousToCurrentRatio == 1.5f) {
if( swapper > 0) {
swapper*=-1;
pt++;
}
}
else {
pt++;
}
}
}
else {
//std::cout << "previousToCurrentRatio < 1.0f\n";
prevCounter+=previousToCurrentRatio;
//std::cout << "connected '" << (*it).getName() << "' to '" << (*pt).getName() << "'\n";
connectIslands(&*it, &*pt);
if(prevCounter >= 0.999) {
pt++;
prevCounter = 0.0f;
}
}
}
next++;
prev++;
}
//now connecting the final rim into the middle nuclear island
std::list<Rim>::iterator nukeRim = lastRim;
lastRim--;
for(std::list<Island>::iterator it = (*lastRim).islands.begin(); it != (*lastRim).islands.end(); it++) {
connectIslands(&(*it), &(*(*nukeRim).islands.begin()));
}
//std::cout << "--------------------------------------After following connecting rim status is:----------------------------------------\n";
//debugPrint();
}
void World::peaceTreaty(Faction* a, Faction* b) {
if( a->isAllyOf(b) || b->isAllyOf(a) ) {
std::cerr << "Error in World::peaceTreaty(): Factions '" << a->getName() << "' and '" << b->getName() << "' were already allies\n";
return;
}
a->addAlly(b);
b->addAlly(a);
}
void World::setWar(Faction* a, Faction* b) {
if( !a->isAllyOf(b) || !b->isAllyOf(a) ) {
//actually, it is better for the function to just return instead of an error message
//std::cerr << "Error in World::declareWar(): factions '" << a->getName() << "' and '" << b->getName() << "' were at war to begin with.\n";
return;
}
a->removeAlly(b);
b->removeAlly(a);
}
bool World::isDeclaringWar(Faction* subject, Faction* object) {
for(auto it = warDeclarations.begin(); it != warDeclarations.end(); it++) {
if( (*it).first == subject && (*it).second == object ) {
return true;
}
}
return false;
}
void World::handleDiplomacy() {
auto ct = treatyRequests.begin();
ct++;
//function will compare every treatyRequest with the other once, and if the two requests
//are a pair in a way that they are two factions requesting each other for treaty, a peace treaty will be made
for( auto it = treatyRequests.begin(); it != treatyRequests.end(); it++ ) {
for(; ct != treatyRequests.end(); ct++) {
if( ( (*it).first == (*ct).second && (*ct).first == (*it).second ) || ( (*ct).first == (*it).second && (*it).first == (*ct).second ) ) {
peaceTreaty( (*it).first, (*it).second );
it = treatyRequests.erase(it);
ct = treatyRequests.erase(ct);
}
}
}
for( auto it = warDeclarations.begin(); it != warDeclarations.end(); it++ ) {
setWar((*it).first, (*it).second);
it = warDeclarations.erase(it);
}
}
std::string World::startWorld(unsigned _rimAmount, int islandness, int _falloutTime, float _baseRegimentSupply, float _baseBattleshipSupply,
unsigned _spyAmount, int _regimentRecoveryRate, int _shipRecoveryRate, std::string worldName, float _turnTimeInterval) {
if(!unstarted) {
return MSG::WORLD_ALREADY_STARTED;
}
std::list<Faction*> factionsPointerList;
turn = 1;
turnTimeInterval = sf::seconds(_turnTimeInterval);
turnEndTime = turnTimeInterval;
turnTimer.restart();
int rimIslandAdditionValues[_rimAmount];
for(unsigned i = 0; i < _rimAmount; i++) {
rimIslandAdditionValues[i] = random(islandness);
//std::cout << "rim " << i << " has " << rimIslandAdditionValues[i] << " as it's island multiplier value\n";
}
//initializing World data
setName(worldName);
//create pointer list for rims to use
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
//factions.push_back(Faction(factionNames[i]));
factionsPointerList.push_back(&(*it));
}
playerAmount = factions.size();
unverifiedFactions.clear();
rimAmount = _rimAmount+1;
falloutTime = _falloutTime;
baseRegimentSupply = _baseRegimentSupply;
baseBattleshipSupply = _baseBattleshipSupply;
spyAmount = _spyAmount;
regimentRecoveryRate = _regimentRecoveryRate;
shipRecoveryRate = _shipRecoveryRate;
unstarted = false;
//creating Rims and islands for world according to function parameters
Rim baseRim = Rim(playerAmount, factionsPointerList, 0, 1, 1, &islandNames);
baseRim.setDefaultName();
rims.push_back(baseRim);
//int lastAmountOfIslands = _playerAmount;
//int islandAmount = lastAmountOfIslands;
//std::cout << "First rim pushed!\n";
for(unsigned i = 1; i < _rimAmount; i++) {
int islandAmount = rimIslandAdditionValues[i]*playerAmount;
Rim newRim = Rim(islandAmount, factionsPointerList, 0, 0, i+1, &islandNames);
newRim.setDefaultName();
rims.push_back(newRim);
//std::cout << "Iterable rim pushed!\n";
}
Rim nukeRim = Rim(1, factionsPointerList, 1, 0, _rimAmount+1, &islandNames);
nukeRim.setDefaultName();
rims.push_back(nukeRim);
//std::cout << "Nuke rim pushed!\n";
setAdjacentRims();
//std::cout << "Adjacent rims Set!\n";
setFollowingRims();
//std::cout << "Following rims Set!\n";
setStartingTroops();
return "";
}
void World::setStartingTroops() {
std::list<Rim>::iterator rim1 = rims.begin();
std::list<Faction>::iterator fa = factions.begin();
//conquer one island for every faction in rim 1
for(std::list<Island>::iterator it = (*rim1).islands.begin(); it != (*rim1).islands.end(); it++) {
if(fa == factions.end()) {
std::cerr << "in setStartingTroops(): Differing amount of factions and rim 1 islands!\n";
return;
}
(*fa).baseIsland = &(*it);
//for(unsigned i = 0; i < startRegimentAmount; i++) {
(*it).addTroops(startBattleshipAmount, startRegimentAmount, spyAmount, &(*fa));
(*it).attemptClaim(& (*fa));
fa++;
}
}
void World::setAdjacentRims() {
std::list<Rim>::iterator it = rims.begin();
it++;
for(; it != rims.end(); it++) {
//std::cout << "iterating rim islands for adjacent placement!\n";
(*it).setAdjacentIslands();
}
}
void World::debugPrint() {
std::cout << "World '" << getName() << "' has " << rims.size() << " rims. Their contents are listed below:\n";
for(std::list<Rim>::iterator it = rims.begin(); it != rims.end(); it++) {
(*it).debugPrint();
}
std::cout << "\n***FACTION TROOP INFORMATION***\n";
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
(*it).printTroopData();
}
std::cout << "\n***FACTION DIPLOMACY INFORMATION***\nPending war declarations:\n";
for(auto it = warDeclarations.begin(); it != warDeclarations.end(); it++) {
std::cout << (*it).first->getName() << " is declaring war on " << (*it).second->getName() << ".\n";
}
std::cout << "\nPending peace treaty requests:\n";
for(auto it = treatyRequests.begin(); it != treatyRequests.end(); it++) {
std::cout << (*it).first->getName() << " wants to sign peace with " << (*it).second->getName() << ".\n";
}
std::cout << "\nAlliances:\n";
for(auto it = factions.begin(); it != factions.end(); it++) {
for( auto ct = factions.begin(); ct != factions.end(); ct++ ) {
if(/*!actually, might be good to leave this commented for debugging purposes. If faction thinks it's allied with itself
it's good to know that something is wrong in the code !it != ct && */
(*it).isAllyOf((&*ct))) {
std::cout << (*it).getName() << " is allied with " << (*ct).getName() << "\n";
}
}
}
}
void Faction::printTroopData() {
std::cout << getName() << " troops:\n";
//print regiment data
std::cout << "--regiments--\n";
for(std::list<Regiment>::iterator it = regiments.begin(); it != regiments.end(); it++) {
std::cout << (*it).getName() << "(" << (*it).condition << "/" << MAX_CONDITION << ")" << " is on island " << (*(*it).getPosition()).getName();
if( ((*it).getPosition()) != ((*it).getTarget()) && ((*it).getTarget()) != NULL ) { std::cout << " and is heading towards " << (*(*it).getTarget()).getName(); }
std::cout << "\n";
}
std::cout << "--battleships--\n";
for(std::list<Battleship>::iterator it = battleships.begin(); it != battleships.end(); it++) {
std::cout << (*it).getName() << "(" << (*it).condition << "/" << MAX_CONDITION << ")" << " is at island " << (*(*it).getPosition()).getName();
if( ((*it).getPosition()) != ((*it).getTarget()) && ((*it).getTarget()) != NULL ) { std::cout << " and is heading towards " << (*(*it).getTarget()).getName(); }
std::cout << "\n";
}
std::cout << "--spies--\n";
for(std::list<Spy>::iterator it = spies.begin(); it != spies.end(); it++) {
std::cout << (*it).getName() << " is on island " << (*(*it).getPosition()).getName();
if( ((*it).getPosition()) != ((*it).getTarget()) && ((*it).getTarget()) != NULL ) { std::cout << " and is heading towards " << (*(*it).getTarget()).getName(); }
std::cout << "\n";
}
}
std::string World::addTreatyRequest(Faction* subject, Faction* object) {
//first check for null pointers and return an appropriate error message if found
if(subject == NULL || object == NULL) {
return MSG::INVALID_FACTION;
}
//check if such treatyRequest already exists.
for( auto it = treatyRequests.begin(); it != treatyRequests.end(); it++ ) {
if((*it).first == subject && (*it).second == object) {
return MSG::TREATY_ALREADY_REQUESTED_WITH_THIS_FACTION;
}
}
treatyRequests.push_back(std::pair<Faction*, Faction*>(subject, object));
return "";
}
Regiment* World::getRegimentFromName(std::string regimentName) {
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for(std::list<Regiment>::iterator ct = (*it).regiments.begin(); ct != (*it).regiments.end(); ct++) {
if((*ct).getName() == regimentName) {
return &(*ct);
}
}
}
//std::cerr << "Such regiment was not found, returning NULL!\n";
return NULL;
}
Faction* World::getFactionFromName(std::string factionName) {
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
if((*it).getName() == factionName) {
return &(*it);
}
}
//std::cerr << "Such regiment was not found, returning NULL!\n";
return NULL;
}
Battleship* World::getBattleshipFromName(std::string battleshipName) {
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for(std::list<Battleship>::iterator ct = (*it).battleships.begin(); ct != (*it).battleships.end(); ct++) {
if((*ct).getName() == battleshipName) {
return &(*ct);
}
}
}
return NULL;
}
Spy* World::getSpyFromName(std::string spyName) {
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for(std::list<Spy>::iterator ct = (*it).spies.begin(); ct != (*it).spies.end(); ct++) {
if((*ct).getName() == spyName) {
return &(*ct);
}
}
}
return NULL;
}
std::string World::moveTroop(std::string factionCode, std::vector<std::string> arguments) {
//argument[0] is the unit name and argument[1] is the target island name
if(arguments.size() != 2) {
std::cerr << "Error in World::moveTroop(): wrong amount of arguments given to command 'move'\n";
return MSG::INVALID_AMOUNT_OF_ARGUMENTS_IN_COMMAND;
}
Faction* troopFaction = getFactionFromCode(factionCode);
if(troopFaction == NULL) {
std::cerr << "Error in World::moveTroop(): getFactionCode() returned NULL\n";
}
if(!troopFaction) {
std::cerr << "Error in World::moveTroop(): factionCode argument given in function call did not match to any of the factions.\n";
return MSG::INVALID_FACTION_CODE;
}
Regiment* regiment = getRegimentFromName(arguments[0]);
//std::cout << "regiment->getName returns " << regiment->getName() << "\n";
if(regiment) {
//if regiment of this name was found
if(regiment->getFaction() == NULL) {
std::cerr << "Error in World::moveTroop(): regiments faction was NULL\n";
}
if(regiment->getFaction() != troopFaction) {
//std::cout << "troopFaction: " << troopFaction->getName() << "regiment->faction: ";// << regiment->getFaction()->getName() << "\n";
//if the regiment belonged to a different faction
std::cerr << "Error in World::moveTroop(): unit '" << arguments[0] << "' did not belong to faction '" << troopFaction->getName() << "'\n";
return MSG::UNIT_DID_NOT_BELONG_TO_THIS_FACTION;
}
Island* targetIsland = getIslandFromName(arguments[1]);
if(!targetIsland) {
std::cerr << "Error in World::moveTroop(): island '" << arguments[1] << "' apparently does not exist\n";
return MSG::ISLAND_DOES_NOT_EXIST;
}
//if the islands are not connected, The move is illegal in the game rules. Therefore, return an appropriate error string
if( !(regiment->getPosition())->isLinkedTo(targetIsland) ) {
return MSG::ILLEGAL_MOVE_ISLANDS_NOT_CONNECTED;
}
regiment->setTarget(targetIsland);
return "";
}
Battleship* battleship = getBattleshipFromName(arguments[0]);
if(battleship) {
//if battleship of this name was found
if(battleship->getFaction() == NULL) {
std::cerr << "Error in World::moveTroop(): battleships faction was NULL\n";
}
if(battleship->getFaction() != troopFaction) {
//if the battleship belonged to a different faction
std::cerr << "Error in World::moveTroop(): unit '" << arguments[0] << "' did not belong to faction '" << troopFaction->getName() << "'\n";
return MSG::UNIT_DID_NOT_BELONG_TO_THIS_FACTION;
}
Island* targetIsland = getIslandFromName(arguments[1]);
if(!targetIsland) {
std::cerr << "Error in World::moveTroop(): island '" << arguments[1] << "' apparently does not exist\n";
return MSG::ISLAND_DOES_NOT_EXIST;
}
battleship->setTarget(targetIsland);
return "";
}
Spy* spy = getSpyFromName(arguments[0]);
if(spy) {
//if spy of this name was found
if(spy->getFaction() == NULL) {
std::cerr << "Error in World::moveTroop(): battleships faction was NULL\n";
}
if(spy->getFaction() != troopFaction) {
//if the spy belonged to a different faction
std::cerr << "Error in World::moveTroop(): unit '" << arguments[0] << "' did not belong to faction '" << troopFaction->getName() << "'\n";
return MSG::UNIT_DID_NOT_BELONG_TO_THIS_FACTION;
}
Island* targetIsland = getIslandFromName(arguments[1]);
if(!targetIsland) {
std::cerr << "Error in World::moveTroop(): island '" << arguments[1] << "' apparently does not exist\n";
return MSG::ISLAND_DOES_NOT_EXIST;
}
spy->setTarget(targetIsland);
return "";
}
std::cerr << "Error in World::moveTroop(): no unit named '" << arguments[0] << "' was found\n";
return MSG::UNIT_WAS_NOT_FOUND;
};
Island* World::getIslandFromName(std::string islandName) {
for(std::list<Rim>::iterator it = rims.begin(); it != rims.end(); it++) {
for(std::list<Island>::iterator ct = (*it).islands.begin(); ct != (*it).islands.end(); ct++) {
if( (*ct).getName() == islandName ) {
return &(*ct);
}
}
}
return NULL;
}
void Island::addTroops(int battleshipAmount, int regimentAmount, int spyAmount, Faction* faction) {
Garrison* garrison = getGarrison(faction);
//add battleships
for(int i = 0; i < battleshipAmount; i++) {
garrison->battleships.push_back(faction->addBattleship(this));
garrison->battleships.back()->setFaction(faction);
}
//add regiments
for(int i = 0; i < regimentAmount; i++) {
garrison->regiments.push_back(faction->addRegiment(this));
garrison->regiments.back()->setFaction(faction);
//std::cout << "DEBUG PRINT HERE " << faction->regiments.back().getFaction() << "\n";
}
//add spies
for(int i = 0; i < spyAmount; i++) {
garrison->spies.push_back(faction->addSpy(this));
garrison->spies.back()->setFaction(faction);
}
}
Battleship* Faction::addBattleship(Island* targetIsland) {
std::string shipName = getBattleshipName();
battleships.push_back(Battleship());
battleships.back().condition = MAX_CONDITION;
battleships.back().setName(shipName);
battleships.back().setTarget(NULL);
battleships.back().setPosition(targetIsland);
//battleships.back().setFaction(this);
return &battleships.back();
}
Regiment* Faction::addRegiment(Island* targetIsland) {
std::string regimentName = getRegimentName();
regiments.push_back(Regiment());
regiments.back().condition = MAX_CONDITION;
regiments.back().setName(regimentName);
regiments.back().setTarget(NULL);
regiments.back().setPosition(targetIsland);
//std::cout << "ADDREGIMENT\n";
//battleships.back().setFaction(this);
//std::cout << "in addRegiment regiment faction is '" << battleships.back().getFaction()->getName() << "'\n";
return ®iments.back();
}
Spy* Faction::addSpy(Island* targetIsland) {
std::string spyName = getSpyName();
spies.push_back(Spy());
spies.back().setName(spyName);
spies.back().setTarget(NULL);
spies.back().setPosition(targetIsland);
//battleships.back().setFaction(this);
return &spies.back();
}
std::string World::endTurn() {
if(!isStarted()) {
return MSG::GAME_NOT_STRATED_YET;
}
turn++;
//move troops, do battles. That sort of thing!
//handle peace treaties before moving troops or fighting battles
handleDiplomacy();
turnEndTime = turnTimeInterval;
turnTimer.restart();
//move regiments
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for( std::list<Regiment>::iterator ct = (*it).regiments.begin(); ct != (*it).regiments.end(); ct++ ) {
if( (*ct).getPosition() != (*ct).getTarget() && (*ct).getTarget() != NULL ) {
//if unit was moved
(*ct).recentlyMoved = true;
Island* oldPosition = (*ct).getPosition();
(*ct).setPosition((*ct).getTarget());
(*ct).setTarget(NULL);
oldPosition->popUnitFromList(/*(Movable*)*/&(*ct));
//now add the unit to the new islands unit list
(*ct).getPosition()->addUnitToList(&(*ct), &(*it) );
}
else {
(*ct).recentlyMoved = false;
}
}
}
//move battleships
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for( std::list<Battleship>::iterator ct = (*it).battleships.begin(); ct != (*it).battleships.end(); ct++ ) {
if( (*ct).getPosition() != (*ct).getTarget() && (*ct).getTarget() != NULL ) {
(*ct).recentlyMoved = true;
Island* oldPosition = (*ct).getPosition();
(*ct).setPosition((*ct).getTarget());
(*ct).setTarget(NULL);
oldPosition->popUnitFromList(/*(Movable*)*/&(*ct));
//now add the unit to the new islands unit list
(*ct).getPosition()->addUnitToList(&(*ct), &(*it) );
}
else {
(*ct).recentlyMoved = false;
}
}
}
//move spies
for(std::list<Faction>::iterator it = factions.begin(); it != factions.end(); it++) {
for( std::list<Spy>::iterator ct = (*it).spies.begin(); ct != (*it).spies.end(); ct++ ) {
if( (*ct).getPosition() != (*ct).getTarget() && (*ct).getTarget() != NULL ) {
(*ct).recentlyMoved = true;
Island* oldPosition = (*ct).getPosition();
(*ct).setPosition((*ct).getTarget());
(*ct).setTarget(NULL);
oldPosition->popUnitFromList(/*(Movable*)*/&(*ct));
//now add the unit to the new islands unit list
(*ct).getPosition()->addUnitToList(&(*ct), &(*it) );
}
else {
(*ct).recentlyMoved = false;
}
}
}
fightBattles();
//std::cout << "Battles fought\n";
//recruit new troops
for(auto it = factions.begin(); it != factions.end(); it++) {
(*it).turnUpdate(getDominance((&*it)), baseRegimentSupply, baseBattleshipSupply);
}
return "";
}
//This function returns how many islands are in control of this faction
float World::getDominance(Faction* faction) {
float dominance = 0.0f;
for(auto it = rims.begin(); it != rims.end(); it++) {
for(auto ct = (*it).islands.begin(); ct != (*it).islands.end(); ct++) {
if((*ct).owner == faction) {
dominance+=1;
}
}
}
return dominance;
}
void Faction::turnUpdate(float areaDominance, float baseRegimentSupply, float baseBattleshipSupply) {
std::cout << "Faction " << this->getName() << " has areaDominance of " << areaDominance << ", its newRegminentProgress is " << newRegimentProgress << " and its newBattleshipProgress is " << newBattleshipProgress <<"\n";
//in the beginning of the turn factions will recruit new battleships and regiments relative to the base supply values and how much islands they own
//more islands means more troops
newRegimentProgress+= baseRegimentSupply + areaDominance*dominanceToRegimentsFactor;
newBattleshipProgress+= baseBattleshipSupply + areaDominance*dominanceToBattleshipsFactor;
std::cout << "Faction " << this->getName() << " has areaDominance of " << areaDominance << ", its newRegminentProgress is " << newRegimentProgress << " and its newBattleshipProgress is " << newBattleshipProgress <<"\n";
//add new regiments
if( baseIsland == nullptr ) { std::cerr << "Error in Faction::TurnUpdate(): faction had no base island!\n"; }
for(; newRegimentProgress >= 1.0f; newRegimentProgress-=1.0f ) {
baseIsland->addTroops(0, 1, 0, this);
}
//add new battleships
for(; newBattleshipProgress >= 1.0f; newBattleshipProgress-=1.0f ) {
baseIsland->addTroops(1, 0, 0, this);
}
for(auto it = regiments.begin(); it != regiments.end(); it++) {
(*it).getPosition()->attemptClaim((*it).getFaction());
}
}
void BattleSide::countTotalStrength(std::list<BattleSide>* sides) {
std::cout << "World::countTotalStrenght()\n";
//total strength is personal strength combined with the strength of allies that are fighting your enemies also
totalStrength = personalStrength;
for( auto it = allies.begin(); it != allies.end(); it++ ) {
std::cout << "new battleSide ally: " << (*it)->owner->getName() << "\n";
std::cout << "cts::iterating new i\n";
//float sidesTotal = 0.0f;
float nonMutualEnemyStrength = 0.0f;
float mutualEnemyStrength = 0.0f;
for( auto ct = sides->begin(); ct != sides->end(); ct++ ) {
std::cout << "new iterable side: " << (*ct).owner->getName() << "\n";
std::cout << "cts::iterating new c\n";
if( &(*ct) != this && &(*ct) != (*it) ) {
if( (*ct).isAllyOf((*it)->owner) ) {
//battleside *it is not of use against foe *ct
nonMutualEnemyStrength += (*ct).personalStrength;
}
else {
mutualEnemyStrength += (*ct).personalStrength;
}
std::cout << "aaaa\n";
if(nonMutualEnemyStrength == 0) {
totalStrength += (*it)->personalStrength*1;
}
else {
totalStrength += (*it)->personalStrength*(nonMutualEnemyStrength+mutualEnemyStrength)/nonMutualEnemyStrength;
}
std::cout << "bbbb\n";
}
else {
std::cout << "same side spotted!\n";
}
}
}
std::cout << "totalStrength counted!\n";
}
void BattleSide::countOppressionStrength(std::list<BattleSide>* sides) {
std::cout << "countOpressionStrength\n";
oppressionStrength = 0.0f;
for( auto it = sides->begin(); it != sides->end(); it++ ) {
std::cout << "counting opression strength for " << (*it).owner->getName() << "\n";
if( (*it).owner == owner || (*it).isAllyOf(owner) ) {
continue;
}
oppressionStrength += (*it).personalStrength;
}
std::cout << "battleSide oppression strength: " << oppressionStrength << "\n";
std::cout << "opression Strength counted!\n";
}
void Island::damageUnits(std::list<BattleSide>& sides) {
std::default_random_engine generator;
std::uniform_real_distribution<float> randomDamageDistribution(0, battleRandomDamageConstant*2);
//damage every unit accordingly
for(auto it = garrisons.begin(); it != garrisons.end(); it++) {
if( (*it).regiments.size() + (*it).battleships.size() == 0 ) { continue; }
BattleSide* currentBattleSide = getBattleSideFromFaction(sides, (*it).getFaction());
float disadvantage = battleAttackerDisadvantageConstant;
if( currentBattleSide->defenderSide ) {
disadvantage = 1.0f;
}
for(auto ct = (*it).regiments.begin(); ct != (*it).regiments.end(); ct++) {
if( currentBattleSide->oppressionStrength == 0.0f ) { continue; }
float randomFactor = battleRandomDamageConstant - randomDamageDistribution(generator);
float damage = ( 1 + randomFactor) * powf((currentBattleSide->oppressionStrength/currentBattleSide->totalStrength), 1/battleAdvantageConstant ) * battleUnitDamageConstant;
if((*ct)->recentlyMoved) {
(*ct)->condition -= damage*disadvantage;
}
else {//UNTESTED PART OF CODE
(*ct)->condition -= damage;
}
}
for(auto ct = (*it).battleships.begin(); ct != (*it).battleships.end(); ct++) {
if( currentBattleSide->oppressionStrength == 0.0f ) { continue; }
float randomFactor = battleRandomDamageConstant - randomDamageDistribution(generator);
float damage = ( 1 + randomFactor) * powf((currentBattleSide->oppressionStrength/currentBattleSide->totalStrength), 1/battleAdvantageConstant ) * battleUnitDamageConstant;
if((*ct)->recentlyMoved) {
(*ct)->condition -= damage*disadvantage;
}
else {//UNTESTED PART OF CODE
(*ct)->condition -= damage;
}
}
//kill all units that have negative hitpoints
for(auto ct = (*it).regiments.begin(); ct != (*it).regiments.end(); ct++) {
if( (*ct)->condition <= 0.0f ) {
Faction* unitFaction = (*ct)->getFaction();
//remove this unit from the faction unit list
//obscuring spaghetti code here :s
for( auto kt = unitFaction->regiments.begin(); kt != unitFaction->regiments.end(); kt++ ) {
if( &(*kt) == (*ct) ) {
unitFaction->regiments.erase(kt);
break;
}
}
(*it).regiments.erase(ct);
}
}
for(auto ct = (*it).battleships.begin(); ct != (*it).battleships.end(); ct++) {
if( (*ct)->condition <= 0.0f ) {
Faction* unitFaction = (*ct)->getFaction();
//remove this unit from the faction unit list
//obscuring spaghetti code here :s
for( auto kt = unitFaction->battleships.begin(); kt != unitFaction->battleships.end(); kt++ ) {
if( &(*kt) == (*ct) ) {
unitFaction->battleships.erase(kt);
break;
}
}
(*it).battleships.erase(ct);
}
}
}
}
void Island::battleSides(std::list<BattleSide>& sides) {
for(auto it = garrisons.begin(); it != garrisons.end(); it++) {
//if faction has no military presence on the island, it is not a contestant in a battle
if( ( (*it).regiments.size() + (*it).battleships.size() == 0) ) {
continue;
}
BattleSide a;
a.personalStrength = (*it).countBattleStrength();
std::cout << "battle strength: " << a.personalStrength << "\n";
a.totalStrength = 0.0f;
a.owner = (*it).getFaction();
for(auto ct = (*it).regiments.begin(); ct != (*it).regiments.end(); ct++) {
a.totalStrength += (*ct)->condition/MAX_CONDITION;
}
for(auto ct = (*it).battleships.begin(); ct != (*it).battleships.end(); ct++) {
a.totalStrength += (*ct)->condition/MAX_CONDITION;
}
sides.push_back(a);
}
//now battlesides and their personal strengths have been calculated. Commencing to finding all the allies of battlesides
//this is poorly optimised but the code won't be bottlenecking here
for(auto it = sides.begin(); it != sides.end(); it++) {
for(auto ct = sides.begin(); ct != sides.end(); ct++ ) {
if( (*it).owner->isAllyOf((*ct).owner) ) {
(*it).addAlly(&(*ct));
}
}
}
//next we count the total strengths of the battleSides. This roughly means an equation: personal strength + ally strength - strength of allies
// that are allied to someone else this battle side is fighting with
for(auto it = sides.begin(); it != sides.end(); it++) {
(*it).countTotalStrength(&sides);
(*it).countOppressionStrength(&sides);
}
}
bool Garrisonable::isClaimable(Faction* faction) {
for(auto it = garrisons.begin(); it != garrisons.end(); it++) {
if( (*it).getFaction() == faction ) {
continue;
}
if( !(*it).isEmptyOfRegiments() ) {
return false;
}
}
return true;
}
void World::fightBattles() {
std::cout << "World::Fighting battles!\n";
for( auto it = rims.begin(); it != rims.end(); it++ ) {
for(auto ct = (*it).islands.begin(); ct != (*it).islands.end(); ct++) {
std::list<BattleSide> sides;
(*ct).battleSides(sides);
(*ct).damageUnits(sides);
}
}
}
std::list<Island*> World::getIslandLOSFilter(Faction* faction) {
std::list<Island*> nullList;
return nullList;
}
bool World::islandOnLOS(std::list<Island*>& filter) {
return true;
}
void World::worldInStringFormatForFaction(std::string& stringWorld, Faction* LOSFaction) {
if(unstarted) {
stringWorld = MSG::GAME_NOT_STRATED_YET;
return;
}
//make sure the string is empty
stringWorld.clear();
StrDP::StringDataStructure stringData;
//! FIRST FS SEGMENT
{
StrDP::FS first;
//This segment contains only unchanging information about the world.
//baseRegimentSupply
first.gs.push_back(std::to_string(baseRegimentSupply));
//baseBattleshipSupply
first.gs.push_back(std::to_string(baseBattleshipSupply));
//regimentRecoveryRate
first.gs.push_back(std::to_string(regimentRecoveryRate));
//shipRecoveryRate
first.gs.push_back(std::to_string(shipRecoveryRate));
//factions
StrDP::GS factionsData;
for( auto it = factions.begin(); it != factions.end(); it++ ) {
StrDP::RS factionData;
//faction name
factionData.us.push_back((*it).getName());
//faction color
factionData.us.push_back(std::to_string((*it).getColor()));
//faction capital island name
if((*it).getBaseIsland() == nullptr) {
std::cerr << "Error in worldInStringFormat(): a faction had no base island!\n";
stringWorld = MSG::SERVER_ERROR;
return;
}
factionData.us.push_back((*it).getBaseIsland()->getName());
factionsData.rs.push_back(factionData);
}
//first data section complete
first.gs.push_back(factionsData);
if( LOSFaction != nullptr ) {
first.gs.push_back( LOSFaction->getName() );
}
else {
std::cerr << "WARNING: possibly showing global vision in a game state request!\n";
std::string noneString = "NONE";
first.gs.push_back( noneString );
}
stringData.fs.push_back(first);
}
//! SECOND FS SEGMENT
{
//this segment contains all the players spesific data including preace treaties and treaty requests
StrDP::FS second;
//create the factions strings
StrDP::GS treaties;
//peace treaties already processed are saved in this blackList
//there ought to be a better way to do this than this...
std::vector<std::pair<Faction*, Faction*>> blackList;
for(auto it = factions.begin(); it != factions.end(); it++) {
for(auto ct = factions.begin(); ct != factions.end(); ct++) {
//if faction *it is allied with faction *ct
if( (*it).isAllyOf(&(*ct)) ) {
bool isBlackListed = false;
//if does not appear on blacklist
for(auto kt = blackList.begin(); kt != blackList.end(); kt++) {
if( ( (*kt).first == &(*it) && (*kt).second == &(*ct) ) || ( (*kt).first == &(*ct) && (*kt).second == &(*it) ) ) {
isBlackListed = true;
}
}
//if faction is ally and not on blacklist(that is, already listed in treaties)
if(!isBlackListed) {
StrDP::RS peace;
//use us separation for faction names
peace.us.push_back((*it).getName());
peace.us.push_back((*ct).getName());
//save treaty information as rs data
treaties.rs.push_back(peace);
}
}
}
}
second.gs.push_back(treaties);
StrDP::GS requests;
for(auto it = treatyRequests.begin(); it != treatyRequests.end(); it++) {
StrDP::RS requestUnit;
//save the faction names in the data as us fields
requestUnit.us.push_back( (*it).first->getName() );
requestUnit.us.push_back( (*it).second->getName() );
requests.rs.push_back(requestUnit);
}
second.gs.push_back(requests);
//turn data
second.gs.push_back(std::to_string(turn));
//time left until next turn
second.gs.push_back(std::to_string( getTimeLeft().asSeconds() ));
//second data section complete
stringData.fs.push_back(second);
}
//! THIRD FS SEGMENT
{
//third FS covers the island data and unit data within the islands
StrDP::FS third;
//this data has faction spesific information, as only some islands are in the
//LOS(Line Of Sight) of a faction
//this filter is used in indentyfying the islands, that are not in the line
//of sight, and those units are not displayed in the information
std::list<Island*> LOSfilter = getIslandLOSFilter(LOSFaction);
//handle rims as GS segments
for(auto it = rims.begin(); it != rims.end(); it++) {
StrDP::GS rimUnit;
//each rim contains n amount of islands: these islands' data is stored over
//multiple rs information, the last section contains troop information
//the beginning of a new island data is known because there are fixed amount
//of rs fields in an island
for(auto ct = (*it).islands.begin(); ct != (*it).islands.end(); ct++) {
//in the first RS is stored island name
rimUnit.rs.push_back( (*ct).getName() );
//following information is the island owner
if((*ct).getOwner() == nullptr) { rimUnit.rs.push_back(StrDP::RS()); }
else {
rimUnit.rs.push_back( (*ct).getOwner()->getName() );
}
//third section is for island unit data
StrDP::RS unitSegment;
//if island is not on faction LOS, the unit data section will be empty
if(!islandOnLOS(LOSfilter)) {
rimUnit.rs.push_back(unitSegment);
}
//else if player has line of sight to the island, reveal all troops it occupies
else {
for( auto kt = (*ct).garrisons.begin(); kt != (*ct).garrisons.end();kt++ ) {
for(auto lt = (*kt).regiments.begin(); lt != (*kt).regiments.end();lt++) {
//regiment name
unitSegment.us.push_back((*lt)->getName());
//regiment condition
unitSegment.us.push_back(std::to_string((*lt)->condition));
//regiment movement order (island name)
if( (*lt)->getTarget() == nullptr ) {
unitSegment.us.push_back( StrDP::US("") );
}
else {
unitSegment.us.push_back( (*lt)->getTarget()->getName() );
}
}
for(auto lt = (*kt).battleships.begin(); lt != (*kt).battleships.end();lt++) {
//battleship name
unitSegment.us.push_back((*lt)->getName());
//battleship condition
unitSegment.us.push_back(std::to_string((*lt)->condition));
//battleship movement order (island name)
if( (*lt)->getTarget() == nullptr ) {
unitSegment.us.push_back( StrDP::US("") );
}
else {
unitSegment.us.push_back( (*lt)->getTarget()->getName() );
}
}
for(auto lt = (*kt).spies.begin(); lt != (*kt).spies.end();lt++) {
//spy name
unitSegment.us.push_back((*lt)->getName());
//spy condition(spies have no condition, so this is an empty string)
unitSegment.us.push_back( StrDP::US() );
//spy movement order (island name)
if( (*lt)->getTarget() == nullptr ) {
unitSegment.us.push_back( StrDP::US("") );
}
else {
unitSegment.us.push_back( (*lt)->getTarget()->getName() );
}
}
}
rimUnit.rs.push_back(unitSegment);
}
//fourth and absolute final section is for linked islands data
StrDP::RS linkedIslandData;
std::list<Island*> linkedIslandsList = (*ct).getLinkedIslands();
for(auto kt = linkedIslandsList.begin(); kt != linkedIslandsList.end();kt++) {
linkedIslandData.us.push_back( (*kt)->getName() );
}
rimUnit.rs.push_back(linkedIslandData);
}
third.gs.push_back(rimUnit);
}
//thid data section complete
stringData.fs.push_back(third);
}
//! FOURTH FS SEGMENT
{
StrDP::FS fourth;
//war declarations
StrDP::GS declarations;
for(auto it = warDeclarations.begin(); it != warDeclarations.end(); it++ ) {
StrDP::RS declaration;
declaration.us.push_back((*it).first->getName());
declaration.us.push_back((*it).second->getName());
declarations.rs.push_back( declaration );
}
fourth.gs.push_back(declarations);
stringData.fs.push_back(fourth);
}
stringData.toString(stringWorld);
stringData.printStringData();
}
std::string parseFactionCommand(std::string commandString, std::vector<std::string>& arguments, std::string& command, std::string& factionCode) {
arguments.clear();
//pick up the faction code part from the command string
int firstPoint = commandString.find_first_of(':');
if(firstPoint < 0) {
return MSG::COMMAND_SYNTAX_WAS_INVALID;
}
factionCode = commandString.substr(0, firstPoint);
commandString = commandString.substr(firstPoint+1);
//pick up the command name from the command string
int secondPoint = commandString.find_first_of(':');
if(secondPoint < 0) {
return MSG::COMMAND_SYNTAX_WAS_INVALID;
}
command = commandString.substr(0, secondPoint);
commandString = commandString.substr(secondPoint+1);
//pick up all the following arguments from the command string
while(true) {
//ARGUMENT SEPARATOR WILL BE CHANGED INTO SOME OTHER CHARACTER IN LATER DEVELOPMENT WHEN I'M NOT USING CONSOLES FOR SENDING MESSAGES
int nextPoint = commandString.find_first_of('%');
if(nextPoint < 0) {
break;
}
arguments.push_back(commandString.substr(0, nextPoint));
commandString = commandString.substr(nextPoint+1);
}
return "";
}
bool Faction::isAllyOf(Faction* faction) {
if(faction == NULL) {
std::cerr << "Error in Faction::isAllyOf(): a null pointer was passed into this function as argument\n";
}
for(auto it = allies.begin(); it != allies.end(); it++) {
if( faction == (*it) ) {
return true;
}
}
return false;
}
|
#include "CDateTime.h"
#include "CAutoLock.h"
#include "CInterval.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
using namespace Util;
int CDateTime::_localTimeZone = -8;
CDateTime CDateTime::_lastDt(0);
bool parseYMD(struct tm* time,
unsigned long* millis,
const char ch,
const char* value,
int index,
int length,
int count
)
{
char buf[5];
int nvalue = 0;
if ( index + count > length )
return false;
switch ( ch )
{
case 'Y' :
{
if ( count == 2 || count == 4 )
{
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi( buf );
}
else
return false;
if ( count == 2 )
nvalue += 2000;
if ( nvalue >= 1970 )
nvalue -= 1900;
else
return false;
time->tm_year = nvalue;
}
break;
case 'M' :
{
if ( count > 2 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue > 12 || nvalue <= 0 )
return false;
time->tm_mon = nvalue-1;
}
break;
case 'D' :
{
if ( count > 2 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue > 31 || nvalue <= 0 )
return false;
time->tm_mday = nvalue;
}
break;
case 'h' :
{
if ( count > 2 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue > 23 || nvalue < 0 )
return false;
time->tm_hour = nvalue;
}
break;
case 'm' :
{
if ( count > 2 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue > 59 || nvalue < 0 )
return false;
time->tm_min = nvalue;
}
break;
case 's' :
{
if ( count > 2 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue > 59 || nvalue < 0 )
return false;
time->tm_sec = nvalue;
}
break;
case 'n' :
{
if ( count > 3 )
return false;
memcpy( buf, value + index, count );
buf[count] = 0;
nvalue = atoi(buf);
if ( nvalue < 0 )
return false;
*millis = nvalue;
}
break;
default :
return false;
}
return true;
}
CDateTime::CDateTime() :_timeZone(0),_showZone(0),_tm(NULL)
{
*this = getThreadDt();
}
void CDateTime::update()
{
#ifdef _WIN32
SYSTEMTIME time;
GetLocalTime( &time );
init( time.wYear , time.wMonth , time.wDay
, time.wHour , time.wMinute , time.wSecond , time.wMilliseconds , 0 );
#endif
#ifdef _LINUX
//struct tm *tt2;
//struct timeval tstruct1;
//struct timezone tzp;
//::gettimeofday(&tstruct1,&tzp);
//tt2 = localtime(&tstruct1.tv_sec);
//init( tt2->tm_year+1900 , tt2->tm_mon+1 , tt2->tm_mday,
// tt2->tm_hour , tt2->tm_min , tt2->tm_sec , tstruct1.tv_usec / 1000 , 0 );
struct timespec tm1;
clock_gettime(CLOCK_REALTIME, &tm1);
//std::cout << (int64_t)(1000 )*(tpend.tv_sec)+(tpend.tv_nsec) / ( 1000 * 1000 ) << std::endl;
init( (int64_t)(1000 )*(tm1.tv_sec)+(tm1.tv_nsec) / ( 1000 * 1000 ) , 0 );
#endif
}
CDateTime::CDateTime(int year, int month, int day, int hour,
int minute, int second,int millseconds,short timezone)
:_tm(NULL)
{
init( year, month, day, hour, minute, second, millseconds, timezone );
}
bool CDateTime::init(int year, int month, int day, int hour, int minute,
int second,int millseconds,short timezone)
{
clearTm();
struct tm ltm;
ltm.tm_year = year - 1900;
ltm.tm_mon = month - 1;
ltm.tm_mday = day;
ltm.tm_hour = hour;
ltm.tm_min = minute;
ltm.tm_sec = second;
time_t tmV = mktime(<m);
if ( millseconds < 0 || millseconds > 999 || tmV == -1 )
{
_timeZone = 0;
_showZone = 0;
_timeSpan = 0;
return false;
}
_timeSpan = tmV;
_timeSpan = _timeSpan * 1000 + millseconds;
_timeZone = _showZone = timezone;
return true;
}
bool CDateTime::init(
int64_t millseconds ,
short timezone /* = 0 */)
{
clearTm();
_timeSpan = millseconds;
_timeZone = _showZone = timezone;
return true;
}
CDateTime::CDateTime(const CDateTime& other)
:_tm( NULL )
{
this->_timeZone = other._timeZone;
this->_timeSpan = other._timeSpan;
this->_showZone = other._showZone;
}
CDateTime::CDateTime( int64_t millseconds , short timezone )
:_tm( NULL )
{
init( millseconds , timezone );
}
CDateTime::~CDateTime()
{
delete _tm;
}
int CDateTime::getYear() const
{
return getLocalTime()->tm_year+1900;
}
int CDateTime::getMonth() const
{
return getLocalTime()->tm_mon + 1;
}
int CDateTime::getDay() const
{
return getLocalTime()->tm_mday;
}
int CDateTime::getHour() const
{
return getLocalTime()->tm_hour;
}
int CDateTime::getMinute() const
{
return getLocalTime()->tm_min;
}
int CDateTime::getSecond() const
{
return getLocalTime()->tm_sec;
}
int CDateTime::getDayOfWeek() const
{
return getLocalTime()->tm_wday;
}
int CDateTime::getMillSecond() const
{
return (int)(_timeSpan % 1000 );
}
void CDateTime::clearMillSecond()
{
_timeSpan -= getMillSecond();
}
CDateTime& CDateTime::operator =(const CDateTime& other)
{
clearTm();
this->_timeZone = other._timeZone;
this->_timeSpan = other._timeSpan;
this->_showZone = other._showZone;
return *this;
}
CInterval CDateTime::operator -(const CDateTime& other) const
{
int64_t interval;
if ( this->_timeZone == other._timeZone )
{
interval = this->_timeSpan - other._timeSpan;
}
else
{
interval = this->_timeSpan + this->getTimeZoneMills()
- other._timeSpan - other.getTimeZoneMills();
}
return CInterval(interval);
}
CDateTime CDateTime::operator -(const CInterval& interval) const
{
CDateTime datetime(*this);
datetime -= interval;
return datetime;
}
CDateTime CDateTime::operator +(const CInterval& interval) const
{
CDateTime datetime(*this);
datetime += interval;
return datetime;
}
const CDateTime& CDateTime::operator -=(const CInterval& interval)
{
this->_timeSpan -= interval._timeSpan;
clearTm();
return *this;
}
const CDateTime& CDateTime::operator +=(const CInterval& interval)
{
this->_timeSpan += interval._timeSpan;
clearTm();
return *this;
}
bool CDateTime::operator==(const CDateTime& other) const
{
if ( this->_timeZone == other._timeZone )
return this->_timeSpan == other._timeSpan;
else
return ( this->_timeSpan + getTimeZoneMills() ) == other._timeSpan + other.getTimeZoneMills();
}
bool CDateTime::operator !=(const CDateTime& other) const
{
return !(*this == other);
}
bool CDateTime::operator < (const CDateTime& other) const
{
if ( this->_timeZone == other._timeZone )
return this->_timeSpan < other._timeSpan;
else
return ( this->_timeSpan + getTimeZoneMills() ) < other._timeSpan + other.getTimeZoneMills();
}
bool CDateTime::operator <= (const CDateTime& other) const
{
if( other < *this )
{
return false;
}
return true;
}
bool CDateTime::operator >(const CDateTime& other) const
{
return other < *this;
}
bool CDateTime::operator >=(const CDateTime& other) const
{
if( *this < other )
{
return false;
}
return true;
}
long CDateTime::getTimeZoneMills() const
{
return _timeZone * 1000 * 3600;
}
CDateTime CDateTime::getAbsDt()
{
return CDateTime();
}
void CDateTime::updateThreadDt()
{
CAutoLock l(getLock());
_lastDt.update();
}
CDateTime CDateTime::getThreadDt()
{
CAutoLock l( getLock() );
if( _lastDt.getTotalMill() == 0 )
{
CDateTime dateTime(0);
dateTime.update();
return dateTime;
}
return _lastDt;
}
void CDateTime::setLocalTimeZone( int localTimeZone )
{
_localTimeZone = localTimeZone;
}
CLock* CDateTime::getLock()
{
static CLock lock;
return &lock;
}
void CDateTime::clearTm()
{
//CAutoLock l( getLock() );
delete _tm;
_tm = NULL;
}
const struct tm* CDateTime::getLocalTime() const
{
//CAutoLock l( getLock() );
/*
if( _tm )
{
return _tm;
}
*const_cast<cdf_tm**>(&_tm) = new cdf_tm();
time_t tmV = getTotalSecond();
*_tm = *localtime( &tmV );
return _tm;
*/
if( _tm )
{
return _tm;
}
*const_cast<tm**>(&_tm) = new tm();
time_t tmV = getTotalSecond();
#ifdef _LINUX
localtime_r( &tmV , _tm );
#else
*_tm = *localtime( &tmV );
#endif
return _tm;
}
void CDateTime::setShowTimeZone(short timeZone)
{
this->_showZone = timeZone;
}
bool CDateTime::parse(const char* value, const char* format)
{
int len = (int)strlen(format);
int vallen = (int)strlen(value);
int index = 0;
struct tm ltm;
unsigned long millis = 0;
for ( index = 0 ; index < len ; )
{
char ch = format[index];
switch ( ch )
{
case 'Y' :
case 'M' :
case 'D' :
case 'h' :
case 'm' :
case 's' :
case 'n' :
{
int count = 1;
while ( format[++index] == ch )
count++;
if ( !parseYMD( <m, &millis, ch, value, index-count, vallen, count) )
{
return false;
}
};
break;
default :
index ++;
}
}
time_t timeV = mktime(<m);
if ( timeV == -1 )
{
return false;
}
int64_t mill = timeV;
mill = mill * 1000 + millis;
init( mill );
return true;
}
std::string CDateTime::asString(const char* format) const
{
char buf[100];
sprintf(buf,"%s",format);
int len = (int)strlen(format);
int index = 0;
time_t showtime;
if ( this->_timeZone != _showZone )
{
showtime = getTotalSecond() + ( _showZone - _timeZone) * 3600;
}
else
{
showtime = getTotalSecond();
}
struct tm time = *localtime(&showtime);
unsigned long mills = (long)(_timeSpan % 1000);
for ( index = 0 ; index < len ; )
{
char ch = format[index];
switch ( ch )
{
case 'Y' :
case 'M' :
case 'D' :
case 'h' :
case 'm' :
case 's' :
case 'n' :
{
int count = 1;
while ( format[++index] == ch )
count++;
if ( !asYMD(&time,mills,ch,buf,index-count,count,sizeof(buf)) )
return std::string();
//throw CDateTimeException("CDateTime Format Error!");
};
break;
default :
index ++;
}
}
return std::string(buf);
}
bool CDateTime::asYMD(struct tm* time, unsigned long mills, const char ch,
char* buf, int index, int count, int bufSize) const
{
if ( index + count >= bufSize )
return false;
char change;
char format[5];
sprintf(format,"%%0%dd",count);
change = buf[index+count];
switch ( ch )
{
case 'Y' :
if ( count == 2 )
sprintf( buf + index, format, time->tm_year);
else if ( count == 4 )
sprintf( buf + index, format, time->tm_year+1900 );
else
return false;
break;
case 'M' :
if ( count > 2 )
return false;
sprintf( buf+index, format, time->tm_mon+1 );
break;
case 'D' :
if ( count > 2 )
return false;
sprintf( buf + index, format, time->tm_mday );
break;
case 'h' :
if ( count > 2 )
return false;
sprintf( buf + index, format, time->tm_hour );
break;
case 'm' :
if ( count > 2 )
return false;
sprintf( buf + index, format, time->tm_min );
break;
case 's' :
if ( count > 2 )
return false;
sprintf( buf + index, format, time->tm_sec );
break;
case 'n' :
if ( count > 3 )
return false;
sprintf( buf + index, format, mills );
break;
default :
return false;
}
buf[index + count] = change;
return true;
}
int CDateTime::getTotalDay() const
{
return int(( _timeSpan - _localTimeZone * 60 * 60 * 1000 ) / (24 * 60 * 60 * 1000));
}
int64_t CDateTime::getTotalMill() const
{
return _timeSpan;
}
long CDateTime::getTotalSecond() const
{
return (long)(_timeSpan / 1000);
}
|
/*!
* Modifications Copyright 2017-2018 H2O.ai, Inc.
*/
// original code from https://github.com/NVIDIA/kmeans (Apache V2.0 License)
#pragma once
#include <cublas_v2.h>
#include <thrust/device_allocator.h>
#include <thrust/device_malloc_allocator.h>
#include <thrust/device_vector.h>
#include <thrust/fill.h>
#include <cfloat>
#include <iostream>
#include <sstream>
#include "../include/cub/cub.cuh"
#include "kmeans_general.h"
inline void gpu_assert(cudaError_t code, const char *file, int line,
bool abort = true) {
if (code != cudaSuccess) {
fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file,
line);
std::stringstream ss;
ss << file << "(" << line << ")";
std::string file_and_line;
ss >> file_and_line;
thrust::system_error(code, thrust::cuda_category(), file_and_line);
}
}
inline cudaError_t throw_on_cuda_error(cudaError_t code, const char *file,
int line) {
if (code != cudaSuccess) {
std::stringstream ss;
ss << file << "(" << line << ")";
std::string file_and_line;
ss >> file_and_line;
thrust::system_error(code, thrust::cuda_category(), file_and_line);
}
return code;
}
#ifdef CUBLAS_API_H_
// cuBLAS API errors
static const char *cudaGetErrorEnum(cublasStatus_t error) {
switch (error) {
case CUBLAS_STATUS_SUCCESS:
return "CUBLAS_STATUS_SUCCESS";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "CUBLAS_STATUS_NOT_INITIALIZED";
case CUBLAS_STATUS_ALLOC_FAILED:
return "CUBLAS_STATUS_ALLOC_FAILED";
case CUBLAS_STATUS_INVALID_VALUE:
return "CUBLAS_STATUS_INVALID_VALUE";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "CUBLAS_STATUS_ARCH_MISMATCH";
case CUBLAS_STATUS_MAPPING_ERROR:
return "CUBLAS_STATUS_MAPPING_ERROR";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "CUBLAS_STATUS_EXECUTION_FAILED";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "CUBLAS_STATUS_INTERNAL_ERROR";
}
return "<unknown>";
}
#endif
inline cublasStatus_t throw_on_cublas_error(cublasStatus_t code,
const char *file, int line) {
if (code != CUBLAS_STATUS_SUCCESS) {
fprintf(stderr, "cublas error: %s %s %d\n", cudaGetErrorEnum(code), file,
line);
std::stringstream ss;
ss << file << "(" << line << ")";
std::string file_and_line;
ss >> file_and_line;
thrust::system_error(code, thrust::cuda_category(), file_and_line);
}
return code;
}
extern cudaStream_t cuda_stream[MAX_NGPUS];
template <unsigned int i>
extern __global__ void debugMark(){};
namespace kmeans {
namespace detail {
void labels_init();
void labels_close();
template <typename T>
void memcpy(thrust::host_vector<T, std::allocator<T>> &H,
thrust::device_vector<T, thrust::device_malloc_allocator<T>> &D) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(H.data()), thrust::raw_pointer_cast(D.data()),
sizeof(T) * D.size(), cudaMemcpyDeviceToHost, cuda_stream[dev_num]));
}
template <typename T>
void memcpy(thrust::device_vector<T, thrust::device_malloc_allocator<T>> &D,
thrust::host_vector<T, std::allocator<T>> &H) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(D.data()), thrust::raw_pointer_cast(H.data()),
sizeof(T) * H.size(), cudaMemcpyHostToDevice, cuda_stream[dev_num]));
}
template <typename T>
void memcpy(thrust::device_vector<T, thrust::device_malloc_allocator<T>> &Do,
thrust::device_vector<T, thrust::device_malloc_allocator<T>> &Di) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(Do.data()), thrust::raw_pointer_cast(Di.data()),
sizeof(T) * Di.size(), cudaMemcpyDeviceToDevice, cuda_stream[dev_num]));
}
template <typename T>
void memzero(thrust::device_vector<T, thrust::device_malloc_allocator<T>> &D) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemsetAsync(thrust::raw_pointer_cast(D.data()), 0,
sizeof(T) * D.size(), cuda_stream[dev_num]));
}
template <typename T>
void memcpy(thrust::host_vector<T, std::allocator<T>> &H,
thrust::device_vector<T, thrust::device_allocator<T>> &D) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(H.data()), thrust::raw_pointer_cast(D.data()),
sizeof(T) * D.size(), cudaMemcpyDeviceToHost, cuda_stream[dev_num]));
}
template <typename T>
void memcpy(thrust::device_vector<T, thrust::device_allocator<T>> &D,
thrust::host_vector<T, std::allocator<T>> &H) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(D.data()), thrust::raw_pointer_cast(H.data()),
sizeof(T) * H.size(), cudaMemcpyHostToDevice, cuda_stream[dev_num]));
}
template <typename T>
void memcpy(thrust::device_vector<T, thrust::device_allocator<T>> &Do,
thrust::device_vector<T, thrust::device_allocator<T>> &Di) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemcpyAsync(
thrust::raw_pointer_cast(Do.data()), thrust::raw_pointer_cast(Di.data()),
sizeof(T) * Di.size(), cudaMemcpyDeviceToDevice, cuda_stream[dev_num]));
}
template <typename T>
void memzero(thrust::device_vector<T, thrust::device_allocator<T>> &D) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
safe_cuda(cudaMemsetAsync(thrust::raw_pointer_cast(D.data()), 0,
sizeof(T) * D.size(), cuda_stream[dev_num]));
}
void streamsync(int dev_num);
// n: number of points
// d: dimensionality of points
// data: points, laid out in row-major order (n rows, d cols)
// dots: result vector (n rows)
// NOTE:
// Memory accesses in this function are uncoalesced!!
// This is because data is in row major order
// However, in k-means, it's called outside the optimization loop
// on the large data array, and inside the optimization loop it's
// called only on a small array, so it doesn't really matter.
// If this becomes a performance limiter, transpose the data somewhere
template <typename T>
__global__ void self_dots(int n, int d, T *data, T *dots) {
T accumulator = 0;
int global_id = blockDim.x * blockIdx.x + threadIdx.x;
if (global_id < n) {
for (int i = 0; i < d; i++) {
T value = data[i + global_id * d];
accumulator += value * value;
}
dots[global_id] = accumulator;
}
}
template <typename T>
void make_self_dots(int n, int d, thrust::device_vector<T> &data,
thrust::device_vector<T> &dots) {
int dev_num;
#define MAX_BLOCK_THREADS0 256
const int GRID_SIZE = (n - 1) / MAX_BLOCK_THREADS0 + 1;
safe_cuda(cudaGetDevice(&dev_num));
self_dots<<<GRID_SIZE, MAX_BLOCK_THREADS0, 0, cuda_stream[dev_num]>>>(
n, d, thrust::raw_pointer_cast(data.data()),
thrust::raw_pointer_cast(dots.data()));
#if (CHECK)
gpuErrchk(cudaGetLastError());
#endif
}
#define MAX_BLOCK_THREADS 32
template <typename T>
__global__ void all_dots(int n, int k, T *data_dots, T *centroid_dots,
T *dots) {
__shared__ T local_data_dots[MAX_BLOCK_THREADS];
__shared__ T local_centroid_dots[MAX_BLOCK_THREADS];
// if(threadIdx.x==0 && threadIdx.y==0 && blockIdx.x==0)
// printf("inside %d %d %d\n",threadIdx.x,blockIdx.x,blockDim.x);
int data_index = threadIdx.x + blockIdx.x * blockDim.x;
if ((data_index < n) && (threadIdx.y == 0)) {
local_data_dots[threadIdx.x] = data_dots[data_index];
}
int centroid_index = threadIdx.x + blockIdx.y * blockDim.y;
if ((centroid_index < k) && (threadIdx.y == 1)) {
local_centroid_dots[threadIdx.x] = centroid_dots[centroid_index];
}
__syncthreads();
centroid_index = threadIdx.y + blockIdx.y * blockDim.y;
// printf("data_index=%d
// centroid_index=%d\n",data_index,centroid_index);
if ((data_index < n) && (centroid_index < k)) {
dots[data_index + centroid_index * n] =
local_data_dots[threadIdx.x] + local_centroid_dots[threadIdx.y];
}
}
template <typename T>
void make_all_dots(int n, int k, size_t offset,
thrust::device_vector<T> &data_dots,
thrust::device_vector<T> ¢roid_dots,
thrust::device_vector<T> &dots) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
const int BLOCK_THREADSX =
MAX_BLOCK_THREADS; // BLOCK_THREADSX*BLOCK_THREADSY<=1024
// on modern arch's (sm_61)
const int BLOCK_THREADSY = MAX_BLOCK_THREADS;
const int GRID_SIZEX =
(n - 1) / BLOCK_THREADSX +
1; // on old arch's this has to be less than 2^16=65536
const int GRID_SIZEY =
(k - 1) / BLOCK_THREADSY + 1; // this has to be less than 2^16=65536
// printf("pre all_dots: %d %d %d
// %d\n",GRID_SIZEX,GRID_SIZEY,BLOCK_THREADSX,BLOCK_THREADSY);
// fflush(stdout);
all_dots<<<dim3(GRID_SIZEX, GRID_SIZEY), dim3(BLOCK_THREADSX, BLOCK_THREADSY),
0, cuda_stream[dev_num]>>>(
n, k, thrust::raw_pointer_cast(data_dots.data() + offset),
thrust::raw_pointer_cast(centroid_dots.data()),
thrust::raw_pointer_cast(dots.data()));
#if (CHECK)
gpuErrchk(cudaGetLastError());
#endif
};
template <typename T>
void calculate_distances(int verbose, int q, size_t n, int d, int k,
thrust::device_vector<T> &data, size_t data_offset,
thrust::device_vector<T> ¢roids,
thrust::device_vector<T> &data_dots,
thrust::device_vector<T> ¢roid_dots,
thrust::device_vector<T> &pairwise_distances);
template <typename T, typename F>
void batch_calculate_distances(int verbose, int q, size_t n, int d, int k,
thrust::device_vector<T> &data,
thrust::device_vector<T> ¢roids,
thrust::device_vector<T> &data_dots,
thrust::device_vector<T> ¢roid_dots,
F functor) {
int fudges_size = 4;
double fudges[] = {1.0, 0.75, 0.5, 0.25};
for (const double fudge : fudges) {
try {
// Get info about available memory
// This part of the algo can be very memory consuming
// We might need to batch it
size_t free_byte;
size_t total_byte;
CUDACHECK(cudaMemGetInfo(&free_byte, &total_byte));
free_byte = free_byte * fudge;
size_t required_byte = n * k * sizeof(T);
size_t runs = std::ceil(required_byte / (double)free_byte);
log_verbose(verbose,
"Batch calculate distance - Rows %ld | K %ld | Data size %d",
n, k, sizeof(T));
log_verbose(verbose,
"Batch calculate distance - Free memory %zu | Required "
"memory %zu | Runs %d",
free_byte, required_byte, runs);
size_t offset = 0;
size_t rows_per_run = n / runs;
thrust::device_vector<T> pairwise_distances(rows_per_run * k);
for (int run = 0; run < runs; run++) {
if (run + 1 == runs && n % rows_per_run != 0) {
rows_per_run = n % rows_per_run;
}
thrust::fill_n(pairwise_distances.begin(), pairwise_distances.size(),
(T)0.0);
log_verbose(verbose, "Batch calculate distance - Allocated");
kmeans::detail::calculate_distances(verbose, 0, rows_per_run, d, k,
data, offset, centroids, data_dots,
centroid_dots, pairwise_distances);
log_verbose(verbose, "Batch calculate distance - Distances calculated");
functor(rows_per_run, offset, pairwise_distances);
log_verbose(verbose, "Batch calculate distance - Functor ran");
offset += rows_per_run;
}
} catch (const std::bad_alloc &e) {
cudaGetLastError();
if (fudges[fudges_size - 1] != fudge) {
log_warn(verbose,
"Batch calculate distance - Failed to allocate memory "
"for pairwise distances - retrying.");
continue;
} else {
log_error(verbose,
"Batch calculate distance - Failed to allocate "
"memory for pairwise distances - exiting.");
throw e;
}
}
return;
}
}
template <typename T>
__global__ void make_new_labels(int n, int k, T *pairwise_distances,
int *labels) {
T min_distance =
FLT_MAX; // std::numeric_limits<T>::max(); // might be ok TODO FIXME
T min_idx = -1;
int global_id = threadIdx.x + blockIdx.x * blockDim.x;
if (global_id < n) {
for (int c = 0; c < k; c++) {
T distance = pairwise_distances[c * n + global_id];
if (distance < min_distance) {
min_distance = distance;
min_idx = c;
}
}
labels[global_id] = min_idx;
}
}
template <typename T>
void relabel(int n, int k, thrust::device_vector<T> &pairwise_distances,
thrust::device_vector<int> &labels, size_t offset) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
#define MAX_BLOCK_THREADS2 256
const int GRID_SIZE = (n - 1) / MAX_BLOCK_THREADS2 + 1;
make_new_labels<<<GRID_SIZE, MAX_BLOCK_THREADS2, 0, cuda_stream[dev_num]>>>(
n, k, thrust::raw_pointer_cast(pairwise_distances.data()),
thrust::raw_pointer_cast(labels.data() + offset));
#if (CHECK)
gpuErrchk(cudaGetLastError());
#endif
}
} // namespace detail
} // namespace kmeans
namespace mycub {
extern void *d_key_alt_buf[MAX_NGPUS];
extern unsigned int key_alt_buf_bytes[MAX_NGPUS];
extern void *d_value_alt_buf[MAX_NGPUS];
extern unsigned int value_alt_buf_bytes[MAX_NGPUS];
extern void *d_temp_storage[MAX_NGPUS];
extern size_t temp_storage_bytes[MAX_NGPUS];
extern void *d_temp_storage2[MAX_NGPUS];
extern size_t temp_storage_bytes2[MAX_NGPUS];
extern bool cub_initted;
void sort_by_key_int(thrust::device_vector<int> &keys,
thrust::device_vector<int> &values);
template <typename T, typename U>
void sort_by_key(thrust::device_vector<T> &keys,
thrust::device_vector<U> &values) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
cudaStream_t this_stream = cuda_stream[dev_num];
int SIZE = keys.size();
if (key_alt_buf_bytes[dev_num] < sizeof(T) * SIZE) {
if (d_key_alt_buf[dev_num]) safe_cuda(cudaFree(d_key_alt_buf[dev_num]));
safe_cuda(cudaMalloc(&d_key_alt_buf[dev_num], sizeof(T) * SIZE));
key_alt_buf_bytes[dev_num] = sizeof(T) * SIZE;
std::cout << "Malloc key_alt_buf" << std::endl;
}
if (value_alt_buf_bytes[dev_num] < sizeof(U) * SIZE) {
if (d_value_alt_buf[dev_num]) safe_cuda(cudaFree(d_value_alt_buf[dev_num]));
safe_cuda(cudaMalloc(&d_value_alt_buf[dev_num], sizeof(U) * SIZE));
value_alt_buf_bytes[dev_num] = sizeof(U) * SIZE;
std::cout << "Malloc value_alt_buf" << std::endl;
}
cub::DoubleBuffer<T> d_keys(thrust::raw_pointer_cast(keys.data()),
(T *)d_key_alt_buf[dev_num]);
cub::DoubleBuffer<U> d_values(thrust::raw_pointer_cast(values.data()),
(U *)d_value_alt_buf[dev_num]);
cudaError_t err;
// Determine temporary device storage requirements for sorting operation
// if (temp_storage_bytes[dev_num] == 0) {
void *d_temp;
size_t temp_bytes;
err = cub::DeviceRadixSort::SortPairs(d_temp_storage[dev_num], temp_bytes,
d_keys, d_values, SIZE, 0,
sizeof(T) * 8, this_stream);
// Allocate temporary storage for sorting operation
safe_cuda(cudaMalloc(&d_temp, temp_bytes));
d_temp_storage[dev_num] = d_temp;
temp_storage_bytes[dev_num] = temp_bytes;
std::cout << "Malloc temp_storage. " << temp_storage_bytes[dev_num]
<< " bytes" << std::endl;
std::cout << "d_temp_storage[" << dev_num << "] = " << d_temp_storage[dev_num]
<< std::endl;
if (err) {
std::cout << "Error " << err << " in SortPairs 1" << std::endl;
std::cout << cudaGetErrorString(err) << std::endl;
}
//}
// Run sorting operation
err = cub::DeviceRadixSort::SortPairs(d_temp, temp_bytes, d_keys, d_values,
SIZE, 0, sizeof(T) * 8, this_stream);
if (err) std::cout << "Error in SortPairs 2" << std::endl;
// cub::DeviceRadixSort::SortPairs(d_temp_storage[dev_num],
// temp_storage_bytes[dev_num], d_keys,
// d_values, SIZE, 0, sizeof(T)*8,
// this_stream);
}
template <typename T>
void sum_reduce(thrust::device_vector<T> &values, T *sum) {
int dev_num;
safe_cuda(cudaGetDevice(&dev_num));
if (!d_temp_storage2[dev_num]) {
cub::DeviceReduce::Sum(d_temp_storage2[dev_num],
temp_storage_bytes2[dev_num],
thrust::raw_pointer_cast(values.data()), sum,
values.size(), cuda_stream[dev_num]);
// Allocate temporary storage for sorting operation
safe_cuda(
cudaMalloc(&d_temp_storage2[dev_num], temp_storage_bytes2[dev_num]));
}
cub::DeviceReduce::Sum(d_temp_storage2[dev_num], temp_storage_bytes2[dev_num],
thrust::raw_pointer_cast(values.data()), sum,
values.size(), cuda_stream[dev_num]);
}
void cub_init();
void cub_close();
void cub_init(int dev);
void cub_close(int dev);
} // namespace mycub
|
#ifndef DIELECTRIC_H
#define DIELECTRIC_H
#include "Material.h"
class Dielectric : public Material
{
public:
Dielectric(float ri) : ref_idx(ri) {}
virtual bool scatter(const Ray &rayIn, const hit_record &rec, vec3 &attenuation, Ray &scattered) const
{
vec3 outward_normal;
vec3 reflected = Reflect(rayIn.direction(), rec.normal);
float ni_over_nt;
attenuation = vec3(1.0f, 1.0f, 1.0f);
vec3 refracted;
float reflect_prob;
float cosine;
if (dot(rayIn.direction(), rec.normal) > 0)
{
outward_normal = -rec.normal;
ni_over_nt = ref_idx;
cosine = ref_idx * dot(rayIn.direction(), rec.normal) / rayIn.direction().length();
}
else
{
outward_normal = rec.normal;
ni_over_nt = 1.0f / ref_idx;
cosine = -dot(rayIn.direction(), outward_normal) / rayIn.direction().length();
}
if (Refract(rayIn.direction(), outward_normal, ni_over_nt, refracted))
{
reflect_prob = schlick(cosine, ref_idx);
}
else
{
//scattered = Ray(rec.p, reflected);
reflect_prob = 1.0f;
}
if ((rand() / (RAND_MAX + 1.0)) < reflect_prob)
{
scattered = Ray(rec.p, reflected);
}
else
{
scattered = Ray(rec.p, refracted);
}
return true;
}
float ref_idx;
};
#endif // !DIELECTRIC_H
|
//#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int used[8],L[15],R[15];
int in[8][8];
vector<int> locate[8];
void Queens(int n){
if(n >= 8){
for(int i=0;i<8;++i){
locate[i].push_back(used[i]);
}
return;
}
for(int i=0;i<8;++i){
if(used[i] == -1 && L[n-i+7] == -1 && R[n+i] == -1){
used[i] = L[n-i+7] = R[n+i] = n;
Queens(n+1);
used[i] = L[n-i+7] = R[n+i] = -1;
}
}
}
int main()
{
//freopen("./input.txt","r",stdin);
//freopen("./output.txt","w",stdout);
memset(used,-1,sizeof(used));
memset(L,-1,sizeof(L));
memset(R,-1,sizeof(R));
Queens(0);
int t;
scanf("%d",&t);
while(t--){
for(int i=0;i<8;++i)
for(int j=0;j<8;++j)
scanf("%d",&in[i][j]);
int ans = 0;
for(int i=0;i<92;++i){
int ta = 0;
for(int j=0;j<8;++j){
ta += in[j][locate[j][i]];
}
ans = max(ans, ta);
}
printf("%5d\n",ans);
}
return 0;
}
|
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved.
#pragma once
#include <IEngine.hpp>
namespace be::script
{
// SOL2 throws exceptions through error class derived from std::exception.
// And so we use it to provide high-level error description.
class ScriptSystem : public IEngine, public IEngine::Component
{
public:
ScriptSystem();
~ScriptSystem() = default;
ScriptSystem(const ScriptSystem&) = delete;
ScriptSystem(ScriptSystem&&) = delete;
ScriptSystem operator=(const ScriptSystem&) = delete;
ScriptSystem operator=(ScriptSystem&&) = delete;
public:
void initialize() override;
void run() override;
void finalize() override;
public:
sol::state& getLuaState() { return lua; }
public:
sol::state lua;
};
}
|
#include <string>
#include <vector>
#include <fstream>
#include <unistd.h>
#include <cstdio>
/* Width of each line in the table file, in bytes. */
const int TABLE_ENTRY_WIDTH = 5;
/**
* The Log class implements a generic, 1-indexed log that backs up to a file
* and can be recovered from a file. Individual log entries are immutable. As
* an optimization, log entries are recovered from file into the cache after a
* specified offset, so not all entries are required to be read at a time.
*
* When a Log is constructed, a table file is also generated. Deleting,
* moving, or otherwise modifying this table file may corrupt the entire log.
*/
template <typename T>
class Log {
public:
Log(std::string file_name,
std::function<std::string(const T&)> _serialize_entry,
std::function<T(std::string)> _deserialize_entry);
void clear();
void recover(int _offset = 0);
void trunc(int new_size);
void append(const T &entry);
/* Return the number of entries stored in the log. */
int size() const { return log_cache.size() + offset; }
/* Returns true if there are no entries stored in the log. */
bool empty() const { return size() == 0; }
T operator[](int i); // 1-INDEXED
private:
/* File to which the log entries are stored, one entry per line. */
std::string log_file;
/* Each line of this file is the byte length of the corresponding line in
* log_file. The lines in table_file are of a fixed length. */
std::string table_file;
std::function<std::string(const T&)> serialize_entry;
std::function<T(std::string)> deserialize_entry;
std::vector<T> log_cache;
/* The offset is the number of entries that are in the log file but not
* loaded into the cache. The first element of the cache is the log entry
* at index offset + 1. */
int offset {0};
size_t log_file_pos(int entry_offset);
};
/**
* Construct a log that stores entries of type T and backs up to the specified
* file. The user should provide a function to serialize an object of type T to
* a string and a function to deserialize a string that would be returned from
* the serialize function back into an object of type T. The serialized string
* of each entry is stored as a line in the log file.
*/
template <typename T>
Log<T>::Log(std::string file_name,
std::function<std::string(const T&)> _serialize_entry,
std::function<T(std::string)> _deserialize_entry)
: log_file(file_name),
table_file(file_name + "table"),
serialize_entry(_serialize_entry),
deserialize_entry(_deserialize_entry) {}
/**
* Clear resets the log by deleting the cache, log file, and table file.
*/
template <typename T>
void Log<T>::clear()
{
log_cache.clear();
std::remove(log_file.c_str());
std::remove(table_file.c_str());
}
/**
* Recover a log from the file specified in the constructor. Only the entries
* AFTER the offset index will be read into the in-memory cache. An offset of 0
* means all the entries will be read.
*/
template <typename T>
void Log<T>::recover(int _offset)
{
offset = _offset;
std::ifstream log_ifs(log_file, std::ios::binary);
log_ifs.seekg(log_file_pos(offset));
// read entries into cache
log_cache.clear();
for (std::string log_entry; std::getline(log_ifs, log_entry);) {
log_cache.push_back(deserialize_entry(log_entry));
}
}
/**
* Truncate the log to the specified size. If new_size >= current size or
* new_size is negative, this function has no effect.
*/
template <typename T>
void Log<T>::trunc(int new_size)
{
if (new_size < 0 || new_size >= size()) return;
// truncate() from unistd.h (see Linux man page for more info)
truncate(log_file.c_str(), log_file_pos(new_size));
log_cache.resize(new_size - offset > 0 ? new_size - offset : 0);
if (new_size < offset) offset = new_size;
}
/**
* Add an entry to the end of the log.
*/
template <typename T>
void Log<T>::append(const T &entry)
{
// add to file
std::ofstream log_ofs(log_file, std::ios::app | std::ios::binary);
std::ofstream table_ofs(table_file, std::ios::app | std::ios::binary);
std::string entry_str = serialize_entry(entry);
// Ensure the serialized string's length can be represented in the table
// file, the lines of which must be at most TABLE_ENTRY_WIDTH bytes wide.
if (entry_str.size() >= pow(10, TABLE_ENTRY_WIDTH - 1)) {
throw std::runtime_error("Serialized entry too large for log");
}
log_ofs << entry_str << "\n";
table_ofs << std::setfill('0') << std::setw(TABLE_ENTRY_WIDTH - 1)
<< entry_str.size() << "\n";
// add to cache
log_cache.push_back(entry);
}
/**
* Returns the log entry at index i.
*/
template <typename T>
T Log<T>::operator[](int i)
{
if (i < 1 || i > size()) throw std::runtime_error("Index out of bounds");
// cache hit
if (i > offset) return log_cache[i - offset - 1];
std::ifstream log_ifs(log_file, std::ios::binary);
log_ifs.seekg(log_file_pos(i - 1));
std::string entry;
std::getline(log_ifs, entry);
return deserialize_entry(entry);
}
/**
* Translates from entry_offset, which is the number of log entries being
* skipped, to a byte offset, which is the number of bytes in the log file that
* should be skipped in order to skip that many log entry lines.
*/
template <typename T>
size_t Log<T>::log_file_pos(int entry_offset)
{
std::ifstream table_ifs(table_file, std::ios::binary);
if (!table_ifs) throw std::runtime_error("Could not access table file");
int bytes = 0;
for (std::string table_entry; entry_offset > 0; entry_offset--) {
std::getline(table_ifs, table_entry);
bytes += std::stoi(table_entry) + 1;
}
return bytes;
}
|
#include <iostream>
#include "Instruction.hpp"
Instruction::Instruction() {}
FaceInstruction::FaceInstruction(FaceType face, bool clockwise)
: face(face), clockwise(clockwise) {}
void FaceInstruction::print() const {
char faceLetter{};
switch (face) {
case FaceType::FRONT:
faceLetter = 'F';
break;
case FaceType::UP:
faceLetter = 'U';
break;
case FaceType::BACK:
faceLetter = 'B';
break;
case FaceType::DOWN:
faceLetter = 'D';
break;
case FaceType::LEFT:
faceLetter = 'L';
break;
case FaceType::RIGHT:
faceLetter = 'R';
break;
}
std::cout << faceLetter << (clockwise ? "" : "'");
}
bool FaceInstruction::isFaceInstruction() const
{
return true;
}
FaceType FaceInstruction::getFace() const
{
return face;
}
bool FaceInstruction::isClockwise() const
{
return clockwise;
}
void FaceInstruction::setDirection(bool clockwise) {
this->clockwise = clockwise;
}
bool FaceInstruction::operator==(const FaceInstruction& other) const {
return face == other.face && clockwise == other.clockwise;
}
CubeInstruction::CubeInstruction(glm::vec3 axis)
: axis(axis) {}
void CubeInstruction::print() const {
char axisNotation{};
if (axis[0] == 1 || axis[0] == -1)
axisNotation = 'x';
else if (axis[1] == 1 || axis[1] == -1)
axisNotation = 'y';
else if (axis[2] == 1 || axis[2] == -1)
axisNotation = 'z';
else
axisNotation = '-';
std::cout << axisNotation << (axis[0] + axis[1] + axis[2] < 0 ? "'" : "");
}
glm::vec3 CubeInstruction::getAxis() const {
return axis;
}
bool CubeInstruction::isFaceInstruction() const
{
return false;
}
bool CubeInstruction::operator==(const CubeInstruction& other) const {
return axis == other.axis;
}
|
#ifndef __TIME_HH__
#define __TIME_HH__
#include <string>
#include <time.h>
using Clock = double;
inline std::string ClockToString(const Clock& clock) {
return std::to_string(clock);
}
namespace Time {
static clock_t __lapTime;
static constexpr Clock clockPerSec = (Clock)CLOCKS_PER_SEC;
static constexpr Clock clockPerMSec = (Clock)CLOCKS_PER_SEC/1000;
inline void Reset() {
__lapTime = clock();
}
inline clock_t __elpased() {
clock_t prev = __lapTime;
Time::Reset();
return (__lapTime - prev);
}
inline Clock ElapsedSec() {
return (Clock)__elpased()/clockPerSec;
}
inline Clock ElapsedMSec() {
return (Clock)__elpased()/clockPerMSec;
}
inline Clock GetClock() {
return (Clock)clock()/clockPerMSec;
}
};
#endif
|
/*
* Simon written by liamsdomain for arduino
* This code is public domain and free use
*/
//define button pins
#define butRed 8
#define butYel 9
#define butWhi 10
#define butGre 11
//define LED pins
#define ledRed 2
#define ledYel 3
#define ledWhi 4
#define ledGre 5
//variables used for button logic
//state is equal to the last state of the button
//lastMil is equal to the time when the button was last pressed, used to prevent bouncing
boolean state = false;
unsigned long lastMil = 0;
boolean state2 = false;
unsigned long lastMil2 = 0;
boolean state3 = false;
unsigned long lastMil3 = 0;
boolean state4 = false;
unsigned long lastMil4 = 0;
int order[20]; //keeps track of order of lights
int turn = 1; //turn number
int part = 0; //progress of current turn
boolean playing = true; //set to false when game has been lost/won
void setup() {
pinMode(butRed, INPUT_PULLUP); //setup pins
pinMode(butYel, INPUT_PULLUP);
pinMode(butWhi, INPUT_PULLUP);
pinMode(butGre, INPUT_PULLUP);
pinMode(ledRed, OUTPUT);
pinMode(ledYel, OUTPUT);
pinMode(ledWhi, OUTPUT);
pinMode(ledGre, OUTPUT);
Serial.begin(9600); //setup for debugging, un-needed
randomSeed(analogRead(0));
for(int i=0; i<=20; i++){ //set light order before game
order[i] = random(2,6); // 2 = red, 3 = yellow...
}
}
void lightsOn(){ //turn all lights on
for(int i = 2; i<=5; i++){
digitalWrite(i, HIGH);
}
}
void lightsOff(){ //turn all lights off
for(int i = 2; i<=5; i++){
digitalWrite(i, LOW);
}
}
void loop() {
if(playing && turn<=20){
//show light pattern at start of each turn
for(int i=0; i<turn; i++){
digitalWrite(order[i], HIGH);
delay(750);
digitalWrite(order[i], LOW);
delay(200);
}
//get button pushes
while(part<turn){
if(!digitalRead(butRed)!=state && lastMil+50<=millis()){
Serial.println("RED");
if(order[part]==2 && !state){
part++;
digitalWrite(2, HIGH); //flash light while button is down
}else if(!state){
//failure
part=22;//end loop (doesn't matter what number is used as long as it's above 21)
lightsOn();
playing = false;
} else {
digitalWrite(2, LOW);
}
state = !state;
lastMil = millis();
}else if(!digitalRead(butYel)!=state2 && lastMil2+50<=millis()){
Serial.println("YELLOW");
if(order[part]==3 && !state2){
part++;
digitalWrite(3, HIGH);
}else if(!state2){
//failure
part=22;//end loop
lightsOn();
playing = false;
} else {
digitalWrite(3, LOW);
}
state2 = !state2;
lastMil2 = millis();
} else if(!digitalRead(butWhi)!=state3 && lastMil3+50<=millis()){
Serial.println("WHITE");
if(order[part]==4 && !state3){
part++;
digitalWrite(4, HIGH);
}else if(!state3){
//failure
part=22;//end loop
lightsOn();
playing = false;
} else {
digitalWrite(4, LOW);
}
state3 = !state3;
lastMil3 = millis();
} else if(!digitalRead(butGre)!=state4 && lastMil4+50<=millis()){
Serial.println("GREEN");
if(order[part]==5 && !state4){
part++;
digitalWrite(5, HIGH);
}else if(!state4){
//failure
part=22;//end loop
lightsOn();
playing = false;
} else {
digitalWrite(5, LOW);
}
state4 = !state4;
lastMil4 = millis();
}
}
if(playing){
part = 0;
turn++;
delay(500);
lightsOff();
delay(500);
}
}else if (playing==21){
part = random(2,6);
digitalWrite(part, HIGH);
delay(250);
digitalWrite(part, LOW);
}
}
|
#include "incu8ator.h"
inline void incu8ator::clearSS(std::stringstream& ss) {
if(ss) {
ss.str("");
ss.clear();
}
}
void incu8ator::sdt(std::string& s) {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y.%m.%d %X", &tstruct);
s = buf;
}
void incu8ator::toogleHeating(int level) {
bcm2835_gpio_write(_heatGPIOPin, level);
}
void incu8ator::heatOn(void) {
toogleHeating(HIGH);
heating = true;
}
void incu8ator::heatOff(void) {
toogleHeating(LOW);
heating = false;
}
incu8ator::incu8ator(void) {
}
incu8ator::~incu8ator(void) {
if(p!=NULL) delete p;
if(s!=NULL) delete s;
if(d!=NULL) delete d;
}
/**
* Determine whether a sensor has connected or not.
* Check if the program wheel is available or not.
* Show the messages on the display.
* Check the GPIO port used to switch the heat-thread.
*/
bool incu8ator::initIncu8ator(std::string const sensorType, std::string displayType, int sensorGPIOPin, int heatGPIOPin, int readAlgorythm, double maxt, int maxse) {
log::inf("Starting the incu8ator...");
log::inf("Initializing the display...");
log::inf(std::string("Wanted display type is \'").append(displayType).append("\'"));
d = displayBase::createDisplay(displayType);
d->showMessage(std::string("Welcome on \"").append(displayType).append("\""));
d->showMessage("Waking up the sensor...");
log::inf("Waking up the sensor...");
s = sensorBase::createSensor(sensorType);
s->setGPIOPin(sensorGPIOPin);
s->setAlgorythm(readAlgorythm);
if(!s->helloSensor()) {
d->showMessage("No sensor was detected.");
log::err("No sensor was detected. Program ends.");
return false;
}
else {
d->showMessage(std::string("Used sensor type is \"").append(sensorType).append("\""));
log::inf(std::string("Used sensor type is \'").append(sensorType).append("\'"));
}
std::string errConfig = "";
p = new programWheel();
if(!p->initProgramWheel(errConfig)) {
log::err(std::string("Unable to init the program wheel: \'").append(errConfig).append("\'"));
return false;
}
_heatGPIOPin = heatGPIOPin;
bcm2835_gpio_fsel(_heatGPIOPin, BCM2835_GPIO_FSEL_OUTP);
maxTemp = maxt;
maxSensorError = maxse;
prevTemp = 0.0;
heating = true;
return true;
}
/**
* Start here the elapsed time counter of the program wheel (thread t1).
*/
void incu8ator::startIncu8ator(void) {
log::inf("Starting the program wheel...");
p->startProgramWheel();
}
/**
* @return false if the program wheel notices that there is no
* more program steps set. That means the while loop in the main
* must be stoped.
*/
bool incu8ator::controlTemp(void) {
if(s==NULL) return false;
if(p==NULL) return false;
double temp = 0.0;
double wantedTemp = 0.0;
double hum = 0.0;
std::string lines = "";
std::string lastError = "";
std::string dt = "";
std::stringstream ss;
sdt(dt);
// ask the sensor for the temp (and humidity if available)
s->readOut();
// check if there was an error in the sensor query
if(s->getCrcError(lastError)) {
int ec = s->getCrcErrorCounter();
// the maxSensorError is 5 by default;
// the query interval can not be bigger than 10seconds
// so 5*10seconds=50seconds, this is the maximum time
// the heating device can be turned on; assuming a ceramic heating
// wire within an insulated ca. 0.6m3 box the temperature increases
// ca. 1°C/15 seconds; this should mean not more than 5°C increase within the
// 50 seconds; assuming that the eggs needs ca. 38°C and the process
// ran well until this critical sensor error the inner temperature
// will be ca. 43°C which is not so critical and flammable.
if(ec>=maxSensorError) {
// turn off the heating just to avoid
// overheating in case of sensor error
heatOff();
clearSS(ss);
ss << "Too many errors after each other! (" << s->getCrcErrorCounter() << ")";
d->showMessage(ss.str());
}
clearSS(ss);
ss << "Sensor query error: " << lastError;
log::err(ss.str());
clearSS(ss);
ss << dt << ",0.0," << "0.0,\"" << lastError << "\"" << std::endl;
log::_reportQuery(ss.str());
// return with true because we do not need to stop the
// thermostat but need to stop the temperature control process
return true;
}
// inform the user the status of the internals
s->getFormattedLines(lines);
clearSS(ss);
ss << lines << std::endl << std::setprecision(3) << p->getElapsedHours() << "/" << p->getInterval() << "h";
d->showMessage(ss.str());
temp = s->getTemperature();
hum = s->getHumidity();
wantedTemp = p->getWantedTemperature();
clearSS(ss);
ss << dt << "," << temp << "," << hum << ",\"" << "\"" << std::endl;
log::_reportQuery(ss.str());
if(wantedTemp==0.0) {
d->showMessage("Program has done.\nIncu8ator has stoped.");
log::inf("Incu8ator has stoped because the program has done.");
return false;
}
else {
clearSS(ss);
ss << "Wanted/measured temp: " << wantedTemp << "/" << temp;
log::inf(ss.str());
// turn on or off the heating device here
if(temp<=wantedTemp) {
heatOn();
}
if(prevTemp<temp) {
heatOff();
}
if(temp>=wantedTemp) {
heatOff();
}
// emergency limit!
if(temp>=maxTemp) {
heatOff();
}
prevTemp = temp;
log::inf(std::string("Turn the heating ").append(((heating) ? "ON" : "OFF")));
}
return true;
}
|
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a, b;
while(scanf("%lld %lld",&a,&b) != EOF)
{
a >= b ? printf("%lld\n",a - b) : printf("%lld\n",b - a);
}
return 0;
}
|
#pragma once
//RightArrowKey.h
#ifndef _RIGHTARROWKEY_H
#define _RIGHTARROWKEY_H
#include "KeyAction.h"
class RightArrowKey :public KeyAction {
public:
RightArrowKey(Form *form = 0);
RightArrowKey(const RightArrowKey& source);
~RightArrowKey();
RightArrowKey& operator=(const RightArrowKey& source);
virtual void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
};
#endif //_RIGHTARROWKEY_H
|
#include "../include/eih_system.h"
/**
* EihSystem constructors and initializers
*/
EihSystem::EihSystem(rave::EnvironmentBasePtr e, Manipulator *m, KinectSensor *k) : env(e), manip(m), kinect(k) {
mat uMin, uMax;
manip->get_limits(uMin, uMax);
init(uMin, uMax);
}
EihSystem::EihSystem(rave::EnvironmentBasePtr e, Manipulator *m, KinectSensor *k,
ObsType obs_type) : env(e), manip(m), kinect(k) {
mat uMin, uMax;
manip->get_limits(uMin, uMax);
init(uMin, uMax, obs_type);
}
EihSystem::EihSystem(rave::EnvironmentBasePtr e, Manipulator *m, KinectSensor *k,
ObsType obs_type, int T) : env(e), manip(m), kinect(k) {
mat uMin, uMax;
manip->get_limits(uMin, uMax);
init(uMin, uMax, obs_type, T);
}
EihSystem::EihSystem(rave::EnvironmentBasePtr e, Manipulator *m, KinectSensor *k,
ObsType obs_type, int T, const mat &uMin, const mat &uMax) : env(e), manip(m), kinect(k) {
init(uMin, uMax, obs_type, T);
}
void EihSystem::init(const mat &uMin, const mat &uMax, ObsType obs_type, int T, double DT) {
mat j = manip->get_joint_values();
X_DIM = MAX(j.n_rows, j.n_cols);
U_DIM = X_DIM;
this->obs_type = obs_type;
mat R_diag;
// double height = kinect->get_height(), width = kinect->get_width();
// double min_range = kinect->get_min_range(), max_range = kinect->get_max_range(),
// optimal_range = kinect->get_optimal_range();
switch(obs_type) {
case ObsType::fov:
// R_diag << 100*height << 100*width << 1*(max_range - min_range);
// desired_observations = std::vector<mat>(1);
// desired_observations[0] << height/2 << width/2 << optimal_range;
break;
case ObsType::fov_occluded:
// R_diag << .5 << .01;
// desired_observations = std::vector<mat>(2);
// desired_observations[0] << 0 << UNKNOWN;
// desired_observations[1] << 1 << 1;
break;
case ObsType::fov_occluded_color:
default:
R_diag << .5 << .01 << .05 << 1 << 1;
desired_observations = std::vector<mat>(3);
desired_observations[0] << 0 << UNKNOWN << UNKNOWN << UNKNOWN << UNKNOWN; // outside FOV
desired_observations[1] << 1 << 1 << UNKNOWN << UNKNOWN << UNKNOWN; // inside FOV, occluded
desired_observations[2] << 1 << .5 << 0 << 1 << 1; // inside FOV, not occluded, red
break;
}
R = diagmat(R_diag);
Z_DIM = R.n_rows;
this->DT = DT;
manip->get_limits(xMin, xMax);
this->uMin = uMin;
this->uMax = uMax;
kinect->power_on();
boost::this_thread::sleep(boost::posix_time::seconds(2));
use_casadi = false;
}
/**
* EihSystem public methods
*/
mat EihSystem::dynfunc(const mat &x, const mat &u) {
int X_DIM = std::max(x.n_rows, x.n_cols);
mat x_new = x + DT*u;
for(int i=0; i < X_DIM; ++i) {
x_new(i) = MAX(x_new(i), xMin(i));
x_new(i) = MIN(x_new(i), xMax(i));
}
return x_new;
}
mat EihSystem::obsfunc(const mat& x, const mat& t, const mat& r) {
}
double EihSystem::obsfunc_continuous_weight(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
switch(obs_type) {
case ObsType::fov:
return obsfunc_continuous_weight_fov(particle, image, z_buffer, plot);
case ObsType::fov_occluded:
return obsfunc_continuous_weight_fov_occluded(particle, image, z_buffer, plot);
case ObsType::fov_occluded_color:
return obsfunc_continuous_weight_fov_occluded_color(particle, image, z_buffer, plot);
default:
return obsfunc_continuous_weight_fov_occluded_color(particle, image, z_buffer, plot);
}
}
double EihSystem::obsfunc_discrete_weight(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
switch(obs_type) {
case ObsType::fov:
return obsfunc_discrete_weight_fov(particle, image, z_buffer, plot);
case ObsType::fov_occluded:
return obsfunc_discrete_weight_fov_occluded(particle, image, z_buffer, plot);
case ObsType::fov_occluded_color:
return obsfunc_discrete_weight_fov_occluded_color(particle, image, z_buffer, plot);
default:
return obsfunc_discrete_weight_fov_occluded_color(particle, image, z_buffer, plot);
}
}
double EihSystem::obsfunc_continuous_weight_fov(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
// compute comparison
double height = kinect->get_height(), width = kinect->get_width();
double min_range = kinect->get_min_range(), max_range = kinect->get_max_range(),
optimal_range = kinect->get_optimal_range();
mat R_diag;
R_diag << 100*height << 100*width << 1*(max_range - min_range);
mat R = diagmat(R_diag);
mat z_low_weight;
z_low_weight << height/2 << width/2 << optimal_range;
// actual observation
mat z;
mat pixel = kinect->get_pixel_from_point(particle, false);
double y = pixel(0), x = pixel(1);
double d = norm(rave_utils::rave_vec_to_mat(kinect->get_pose().trans) - particle, 2);
z << y << x << d;
double max_likelihood = gauss_likelihood(zeros<mat>(Z_DIM,1), R);
mat e = z - z_low_weight;
double weight = (max_likelihood - gauss_likelihood(e.t(), R)) / max_likelihood;
if (plot) {
rave::Vector color = (weight > .5) ? rave::Vector(1, 1, 1) : rave::Vector(0, 1, 0);
rave::Vector particle_vec = rave_utils::mat_to_rave_vec(particle);
handles.push_back(rave_utils::plot_point(env, particle_vec, color));
}
return weight;
}
double EihSystem::obsfunc_discrete_weight_fov(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
double weight;
rave::Vector color;
if (!kinect->is_visible(particle)) {
weight = 1;
color = rave::Vector(0, 1, 0);
} else {
weight = 0;
color = rave::Vector(1, 1, 1);
}
if (plot) {
rave::Vector particle_vec = rave_utils::mat_to_rave_vec(particle);
handles.push_back(rave_utils::plot_point(env, particle_vec, color));
}
return weight;
}
double EihSystem::obsfunc_continuous_weight_fov_occluded(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
double weight;
rave::Vector color;
double fov_weight = obsfunc_continuous_weight_fov(particle, image, z_buffer, false);
if (kinect->is_visible(particle)) {
mat kinect_pos = rave_utils::rave_vec_to_mat(kinect->get_pose().trans);
double particle_dist = norm(particle - kinect_pos, 2);
mat pixel = kinect->get_pixel_from_point(particle);
int y = int(pixel(0)), x = int(pixel(1));
double sd = particle_dist - z_buffer(y, x);
double occluded_weight = sigmoid(sd, 5);
weight = std::max(fov_weight, occluded_weight);
color = (occluded_weight < .5) ? rave::Vector(1, 1, 1) : rave::Vector(0, 0, 0);
} else {
weight = fov_weight;
color = rave::Vector(0, 1, 0);
}
if (plot) {
rave::Vector particle_vec = rave_utils::mat_to_rave_vec(particle);
handles.push_back(rave_utils::plot_point(env, particle_vec, color));
}
return weight;
}
double EihSystem::obsfunc_discrete_weight_fov_occluded(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
double weight;
rave::Vector color;
if (!kinect->is_visible(particle)) {
weight = 1;
color = rave::Vector(0, 1, 0);
} else {
mat kinect_pos = rave_utils::rave_vec_to_mat(kinect->get_pose().trans);
double particle_dist = norm(particle - kinect_pos, 2);
mat pixel = kinect->get_pixel_from_point(particle);
int y = int(pixel(0)), x = int(pixel(1));
double sd = particle_dist - z_buffer(y, x);
if (sd > -.01) {
weight = 1;
color = rave::Vector(0, 0, 0);
} else {
weight = 0;
color = rave::Vector(1, 1, 1);
}
}
if (plot) {
rave::Vector particle_vec = rave_utils::mat_to_rave_vec(particle);
handles.push_back(rave_utils::plot_point(env, particle_vec, color));
}
return weight;
}
double EihSystem::obsfunc_continuous_weight_fov_occluded_color(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
double is_in_fov = UNKNOWN, sd_sigmoid = UNKNOWN;
mat color = UNKNOWN*ones<mat>(3,1);
mat pixel = kinect->get_pixel_from_point(particle);
int y = int(pixel(0)), x = int(pixel(1));
double alpha = 1e6;
mat boundary;
boundary << y << -y + kinect->get_height() << x << -x + kinect->get_width();
is_in_fov = prod(prod(sigmoid(boundary, alpha)));
is_in_fov = (1-.5)*is_in_fov + .5; // make being out of FOV not so advantageous for gauss likelihood
if (is_in_fov > .75) {
mat kinect_pos = rave_utils::rave_vec_to_mat(kinect->get_pose().trans);
double particle_dist = norm(particle - kinect_pos, 2);
mat pixel = kinect->get_pixel_from_point(particle);
int y = int(pixel(0)), x = int(pixel(1));
double sd = particle_dist - z_buffer(y, x);
sd_sigmoid = sigmoid(sd, 10);
if (fabs(sd) < .03) {
mat rgb = image.subcube(y,x,0,y,x,2);
color = utils::rgb_to_hsv(rgb);
}
sd_sigmoid = (1-.1)*sd_sigmoid + .1/2.0;
}
mat z(1, Z_DIM);
z(0) = is_in_fov;
z(1) = sd_sigmoid;
z(2) = color(0);
z(3) = color(1);
z(4) = color(2);
double weight = -INFINITY;
for(int i=0; i < desired_observations.size(); ++i) {
mat z_des = desired_observations[i];
mat e = z - z_des;
// deal with hue wrap-around
double hue_small = MIN(z(2), z_des(2));
double hue_large = MAX(z(2), z_des(2));
e(2) = MIN(hue_large - hue_small, hue_small + (1-hue_large));
weight = MAX(weight, gauss_likelihood(e.t(), R));
}
if (plot) {
if (z(0) <= .5) { // outside FOV
color << 0 << 1 << 0;
} else if (z(1) < .25) { // free space
color << 1 << 1 << 1;
} else if (z(1) > .75) { // occluded
color << 0 << 0 << 0;
} else { // near surface and red
color = image.subcube(y,x,0,y,x,2);
}
handles.push_back(rave_utils::plot_point(env, particle, color));
}
return weight;
}
double EihSystem::obsfunc_discrete_weight_fov_occluded_color(const mat &particle, const cube &image, const mat &z_buffer, bool plot) {
double weight;
rave::Vector color;
if (!kinect->is_visible(particle)) {
weight = 1;
color = rave::Vector(0, 1, 0);
} else {
mat kinect_pos = rave_utils::rave_vec_to_mat(kinect->get_pose().trans);
double particle_dist = norm(particle - kinect_pos, 2);
mat pixel = kinect->get_pixel_from_point(particle);
int y = int(pixel(0)), x = int(pixel(1));
double sd = particle_dist - z_buffer(y, x);
if (sd > .03) {
weight = 1;
color = rave::Vector(0, 0, 0);
} else if (sd < -.03) {
weight = 0;
color = rave::Vector(1, 1, 1);
} else {
mat rgb = image.subcube(y,x,0,y,x,2);
mat hsv = utils::rgb_to_hsv(rgb);
double dist_to_red = MIN(hsv(0), 1-hsv(0));
if (dist_to_red < .04) {
weight = 1.1;
color = rave_utils::mat_to_rave_vec(rgb);
} else {
weight = 0;
color = rave::Vector(1, 1, 0);
}
}
}
if (plot) {
rave::Vector particle_vec = rave_utils::mat_to_rave_vec(particle);
handles.push_back(rave_utils::plot_point(env, particle_vec, color));
}
return weight;
}
void EihSystem::update_state_and_particles(const mat& x_t, const mat& P_t, const mat& u_t, mat& x_tp1, mat& P_tp1) {
update_state_and_particles(x_t, P_t, u_t, x_tp1, P_tp1, false);
}
void EihSystem::update_state_and_particles(const mat& x_t, const mat& P_t, const mat& u_t, mat& x_tp1, mat& P_tp1, bool plot) {
handles.clear();
int M = P_t.n_cols;
x_tp1 = dynfunc(x_t, u_t);
manip->set_joint_values(x_tp1);
cube image = kinect->get_image(true);
mat z_buffer = kinect->get_z_buffer(false);
mat W(M, 1, fill::zeros);
for(int m=0; m < M; ++m) {
W(m) = obsfunc_discrete_weight(P_t.col(m), image, z_buffer, plot);
// W(m) = obsfunc_continuous_weight(P_t.col(m), image, z_buffer, plot);
}
W = W / accu(W);
double sampling_noise = uniform(0, 1/double(M));
P_tp1 = low_variance_sampler(P_t, W, sampling_noise);
// add noise to each particle
for(int m=0; m < M; ++m) {
mat noise = .01*randu<mat>(3,1) - .005;
P_tp1.col(m) += noise;
}
}
double EihSystem::cost(const std::vector<mat>& X, const std::vector<mat>& U, const mat& P) {
double entropy = 0;
int M = P.n_cols;
int T = U.size()+1;
manip->set_joint_values(X[0]);
mat W_t = (1/double(M))*ones<mat>(M, 1), W_tp1(M, 1, fill::zeros);
for(int t=0; t < T-1; ++t) {
mat x_tp1 = dynfunc(X[t], U[t]);
manip->set_joint_values(x_tp1);
cube image = kinect->get_image(true);
mat z_buffer = kinect->get_z_buffer(false);
for(int m=0; m < M; ++m) {
W_tp1(m) = obsfunc_continuous_weight(P.col(m), image, z_buffer) * W_t(m);
}
W_tp1 = W_tp1 / accu(W_tp1);
entropy += accu(-W_tp1 % log(W_tp1));
W_t = W_tp1;
}
manip->set_joint_values(X[0]);
return entropy;
}
double EihSystem::cost(const mat &x0, const std::vector<mat>& U, const mat& P) {
int T = U.size()+1;
std::vector<mat> X(T);
X[0] = x0;
for(int t=0; t < T-1; ++t) {
X[t+1] = dynfunc(X[t], U[t]);
}
return cost(X, U, P);
}
mat EihSystem::cost_grad(std::vector<mat>& X, std::vector<mat>& U, const mat& P) {
return System::cost_grad(X, U, P);
}
mat EihSystem::cost_grad(const mat &x0, std::vector<mat>& U, const mat& P) {
int T = U.size()+1;
mat g(U_DIM*(T-1), 1, fill::zeros);
double orig, cost_p, cost_l;
int index = 0;
for(int t=0; t < T-1; ++t) {
for(int i=0; i < U_DIM; ++i) {
orig = U[t](i);
U[t](i) = orig + step;
cost_p = this->cost(x0, U, P);
U[t](i) = orig - step;
cost_l = this->cost(x0, U, P);
U[t][i] = orig;
g(index++) = (cost_p - cost_l)/(2*step);
}
}
return g;
}
// plots kinect position
void EihSystem::display_states_and_particles(const std::vector<mat>& X, const mat& P, bool pause) {
handles.clear();
int M = P.n_cols;
mat color;
color << 0 << 0 << 1;
for(int m=0; m < M; ++m) {
handles.push_back(rave_utils::plot_point(env, P.col(m), color));
}
int T = X.size();
double hue_start = 120.0/360, hue_end = 0.0/360;
mat initial_joints = manip->get_joint_values();
for(int t=0; t < T; ++t) {
manip->set_joint_values(X[t]);
mat hsv;
hsv << hue_start + (hue_end - hue_start)*(t/double(T)) << 1 << 1;
rave::Vector color = rave_utils::mat_to_rave_vec(utils::hsv_to_rgb(hsv));
handles.push_back(rave_utils::plot_point(env, kinect->get_pose().trans, color));
rave_utils::plot_transform(env, kinect->get_pose(), handles);
}
manip->set_joint_values(initial_joints);
if (pause) {
LOG_INFO("Press enter to continue");
std::cin.ignore();
}
}
|
/**********************************
* FILE NAME: MP2Node.cpp
*
* DESCRIPTION: MP2Node class definition
**********************************/
#include "MP2Node.h"
/**
* constructor
*/
MP2Node::MP2Node(Member *memberNode, Params *par, EmulNet * emulNet, Log * log, Address * address) {
this->memberNode = memberNode;
this->par = par;
this->emulNet = emulNet;
this->log = log;
ht = new HashTable();
this->memberNode->addr = *address;
this->transaction_id = 0; //set transaction id to begin with 0 for this node
}
/**
* Destructor
*/
MP2Node::~MP2Node() {
delete ht;
delete memberNode;
}
/**
*
* Short print function for printing address. For debugging purpose only.
*/
void MP2Node::printAddress(Address *addr) {
printf("%d.%d.%d.%d:%d ", addr->addr[0], addr->addr[1], addr->addr[2], addr->addr[3], *(short *)&addr->addr[4]);
}
/**
* FUNCTION NAME: updateRing
*
* DESCRIPTION: This function does the following:
* 1) Gets the current membership list from the Membership Protocol (MP1Node)
* The membership list is returned as a vector of Nodes. See Node class in Node.h
* 2) Constructs the ring based on the membership list
* 3) Calls the Stabilization Protocol
*/
void MP2Node::updateRing() {
/*
* Implement this. Parts of it are already implemented
*/
vector<Node> curMemList;
bool change = false;
/*
* Step 1. Get the current membership list from Membership Protocol / MP1
*/
curMemList = getMembershipList();
/*
* Step 2: Construct the ring
*/
// Sort the list based on the hashCode
sort(curMemList.begin(), curMemList.end());
//check if stablization required or not by checking the change in ring
change = isRingSame(curMemList);
//If the ring has changed or it was empty before assign ring the new Member List
if (ring.empty() || change)
ring = curMemList;
//Initially when hasMyReplicas and haveReplicasOf is empty initialize those variables for this node
if (hasMyReplicas.empty() || haveReplicasOf.empty())
assignReplicationNodes();
/*
* Step 3: Run the stabilization protocol IF REQUIRED
*/
//Run stabilization protocol if the hash table size is greater than zero and if there has been a changed in the ring
cout << "Stablization required = " << change << endl;
// If stablization is required run stablization protocol.
if (change && !ht->isEmpty())
stabilizationProtocol();
}
/**
* FUNCTION NAME: getMemberhipList
*
* DESCRIPTION: This function goes through the membership list from the Membership protocol/MP1 and
* i) generates the hash code for each member
* ii) populates the ring member in MP2Node class
* It returns a vector of Nodes. Each element in the vector contain the following fields:
* a) Address of the node
* b) Hash code obtained by consistent hashing of the Address
*/
vector<Node> MP2Node::getMembershipList() {
unsigned int i;
vector<Node> curMemList;
for ( i = 0 ; i < this->memberNode->memberList.size(); i++ ) {
Address addressOfThisMember;
int id = this->memberNode->memberList.at(i).getid();
short port = this->memberNode->memberList.at(i).getport();
memcpy(&addressOfThisMember.addr[0], &id, sizeof(int));
memcpy(&addressOfThisMember.addr[4], &port, sizeof(short));
curMemList.emplace_back(Node(addressOfThisMember));
}
return curMemList;
}
/**
* FUNCTION NAME: hashFunction
*
* DESCRIPTION: This functions hashes the key and returns the position on the ring
* HASH FUNCTION USED FOR CONSISTENT HASHING
*
* RETURNS:
* size_t position on the ring
*/
size_t MP2Node::hashFunction(string key) {
std::hash<string> hashFunc;
size_t ret = hashFunc(key);
return ret%RING_SIZE;
}
/**
* FUNCTION NAME: clientCreate
*
* DESCRIPTION: client side CREATE API
* The function does the following:
* 1) Constructs the message
* 2) Finds the replicas of this key
* 3) Sends a message to the replica
*/
void MP2Node::clientCreate(string key, string value) {
/*
* Implement this
*/
/*
* Hash the key and modulo by number of members in the ring
* Find the Node where that key should be present
* Also, replicate that key on the next 2 neighbors
* Message all those nodes to save this key
*/
// find the destination 3 nodes where this key needs to go
vector<Node> destination_nodes = findNodes(key);
// print the location of nodes just for debugging
for(int i = 0; i < destination_nodes.size(); i++){
cout << "Key = " << key << " Replica = ";
printAddress(destination_nodes[i].getAddress());
cout << endl;
}
// Create a create message with key and value and replica type and send each replica create message according to its type
Message *msg;
ReplicaType type;
for (int i = 0; i < RF; i++){ // Loop over each replica
type = static_cast<ReplicaType>(i); // convert int type into enum ReplicaType
msg = new Message(this->transaction_id, getMemberNode()->addr, CREATE, key, value, type); //create a create type message
emulNet->ENsend(&getMemberNode()->addr, destination_nodes[i].getAddress(), msg->toString());
free(msg); // free message
}
// Increment this node transaction_id and set other transaction details like key, value and MessageType
initTransactionCount(this->transaction_id++, key, value, CREATE);
}
/**
* FUNCTION NAME: clientRead
*
* DESCRIPTION: client side READ API
* The function does the following:
* 1) Constructs the message
* 2) Finds the replicas of this key
* 3) Sends a message to the replica
*/
void MP2Node::clientRead(string key){
/*
* Implement this
*/
// find the destination 3 nodes where this key needs to go
vector<Node> destination_nodes = findNodes(key);
// Create a read message with key and send each replica this message
Message *msg;
for (int i = 0; i < RF; i++){
msg = new Message(this->transaction_id, getMemberNode()->addr, READ, key);
emulNet->ENsend(&getMemberNode()->addr, destination_nodes[i].getAddress(), msg->toString());
free(msg);
}
// Increment this node transaction_id and set other transaction details like key, value and MessageType
initTransactionCount(this->transaction_id++, key, "", READ);
}
/**
* FUNCTION NAME: clientUpdate
*
* DESCRIPTION: client side UPDATE API
* The function does the following:
* 1) Constructs the message
* 2) Finds the replicas of this key
* 3) Sends a message to the replica
*/
void MP2Node::clientUpdate(string key, string value){
/*
* Implement this
*/
//find the destination 3 nodes where this key needs to go
vector<Node> destination_nodes = findNodes(key);
// Create a update message with key and value and send each replica this message according to their type
Message *msg;
ReplicaType type;
for (int i = 0; i < RF; i++){
type = static_cast<ReplicaType>(i);
msg = new Message(this->transaction_id, getMemberNode()->addr, UPDATE, key, value, type);
emulNet->ENsend(&getMemberNode()->addr, destination_nodes[i].getAddress(), msg->toString());
free(msg);
}
// Increment this node transaction_id and set other transaction details like key, value and MessageType
initTransactionCount(this->transaction_id++, key, value, UPDATE);
}
/**
* FUNCTION NAME: clientDelete
*
* DESCRIPTION: client side DELETE API
* The function does the following:
* 1) Constructs the message
* 2) Finds the replicas of this key
* 3) Sends a message to the replica
*/
void MP2Node::clientDelete(string key){
/*
* Implement this
*/
//find the destination 3 nodes where this key needs to go
vector<Node> destination_nodes = findNodes(key);
// Create a delete message with key and send each replica this message
Message *msg;
for (int i = 0; i < RF; i++){
msg = new Message(this->transaction_id, getMemberNode()->addr, DELETE, key);
emulNet->ENsend(&getMemberNode()->addr, destination_nodes[i].getAddress(), msg->toString());
free(msg);
}
// Increment this node transaction_id and set other transaction details like key, value and MessageType
initTransactionCount(this->transaction_id++, key, "", DELETE);
}
/**
* FUNCTION NAME: createKeyValue
*
* DESCRIPTION: Server side CREATE API
* The function does the following:
* 1) Inserts key value into the local hash table
* 2) Return true or false based on success or failure
*/
bool MP2Node::createKeyValue(string key, string value, ReplicaType replica) {
/*
* Implement this
*/
// Insert key, value, replicaType into the hash table
// Use entry class object to convert the information into string
Entry e(value, par->getcurrtime(), replica);
return ht->create(key, e.convertToString()); //insert key and value in local hashtable and return the status
}
/**
* FUNCTION NAME: readKey
*
* DESCRIPTION: Server side READ API
* This function does the following:
* 1) Read key from local hash table
* 2) Return value
*/
string MP2Node::readKey(string key) {
/*
* Implement this
*/
// Read key from local hash table and return value
return ht->read(key); // read the value in local hashtable and return the value
}
/**
* FUNCTION NAME: updateKeyValue
*
* DESCRIPTION: Server side UPDATE API
* This function does the following:
* 1) Update the key to the new value in the local hash table
* 2) Return true or false based on success or failure
*/
bool MP2Node::updateKeyValue(string key, string value, ReplicaType replica) {
/*
* Implement this
* */
// Update key in local hash table and return true or false
// Use entry class object to convert the information into string
Entry e(value, par->getcurrtime(), replica);
return ht->update(key, e.convertToString()); // update key and value in local hashtable and return the status
}
/**
* FUNCTION NAME: deleteKey
*
* DESCRIPTION: Server side DELETE API
* This function does the following:
* 1) Delete the key from the local hash table
* 2) Return true or false based on success or failure
*/
bool MP2Node::deletekey(string key) {
/*
* Implement this
*
* */
// Delete the key from the local hash table
return ht->deleteKey(key); // delete the key in local hashtable and return the status
}
/**
* FUNCTION NAME: checkMessages
*
* DESCRIPTION: This function is the message handler of this node.
* This function does the following:
* 1) Pops messages from the queue
* 2) Handles the messages according to message types
*/
void MP2Node::checkMessages() {
/*
* Implement this. Parts of it are already implemented
*/
char * data;
int size;
/*
* Declare your local variables here
*/
// dequeue all messages and handle them
while ( !memberNode->mp2q.empty() ) {
/*
* Pop a message from the queue
*/
data = (char *)memberNode->mp2q.front().elt;
size = memberNode->mp2q.front().size;
memberNode->mp2q.pop();
string message(data, data + size);
/*
* Handle the message types here
*/
cout << "Got message = " << message << endl;
Message incoming_msg(message); //convert the message in string form to Message type
//check for message type and call their handlers accordingly.
switch(incoming_msg.type) {
case CREATE : {processCreate(incoming_msg); break;}
case READ : {processRead(incoming_msg); break;}
case REPLY : {processNodesReply(incoming_msg); break;}
case READREPLY : {processReadReply(incoming_msg);break;}
case DELETE : {processDelete(incoming_msg); break;}
case UPDATE : {processUpdate(incoming_msg); break;}
default : {}
}
}
// At the end check the acks or nacks that this node may have received from the reply messages from the nodes to
// whom this node may sent the client CRUD message
checkReplyMessages();
/*
* This function should also ensure all READ and UPDATE operation
* get QUORUM replies
*/
}
// comparator that sorts the entry object by timestamp in descending order.
struct by_entry_timestamp {
bool operator()(pair<int, string> const &a, pair<int, string> const &b) const {
Entry e1(a.second);
Entry e2(b.second);
return e1.timestamp > e2.timestamp;
}
};
//pass the transaction count map iterator to this function to log the success according to the message type
// These log messages are the messages of coordinator
void MP2Node::logCoordinatorSuccess(map<int, transaction_details>::iterator it) {
switch(this->transaction_count[it->first].rep_type){
case CREATE : {log->logCreateSuccess(&getMemberNode()->addr, true, it->first, it->second.key, it->second.value); break;}
case DELETE : {log->logDeleteSuccess(&getMemberNode()->addr, true, it->first, it->second.key); break;}
case READ : {
if (!it->second.value.empty()){ // print Sucess only when value returned is not invalid i.e. ""
// Sort the value by timestamp and return the value with highest timestamp.
sort(transaction_count[it->first].ackStore.begin(), transaction_count[it->first].ackStore.end(), by_entry_timestamp());
log->logReadSuccess(&getMemberNode()->addr, true, it->first, it->second.key, transaction_count[it->first].ackStore[0].second);
}
else // otherwise log failure
log->logReadFail(&getMemberNode()->addr, true, it->first, it->second.key);
break;
}
case UPDATE : {log->logUpdateSuccess(&getMemberNode()->addr, true, it->first, it->second.key, it->second.value); break;}
default: {}
}
cout << "Success transaction for transaction_id = " << it->first << ". Count is " << it->second.reply_count << " for key = " << it->second.key << " and value = " << it->second.value << endl;
this->transaction_count.erase(it->first); // Now erase the transaction as it will not be used again
}
//pass the transaction count map iterator to this function to log the failure according to the message type
// These log messages are the messages of coordinator
void MP2Node::logCoordinatorFailure(map<int, transaction_details>::iterator it) {
switch(this->transaction_count[it->first].rep_type){
case CREATE : {log->logCreateFail(&getMemberNode()->addr, true, it->first, it->second.key, it->second.value); break;}
case DELETE : {log->logDeleteFail(&getMemberNode()->addr, true, it->first, it->second.key); break;}
case READ : {log->logReadFail(&getMemberNode()->addr, true, it->first, it->second.key); break;}
case UPDATE : {log->logUpdateFail(&getMemberNode()->addr, true, it->first, it->second.key, it->second.value); break;}
default: {}
}
cout << "Failed transaction for transaction_id = " << it->first << ". Count is " << it->second.reply_count << " for key = " << it->second.key << " and value = " << it->second.value << endl;
this->transaction_count.erase(it->first); // Now erase the transaction
}
//Check the reply message received at the coordinator
void MP2Node::checkReplyMessages() {
int curr_time = par->getcurrtime(); //get current time
map<int, transaction_details>::iterator it = this->transaction_count.begin();
cout << "For server = ";
printAddress(&getMemberNode()->addr);
cout << endl;
pair<int, int> rep_count;
int acks = 0, nacks = 0;
while(it != this->transaction_count.end()) { // iterate over each pending transaction whose ack or nack not received.
rep_count = this->countAcks(it->first); // count the number of acks and nacks
acks = rep_count.first; nacks = rep_count.second;
if ( (acks + nacks) <= 2){
if (acks == 2){ // if ack == 2, the quorum in +ve replies so, log success at coordinator
this->logCoordinatorSuccess(it);
} else { // otherwise check if the reply by the server has timeout. If yes, then log failure
if ((curr_time - it->second.timestamp) >= Reply_Timeout) {
this->logCoordinatorFailure(it);
}
}
} else {
if (acks < nacks){ // if acks < nacks when count = 3, then check for timeout and log failure if necessary.
if ((curr_time - it->second.timestamp) >= Reply_Timeout) {
this->logCoordinatorFailure(it);
}
} else { // Otherwise log success at coordinator.
this->logCoordinatorSuccess(it);
}
}
it++;
}
}
/**
* FUNCTION NAME: findNodes
*
* DESCRIPTION: Find the replicas of the given keyfunction
* This function is responsible for finding the replicas of a key
*/
vector<Node> MP2Node::findNodes(string key) {
size_t pos = hashFunction(key);
vector<Node> addr_vec;
if (ring.size() >= 3) {
// if pos <= min || pos > max, the leader is the min
if (pos <= ring.at(0).getHashCode() || pos > ring.at(ring.size()-1).getHashCode()) {
addr_vec.emplace_back(ring.at(0));
addr_vec.emplace_back(ring.at(1));
addr_vec.emplace_back(ring.at(2));
}
else {
// go through the ring until pos <= node
for (int i=1; i<ring.size(); i++){
Node addr = ring.at(i);
if (pos <= addr.getHashCode()) {
addr_vec.emplace_back(addr);
addr_vec.emplace_back(ring.at((i+1)%ring.size()));
addr_vec.emplace_back(ring.at((i+2)%ring.size()));
break;
}
}
}
}
return addr_vec;
}
/**
* FUNCTION NAME: recvLoop
*
* DESCRIPTION: Receive messages from EmulNet and push into the queue (mp2q)
*/
bool MP2Node::recvLoop() {
if ( memberNode->bFailed ) {
return false;
}
else {
return emulNet->ENrecv(&(memberNode->addr), this->enqueueWrapper, NULL, 1, &(memberNode->mp2q));
}
}
/**
* FUNCTION NAME: enqueueWrapper
*
* DESCRIPTION: Enqueue the message from Emulnet into the queue of MP2Node
*/
int MP2Node::enqueueWrapper(void *env, char *buff, int size) {
Queue q;
return q.enqueue((queue<q_elt> *)env, (void *)buff, size);
}
/**
* FUNCTION NAME: stabilizationProtocol
*
* DESCRIPTION: This runs the stabilization protocol in case of Node joins and leaves
* It ensures that there always 3 copies of all keys in the DHT at all times
* The function does the following:
* 1) Ensures that there are three "CORRECT" replicas of all the keys in spite of failures and joins
* Note:- "CORRECT" replicas implies that every key is replicated in its two neighboring nodes in the ring
*/
void MP2Node::stabilizationProtocol() {
/*
* Implement this
*/
cout << "In stablization " << endl;
vector<Node> new_replicas, new_bosses;
Node this_node = Node(getMemberNode()->addr); // Current Node
for (int i = 0; i < ring.size(); i++) {
if (isNodeSame(ring[i], this_node)) { // When we find the current node, assign the new replicas and predecessors(bosses) using same technique used in assignReplicationNodes()
if (i == 0) {
new_bosses.push_back(Node(*ring[ring.size() - 1].getAddress()));
new_bosses.push_back(Node(*ring[ring.size() - 2].getAddress()));
}else if (i == 1){
new_bosses.push_back(Node(*ring[0].getAddress()));
new_bosses.push_back(Node(*ring[ring.size() - 1].getAddress()));
} else {
new_bosses.push_back(Node(*ring[(i - 1) % ring.size()].getAddress()));
new_bosses.push_back(Node(*ring[(i - 2) % ring.size()].getAddress()));
}
new_replicas.push_back(Node(*ring[(i + 1) % ring.size()].getAddress()));
new_replicas.push_back(Node(*ring[(i + 2) % ring.size()].getAddress()));
}
}
// CHeck new replicas first
for (int i = 0; i < new_replicas.size(); i++) {
if (isNodeSame(hasMyReplicas[i], new_replicas[i])) { // if the previous replica is again at same location then continue.
continue;
}
else {
// if this is the not the new replica for this key but its location has changed from Tertiary to Secondary because of failure of secondary.
if (ifExistNode(hasMyReplicas, new_replicas[i]) != -1) {
vector<pair<string, string>> keys = findMyKeys(PRIMARY); //then find all the primary keys at this server and send update message to the server to change its replica type.
Message *msg;
for (int k = 0; k < keys.size(); k++) { // for each primary key at this node update the replica type of the node which has now become secondary from tertiary.
msg = new Message(-1, getMemberNode()->addr, UPDATE, keys[k].first, keys[k].second, static_cast<ReplicaType>(i + 1));
emulNet->ENsend(&getMemberNode()->addr, new_replicas[i].getAddress(), msg->toString());
free(msg);
}
} else {
// if this is the new node that is now a replica, find all the primary keys at this node and send create messages to new node to insert those keys into their hashtable.
vector<pair<string, string>> keys = findMyKeys(PRIMARY);
Message *msg;
for (int k = 0; k < keys.size(); k++) {
msg = new Message(-1, getMemberNode()->addr, CREATE, keys[k].first, keys[k].second, static_cast<ReplicaType>(i + 1));
emulNet->ENsend(&getMemberNode()->addr, new_replicas[i].getAddress(), msg->toString());
free(msg);
}
}
}
}
// check for my bosses if they failed
for (int i = 0; i < haveReplicasOf.size(); i++) {
if (isNodeSame(haveReplicasOf[i], new_bosses[i])) {
break; // if the boss is same and at same location, then break because boss will take care of its boss and will also correct this nodes replica type if necessary as is shown below.
}
else {
if (ifExistNode(new_bosses, haveReplicasOf[i]) != -1) {
break; // if there is some boss present which was also present earlier then don't do anything as it will take care of things and nodes in this system only leave, no join is there'
} else {
// else find keys at this node which are secondary or tertiary depending on how this node is located according to the new boss.
vector<pair<string, string>> keys = findMyKeys(static_cast<ReplicaType>(i + 1));
Entry *e; // Update keys at this local server. No need to send message since all the operations are local.
for (int k = 0; k < keys.size(); k++){
e = new Entry(keys[k].second, par->getcurrtime(), PRIMARY);
ht->update(keys[k].first, e->convertToString());
free(e);
}
if (i == 0){ // If this was the secondary replica of the failed boss, then make your first replica secondary from tertiary by updating it.
// Also, add new tertiary replica by sending create messages for all the keys of the bosses which have now become primary at this server.
Message *msg;
for (int k = 0; k < keys.size(); k++) {
if (isNodeSame(new_replicas[0], hasMyReplicas[0])){
msg = new Message(-1, getMemberNode()->addr, UPDATE, keys[k].first, keys[k].second, SECONDARY);
emulNet->ENsend(&getMemberNode()->addr, new_replicas[0].getAddress(), msg->toString());
} else {
msg = new Message(-1, getMemberNode()->addr, CREATE, keys[k].first, keys[k].second, SECONDARY);
emulNet->ENsend(&getMemberNode()->addr, new_replicas[0].getAddress(), msg->toString());
}
free(msg);
msg = new Message(-1, getMemberNode()->addr, CREATE, keys[k].first, keys[k].second, TERTIARY);
emulNet->ENsend(&getMemberNode()->addr, new_replicas[1].getAddress(), msg->toString());
free(msg);
}
} else if (i == 1){
// If this was the tertiary replica of the failed boss, then add both of your replicas
// by sending create messages for all the keys of the bosses which have now become primary at this server.
Message *msg;
for (int k = 0; k < keys.size(); k++) {
msg = new Message(-1, getMemberNode()->addr, CREATE, keys[k].first, keys[k].second, SECONDARY);
emulNet->ENsend(&getMemberNode()->addr, new_replicas[0].getAddress(), msg->toString());
free(msg);
msg = new Message(-1, getMemberNode()->addr, CREATE, keys[k].first, keys[k].second, TERTIARY);
emulNet->ENsend(&getMemberNode()->addr, new_replicas[1].getAddress(), msg->toString());
free(msg);
}
}
}
}
}
// Now update the new replicas and bosses
hasMyReplicas = new_replicas;
haveReplicasOf = new_bosses;
}
// Find Keys at this server that are residing here as of specific replica type.
vector<pair<string, string>> MP2Node::findMyKeys(ReplicaType rep_type) {
map<string, string>::iterator iterator1 = ht->hashTable.begin();
vector<pair<string, string>> keys;
Entry *temp_e;
while (iterator1 != ht->hashTable.end()){ // Loop over all the keys in the hashtable and find the key that belong to the passed replica type
temp_e = new Entry(iterator1->second);
if (temp_e->replica == rep_type){
keys.push_back(pair<string, string>(iterator1->first, temp_e->value));
}
iterator1++;
free(temp_e); // free the entry variable
}
return keys; // return vector of pair of keys and values.
}
/*
* Check if 2 nodes are same by checking their address are same or not using memcmp
* */
bool MP2Node::isNodeSame(Node n1, Node n2){
if (memcmp(n1.getAddress()->addr, n2.getAddress()->addr, sizeof(Address)) == 0)
return true;
return false;
}
/*
* Check if some vector of nodes contain a given node.
* */
int MP2Node::ifExistNode(vector<Node> v, Node n1){
vector<Node>::iterator iterator1 = v.begin();
int i = 0;
while(iterator1 != v.end()){ // iterate over each node in the vector
if (isNodeSame(n1, *iterator1)) // if the nodes are same return the location otherwise return -1
return i;
iterator1++;
i++;
}
return -1;
}
// Handle the create message coming at its correct destinations
void MP2Node::processCreate(Message incoming_msg) {
// Call the server local function to insert key and value into its local hash table according to replica type.
bool success_status = createKeyValue(incoming_msg.key, incoming_msg.value, incoming_msg.replica);
int _trans_id = incoming_msg.transID; // get trans_id from the incoming message
Address to_addr(incoming_msg.fromAddr); // get the coordinator address from where this message came
if (_trans_id < 0) //if stablization came with trans_id = -1. This is special type of message that comes when ring repair work is going on. So, don't send its reply
return;
Message *msg = new Message(_trans_id, getMemberNode()->addr, REPLY, success_status);
emulNet->ENsend(&getMemberNode()->addr, &to_addr, msg->toString()); // send reply message back to the coordinator
// if the local create operation returned success then log server success otherwise log failure.
if (success_status)
log->logCreateSuccess(&getMemberNode()->addr, false, _trans_id, incoming_msg.key, incoming_msg.value);
else
log->logCreateFail(&getMemberNode()->addr, false, _trans_id, incoming_msg.key, incoming_msg.value);
// free the message variable.
free(msg);
}
// Handle the read message coming at its correct destinations
void MP2Node::processRead(Message incoming_msg) {
// Call the server local function to read key and return value from its local hash table.
string read_value = readKey(incoming_msg.key);
cout << "Read from local " << read_value << " for key = " << incoming_msg.key << endl;
int _trans_id = incoming_msg.transID; // get trans_id from the incoming message
Address to_addr(incoming_msg.fromAddr); // get the coordinator address from where this message came
if (_trans_id < 0)//if stablization came with trans_id = -1. This is special type of message that comes when ring repair work is going on. So, don't send its reply
return;
Message *msg = new Message(_trans_id, getMemberNode()->addr, read_value); // send ReadReply message back to the coordinator
emulNet->ENsend(&getMemberNode()->addr, &to_addr, msg->toString());
// if the local read operation returned non empty value then log server success otherwise log failure.
if (!read_value.empty())
log->logReadSuccess(&getMemberNode()->addr, false, _trans_id, incoming_msg.key, read_value);
else
log->logReadFail(&getMemberNode()->addr, false, _trans_id, incoming_msg.key);
// free the message variable
free(msg);
}
// Handle the update message coming at its correct destinations
void MP2Node::processUpdate(Message incoming_msg) {
// Call the server local function to update value corresponding to a key in its local hash table.
bool success_status = updateKeyValue(incoming_msg.key, incoming_msg.value, incoming_msg.replica);
int _trans_id = incoming_msg.transID; // get trans_id from the incoming message
Address to_addr(incoming_msg.fromAddr); // get the coordinator address from where this message came
if (_trans_id < 0)//if stablization came with trans_id = -1. This is special type of message that comes when ring repair work is going on. So, don't send its reply
return;
Message *msg = new Message(_trans_id, getMemberNode()->addr, REPLY, success_status); // send reply message back to the coordinator
emulNet->ENsend(&getMemberNode()->addr, &to_addr, msg->toString());
// if the local update operation returns success then log server success otherwise log failure.
if (success_status)
log->logUpdateSuccess(&getMemberNode()->addr, false, _trans_id, incoming_msg.key, incoming_msg.value);
else
log->logUpdateFail(&getMemberNode()->addr, false, _trans_id, incoming_msg.key, incoming_msg.value);
// free message variable
free(msg);
}
// Handle the delete message coming at its correct destinations
void MP2Node::processDelete(Message incoming_msg) {
// Calls the server local function to delete key from its local hash table.
bool success_status = deletekey(incoming_msg.key);
int _trans_id = incoming_msg.transID; // get trans_id from the incoming message
Address to_addr(incoming_msg.fromAddr); // get the coordinator address from where this message came
if (_trans_id < 0)//if stablization came with trans_id = -1. This is special type of message that comes when ring repair work is going on. So, don't send its reply
return;
Message *msg = new Message(_trans_id, getMemberNode()->addr, REPLY, success_status); // send reply message back to the coordinator
emulNet->ENsend(&getMemberNode()->addr, &to_addr, msg->toString());
// if the local delete operation returns success then log server success otherwise log failure.
if (success_status)
log->logDeleteSuccess(&getMemberNode()->addr, false, _trans_id, incoming_msg.key);
else
log->logDeleteFail(&getMemberNode()->addr, false, _trans_id, incoming_msg.key);
// free the message variable
free(msg);
}
// Handle the ReadReply message coming at the coordinator
void MP2Node::processReadReply(Message incoming_msg){
int _trans_id = incoming_msg.transID;// get trans_id from the incoming message
string value = incoming_msg.value;// get the value returned by the server
// if value not empty then save it as +ve ack along with value otherwise save it as -ve ack with empty null value for the specific transaction id of the operation.
if (!value.empty()){
Entry entry_value(value);
this->transaction_count[_trans_id].value = entry_value.value;
incTransactionReplyCount(_trans_id, 1, value);
}
else
incTransactionReplyCount(_trans_id, -1, "");
}
// Handle the normal reply messages coming at the coordinator
void MP2Node::processNodesReply(Message incoming_msg) {
Address from_addr(incoming_msg.fromAddr); // address from where the ack or nack came
int _trans_id = incoming_msg.transID;// get trans_id from the incoming message
bool success = incoming_msg.success;// success status returned by the server
cout << "I got a reply from ";
printAddress(&from_addr);
cout << endl;
// if status success save the ack as +ve ack otherwise -ve ack for the specific transaction id of the operation
if (success)
incTransactionReplyCount(_trans_id, 1, "");
else
incTransactionReplyCount(_trans_id, -1, "");
}
/*
*
* Check whether the ring is same as it was before getting the new members list.
*/
bool MP2Node::isRingSame(vector<Node> sortedMemList) {
bool stablization_required = false;
if (!ring.empty()) { // check if ring is not empty. Not make sense to run stablization on new incoming node
if (ring.size() != sortedMemList.size()) //if the size is not same straightaway return true;
stablization_required = true;
else // otherwise check looping through ring to check if each member is same as before (required when there are joins)
for (int i = 0; i < sortedMemList.size(); i++) {
if (!isNodeSame(sortedMemList[i], ring[i])){
stablization_required = true;
break;
}
}
}
return stablization_required;
}
/**
*
* Assign successors and predecessors to this node i.e. change hasMyReplicas and haveReplicasOf
*
*/
void MP2Node::assignReplicationNodes() {
Node this_node = Node(getMemberNode()->addr);
if (hasMyReplicas.empty() || haveReplicasOf.empty()) {
for (int i = 0; i < ring.size(); i++) { // Loop over ring size
if (isNodeSame(ring[i], this_node)){ // When you find the current Node, then assign predecessors and successors.
if (i == 0){ // if node is at 0 location, then this node contains the replicas of last and second last members in the ring
haveReplicasOf.push_back(Node(*ring[ring.size() - 1].getAddress()));
haveReplicasOf.push_back(Node(*ring[ring.size() - 2].getAddress()));
} else if (i == 1){ // if node is at 1 location, then this node contains the replicas of 0th and last member in the ring
haveReplicasOf.push_back(Node(*ring[0].getAddress()));
haveReplicasOf.push_back(Node(*ring[ring.size() - 1].getAddress()));
} else { // If no boundary conditions then, this node contains the replicas of the previous 2 nodes. Modulo just in case :)
haveReplicasOf.push_back(Node(*ring[(i - 1) % ring.size()].getAddress()));
haveReplicasOf.push_back(Node(*ring[(i - 2) % ring.size()].getAddress()));
}
// The replicas of this node will be at the next 2 nodes, hash so as to cover the case when next or next to next node is in the begining of the ring
hasMyReplicas.push_back(Node(*ring[(i + 1) % ring.size()].getAddress()));
hasMyReplicas.push_back(Node(*ring[(i + 2) % ring.size()].getAddress()));
}
}
}
// Just the debugging log to check if new and old rings are what they needs to be.
cout << "Ring is as follows : " << endl;
for (int i = 0; i < ring.size(); i++){
printAddress(ring[i].getAddress());
cout << " ";
}
cout << endl;
cout << "Replicas of ";
printAddress(&getMemberNode()->addr);
cout << " are at " << endl;
for (int i = 0; i < hasMyReplicas.size(); i++){
printAddress(hasMyReplicas[i].getAddress());
cout << endl;
}
cout << " and it has replicas of " << endl;
for (int i = 0; i < haveReplicasOf.size(); i++){
printAddress(haveReplicasOf[i].getAddress());
cout << endl;
}
}
// count the number of acks and nacks for a particular transaction
pair<int, int> MP2Node::countAcks(int _trans_id){
map<int,transaction_details>::iterator it = this->transaction_count.find(_trans_id);
int acks = 0, nacks = 0, reply_val;
if (it != this->transaction_count.end()){
vector<pair<int, string>>::iterator it2 = this->transaction_count[_trans_id].ackStore.begin();
while(it2 != this->transaction_count[_trans_id].ackStore.end()){ // iterator over all the replies that came from the servers.
reply_val = it2->first;
if (reply_val == 1) // check the type of acknowledgement
acks++;
else
nacks++;
it2++;
}
cout << "Acks = "<<acks << " Nacks = " << nacks << endl;
return pair<int, int>(acks, nacks); // return the number of acks and nacks as a pair if found otherwise 0,0.
}
else
return pair<int, int>(0, 0);
}
// initialize the details of a particular transaction using its key, value, msg_type and timestamp
void MP2Node::initTransactionCount(int _trans_id, string key, string value, MessageType msg_type){
map<int,transaction_details>::iterator it = this->transaction_count.find(_trans_id);
if (it == this->transaction_count.end()){
this->transaction_count[_trans_id].reply_count = 0; // set the reply count to 0
this->transaction_count[_trans_id].key = key;
this->transaction_count[_trans_id].value = value;
this->transaction_count[_trans_id].rep_type = msg_type;
this->transaction_count[_trans_id].timestamp = par->getcurrtime(); // set the time as current time
}
else
return;
}
// Update the details of a given transaction according to its transaction id and increase the reply count and set the ack_type of the reply message along with the message.
void MP2Node::incTransactionReplyCount(int _trans_id, int ack_type, string incoming_message){
map<int,transaction_details>::iterator it = this->transaction_count.find(_trans_id);
if (it == this->transaction_count.end())
return;
else{
this->transaction_count[_trans_id].ackStore.push_back(pair<int, string>(ack_type, incoming_message)); // save the message that came from the server.
this->transaction_count[_trans_id].reply_count++; // increment the reply count
}
}
|
#include "Hello.h"
Hello::Hello(const std::string &message)
{
m_message = message;
}
std::shared_ptr<Prototype> Hello::clone() const
{
return std::make_shared<Hello>("");
}
void Hello::setMessage(const std::string &message)
{
m_message = message;
}
std::string Hello::getMessage() const
{
return m_message;
}
|
/*************************************************
* Publicly released by Rhoban System, August 2012
* www.rhoban-system.fr
*
* Freely usable for non-commercial purposes
*
* Licence Creative Commons *CC BY-NC-SA
* http://creativecommons.org/licenses/by-nc-sa/3.0
*************************************************/
#ifndef FILE_MNGT_H
#define FILE_MNGT_H
#include <string>
#include "util.h"
int store_in_file(char * name, ui8 * src, int size);
int read_file(char * name, ui8 * dest, int size);
string file_to_string(string path);
void file_put_contents(string path, string contents);
string file_get_contents(string path);
bool file_exists(string path);
#endif /* FILE_MNGT_H */
|
#pragma once
#include "data/allocator.h"
#include "data/rawrecord.h"
namespace data
{
////////////////////////////////////////////////////////////////////////
struct raw_info
{
raw_info(int id, double time=0.0, raw_type_t type=CR_NONE, std::string string=std::string());
public:
int id_;
double time_;
raw_type_t type_;
bool submessage_;
std::string string_;
};
//////////////////////////////////////////////////////////////////////////
class raw_collection : fastmem::allocator
{
public:
raw_collection();
void clear();
void append_record(const char *begin, const char *end, const raw_info &inf);
const raw_record &get_record(unsigned index) const;
unsigned size() const;
private:
std::vector<raw_record *> data_;
};
}
|
// 338. Counting Bits
// Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
// Example 1:
// Input: 2
// Output: [0,1,1]
// Example 2:
// Input: 5
// Output: [0,1,1,2,1,2]
// Follow up:
// It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
// Space complexity should be O(n).
// Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
#include <vector>
using namespace std;
class Solution {
public:
// Fastest solution O(n)
vector<int> countBits(int num){
vector<int> solution(num+1,0);
for ( int i = 1; i <= num; i++ ){
solution[i] = solution[i>>1] + i%2;
}
return solution;
}
// // O(n) solution.
// // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
// vector<int> countBits(int num){
// static const int S[5] = {1, 2, 4, 8, 16};
// static const int B[5] = {0x55555555,0x33333333,0x0F0F0F0F,0x00FF00FF,0x0000FFFF};
// vector<int> solution;
// int v,c;
// for ( int i = 0; i <= num; i++ ){
// v = i;
// c = v - ((v >> 1) & B[0]);
// c = ((c >> S[1]) & B[1]) + (c & B[1]);
// c = ((c >> S[2]) + c) & B[2];
// c = ((c >> S[3]) + c) & B[3];
// c = ((c >> S[4]) + c) & B[4];
// solution.push_back(c);
// }
// return solution;
// }
// // CHEATING USING POPCOUNT
// vector<int> countBits(int num) {
// vector<int> solution;
// for ( int i = 0; i <= num; i++ ){
// solution.push_back( __builtin_popcount(i) );
// }
// return solution;
// }
// // O(n*sizeof(INT))
// vector<int> countBits(int num) {
// vector<int> solution;
// for (int i = 0; i <= num; i++){
// int n = i;
// int count = 0;
// while ( n ){
// count += n & 1;
// n >>= 1;
// }
// solution.push_back(count);
// }
// return solution;
// }
};
|
#include <iostream>
using namespace std;
int main()
{
double array[] = {1, 3, 6, 89};
cout << array[1] << endl;
}
|
// *****************************************************************
// This file is part of the CYBERMED Libraries
//
// Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve),
// Federal University of Paraiba and University of São Paulo.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.
// *****************************************************************
#include "cybUDPServer.h"
CybUDPServer::CybUDPServer(void) { }
CybUDPServer::CybUDPServer(const short server_port)
{
int i;
this->dataSock = new CybDatagramSock();
this->serverAddr = new CybNodeAddress(server_port, NULL, AF_INET);
for(i=0; i<MAX; i++)
{
this->clientAddr[i] = new CybNodeAddress();
}
this->dataSock->connectToPort(this->dataSock->getSock(), this->serverAddr);
cout << "The server is on." << endl;
}
CybUDPServer::CybUDPServer(const short server_port, const short family)
{
int i;
this->dataSock = new CybDatagramSock();
this->serverAddr = new CybNodeAddress(server_port, NULL, family);
for(i=0; i<MAX; i++)
{
this->clientAddr[i] = new CybNodeAddress();
}
this->dataSock->connectToPort(this->dataSock->getSock(), this->serverAddr);
cout << "The server is on." << endl;
}
CybUDPServer::~CybUDPServer()
{
close(this->dataSock->getSock());
cout << "The server is off." << endl;
}
int CybUDPServer::getSock(void)
{
return this->dataSock->getSock();
}
CybDatagramSock* CybUDPServer::getDatagramSock(void)
{
return this->dataSock;
}
char* CybUDPServer::getIP(void)
{
return this->serverAddr->getIP();
}
short CybUDPServer::getPort(void)
{
return this->serverAddr->getPort();
}
short CybUDPServer::getFamily(void)
{
return this->serverAddr->getFamily();
}
CybNodeAddress* CybUDPServer::getNodeAddr(void)
{
return this->serverAddr;
}
struct sockaddr_in* CybUDPServer::getAddr(void)
{
return this->serverAddr->getAddr();
}
CybNodeAddress* CybUDPServer::getClientAddr(int i)
{
return this->clientAddr[i];
}
void CybUDPServer::sendData(int sock, void* data, int size) throw (CybCommunicationException)
{
sendData(data, size);
}
void CybUDPServer::receiveData(int sock, void* data, int size) throw (CybCommunicationException)
{
receiveData(data, size);
}
void CybUDPServer::sendData(void* data, int size) throw (CybCommunicationException)
{
int result = 0;
result = sendto(this->dataSock->getSock(), data, size, 0, (struct sockaddr *)this->clientAddr[0]->getAddr(), this->serverAddr->getAddrSizeValue());
if(result < 0) throw CybCommunicationException(2);
}
int CybUDPServer::receiveData(void* data, int size) throw (CybCommunicationException)
{
struct sockaddr_in auxAddr;
int result = 0;
result = recvfrom(this->dataSock->getSock(), data, size, 0, (struct sockaddr *)this->clientAddr[0]->getAddr(), this->serverAddr->getAddrSize());
if(result < 0) throw CybCommunicationException(1);
return result;
}
void CybUDPServer::sendData(void* data, int size, CybNodeAddress* address) throw (CybCommunicationException)
{
int result = 0;
result = sendto(this->dataSock->getSock(), data, size, 0, (struct sockaddr *)address->getAddr(), address->getAddrSizeValue());
if(result < 0) {
throw CybCommunicationException(2);
cout << "erro ao enviar...\n" << endl;
}
//else cout << result << " bytes enviados: " << data << "para o host: "<< inet_ntoa(address->getAddr()->sin_addr) << endl;
}
int CybUDPServer::receiveDataFrom(void* data, int size, CybNodeAddress* address) throw (CybCommunicationException)
{
struct sockaddr_in auxAddr;
int result = 0;
result = recvfrom(this->dataSock->getSock(), data, size, 0, (struct sockaddr *)&auxAddr, this->serverAddr->getAddrSize());
//cout << "Data: " << (char*) data << " received from host --> " << inet_ntoa(auxAddr.sin_addr) << ":" << htons(auxAddr.sin_port) << endl;
address->setAddr(&auxAddr);
if(result < 0) throw CybCommunicationException(1);
return result;
}
|
// This file is subject to the terms and conditions defined in 'LICENSE' included in the source code package
#include <gtest/gtest.h>
#include "proto/assembly_machine.h"
namespace jactorio::data
{
TEST(UniqueDataManager, AssignId) {
UniqueDataManager unique;
proto::AssemblyMachineData data_1;
proto::AssemblyMachineData data_2;
unique.AssignId(data_1);
unique.AssignId(data_2);
EXPECT_EQ(data_1.internalId, 1);
EXPECT_EQ(data_2.internalId, 2);
}
TEST(UniqueDataManager, ClearResetId) {
UniqueDataManager unique;
proto::AssemblyMachineData data_1;
unique.AssignId(data_1);
unique.Clear();
proto::AssemblyMachineData data_2;
unique.AssignId(data_2);
EXPECT_EQ(data_1.internalId, 1);
EXPECT_EQ(data_2.internalId, 1);
}
TEST(UniqueDataManager, StoreGetRelocationEntry) {
UniqueDataManager unique;
proto::AssemblyMachineData data_1;
data_1.internalId = 1;
unique.StoreRelocationEntry(data_1);
proto::AssemblyMachineData data_2;
data_2.internalId = 10;
unique.StoreRelocationEntry(data_2);
EXPECT_EQ(&unique.RelocationTableGet(1), &data_1);
EXPECT_EQ(&unique.RelocationTableGet(10), &data_2);
}
TEST(UniqueDataManager, StoreRelocationEntryOverwrite) {
UniqueDataManager unique;
proto::AssemblyMachineData data_1;
data_1.internalId = 1;
unique.StoreRelocationEntry(data_1);
proto::AssemblyMachineData data_2;
data_2.internalId = 1;
unique.StoreRelocationEntry(data_2);
EXPECT_EQ(&unique.RelocationTableGet(1), &data_2);
}
TEST(UniqueDataManager, ClearRelocationTable) {
UniqueDataManager unique;
proto::AssemblyMachineData data_1;
data_1.internalId = 1;
unique.StoreRelocationEntry(data_1);
unique.Clear();
EXPECT_TRUE(unique.GetDebugInfo().dataEntries.empty());
}
} // namespace jactorio::data
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.