text
stringlengths
54
60.6k
<commit_before>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "OSPCommon.h" #if defined(OSPRAY_TASKING_TBB) # include <tbb/task_scheduler_init.h> #elif defined(OSPRAY_TASKING_CILK) # include <cilk/cilk_api.h> #elif defined(OSPRAY_TASKING_OMP) # include <omp.h> #elif defined(OSPRAY_TASKING_INTERNAL) # include "common/tasking/TaskSys.h" #endif // embree #include "embree2/rtcore.h" #include "ospcommon/sysinfo.h" namespace ospray { RTCDevice g_embreeDevice = nullptr; /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void *malloc64(size_t size) { return ospcommon::alignedMalloc(size); } /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void free64(void *ptr) { return ospcommon::alignedFree(ptr); } /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32_t logLevel = 0; bool debugMode = false; int numThreads = -1; WarnOnce::WarnOnce(const std::string &s) : s(s) { std::cout << "Warning: " << s << " (only reporting first occurrence)" << std::endl; } /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr); abort(); } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } void init(int *_ac, const char ***_av) { #ifndef OSPRAY_TARGET_MIC // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will // be increased to SSE4.2 in future. int cpuFeatures = ospcommon::getCPUFeatures(); if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0) throw std::runtime_error("Error. OSPRay only runs on CPUs that support" " at least SSE4.1."); #endif if (_ac && _av) { int &ac = *_ac; char ** &av = *(char ***)_av; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; numThreads = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") { numThreads = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } #if defined(OSPRAY_TASKING_TBB) static tbb::task_scheduler_init tbb_init(numThreads); UNUSED(tbb_init); #elif defined(OSPRAY_TASKING_CILK) __cilkrts_set_param("nworkers", std::to_string(numThreads).c_str()); #elif defined(OSPRAY_TASKING_OMP) if (numThreads > 0) { omp_set_num_threads(numThreads); } #elif defined(OSPRAY_TASKING_INTERNAL) try { ospray::Task::initTaskSystem(debugMode ? 0 : numThreads); } catch (const std::runtime_error &e) { std::cerr << "WARNING: " << e.what() << std::endl; } #endif } void error_handler(const RTCError code, const char *str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } abort(); } size_t sizeOf(const OSPDataType type) { switch (type) { case OSP_VOID_PTR: return sizeof(void *); case OSP_OBJECT: return sizeof(void *); case OSP_DATA: return sizeof(void *); case OSP_CHAR: return sizeof(int8); case OSP_UCHAR: return sizeof(uint8); case OSP_UCHAR2: return sizeof(vec2uc); case OSP_UCHAR3: return sizeof(vec3uc); case OSP_UCHAR4: return sizeof(vec4uc); case OSP_USHORT: return sizeof(uint16); case OSP_INT: return sizeof(int32); case OSP_INT2: return sizeof(vec2i); case OSP_INT3: return sizeof(vec3i); case OSP_INT4: return sizeof(vec4i); case OSP_UINT: return sizeof(uint32); case OSP_UINT2: return sizeof(vec2ui); case OSP_UINT3: return sizeof(vec3ui); case OSP_UINT4: return sizeof(vec4ui); case OSP_LONG: return sizeof(int64); case OSP_LONG2: return sizeof(vec2l); case OSP_LONG3: return sizeof(vec3l); case OSP_LONG4: return sizeof(vec4l); case OSP_ULONG: return sizeof(uint64); case OSP_ULONG2: return sizeof(vec2ul); case OSP_ULONG3: return sizeof(vec3ul); case OSP_ULONG4: return sizeof(vec4ul); case OSP_FLOAT: return sizeof(float); case OSP_FLOAT2: return sizeof(vec2f); case OSP_FLOAT3: return sizeof(vec3f); case OSP_FLOAT4: return sizeof(vec4f); case OSP_FLOAT3A: return sizeof(vec3fa); case OSP_DOUBLE: return sizeof(double); default: break; }; std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType " << (int)type; throw std::runtime_error(error.str()); } OSPDataType typeForString(const char *string) { if (string == NULL) return(OSP_UNKNOWN); if (strcmp(string, "char" ) == 0) return(OSP_CHAR); if (strcmp(string, "double") == 0) return(OSP_DOUBLE); if (strcmp(string, "float" ) == 0) return(OSP_FLOAT); if (strcmp(string, "float2") == 0) return(OSP_FLOAT2); if (strcmp(string, "float3") == 0) return(OSP_FLOAT2); if (strcmp(string, "float4") == 0) return(OSP_FLOAT2); if (strcmp(string, "int" ) == 0) return(OSP_INT); if (strcmp(string, "int2" ) == 0) return(OSP_INT2); if (strcmp(string, "int3" ) == 0) return(OSP_INT3); if (strcmp(string, "int4" ) == 0) return(OSP_INT4); if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR); if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2); if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3); if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4); if (strcmp(string, "ushort") == 0) return(OSP_USHORT); if (strcmp(string, "uint" ) == 0) return(OSP_UINT); if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2); if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3); if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4); return(OSP_UNKNOWN); } size_t sizeOf(const OSPTextureFormat type) { switch (type) { case OSP_TEXTURE_RGBA8: case OSP_TEXTURE_SRGBA: return sizeof(uint32); case OSP_TEXTURE_RGBA32F: return sizeof(vec4f); case OSP_TEXTURE_RGB8: case OSP_TEXTURE_SRGB: return sizeof(vec3uc); case OSP_TEXTURE_RGB32F: return sizeof(vec3f); case OSP_TEXTURE_R8: return sizeof(uint8); case OSP_TEXTURE_R32F: return sizeof(float); } std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat " << (int)type; throw std::runtime_error(error.str()); } } // ::ospray <commit_msg>Fix and complete OSPDataType functions<commit_after>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "OSPCommon.h" #if defined(OSPRAY_TASKING_TBB) # include <tbb/task_scheduler_init.h> #elif defined(OSPRAY_TASKING_CILK) # include <cilk/cilk_api.h> #elif defined(OSPRAY_TASKING_OMP) # include <omp.h> #elif defined(OSPRAY_TASKING_INTERNAL) # include "common/tasking/TaskSys.h" #endif // embree #include "embree2/rtcore.h" #include "ospcommon/sysinfo.h" namespace ospray { RTCDevice g_embreeDevice = nullptr; /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void *malloc64(size_t size) { return ospcommon::alignedMalloc(size); } /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void free64(void *ptr) { return ospcommon::alignedFree(ptr); } /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32_t logLevel = 0; bool debugMode = false; int numThreads = -1; WarnOnce::WarnOnce(const std::string &s) : s(s) { std::cout << "Warning: " << s << " (only reporting first occurrence)" << std::endl; } /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr); abort(); } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } void init(int *_ac, const char ***_av) { #ifndef OSPRAY_TARGET_MIC // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will // be increased to SSE4.2 in future. int cpuFeatures = ospcommon::getCPUFeatures(); if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0) throw std::runtime_error("Error. OSPRay only runs on CPUs that support" " at least SSE4.1."); #endif if (_ac && _av) { int &ac = *_ac; char ** &av = *(char ***)_av; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; numThreads = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") { numThreads = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } #if defined(OSPRAY_TASKING_TBB) static tbb::task_scheduler_init tbb_init(numThreads); UNUSED(tbb_init); #elif defined(OSPRAY_TASKING_CILK) __cilkrts_set_param("nworkers", std::to_string(numThreads).c_str()); #elif defined(OSPRAY_TASKING_OMP) if (numThreads > 0) { omp_set_num_threads(numThreads); } #elif defined(OSPRAY_TASKING_INTERNAL) try { ospray::Task::initTaskSystem(debugMode ? 0 : numThreads); } catch (const std::runtime_error &e) { std::cerr << "WARNING: " << e.what() << std::endl; } #endif } void error_handler(const RTCError code, const char *str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } abort(); } size_t sizeOf(const OSPDataType type) { switch (type) { case OSP_VOID_PTR: case OSP_OBJECT: case OSP_CAMERA: case OSP_DATA: case OSP_FRAMEBUFFER: case OSP_GEOMETRY: case OSP_LIGHT: case OSP_MATERIAL: case OSP_MODEL: case OSP_RENDERER: case OSP_TEXTURE: case OSP_TRANSFER_FUNCTION: case OSP_VOLUME: case OSP_PIXEL_OP: case OSP_STRING: return sizeof(void *); case OSP_CHAR: return sizeof(int8); case OSP_UCHAR: return sizeof(uint8); case OSP_UCHAR2: return sizeof(vec2uc); case OSP_UCHAR3: return sizeof(vec3uc); case OSP_UCHAR4: return sizeof(vec4uc); case OSP_USHORT: return sizeof(uint16); case OSP_INT: return sizeof(int32); case OSP_INT2: return sizeof(vec2i); case OSP_INT3: return sizeof(vec3i); case OSP_INT4: return sizeof(vec4i); case OSP_UINT: return sizeof(uint32); case OSP_UINT2: return sizeof(vec2ui); case OSP_UINT3: return sizeof(vec3ui); case OSP_UINT4: return sizeof(vec4ui); case OSP_LONG: return sizeof(int64); case OSP_LONG2: return sizeof(vec2l); case OSP_LONG3: return sizeof(vec3l); case OSP_LONG4: return sizeof(vec4l); case OSP_ULONG: return sizeof(uint64); case OSP_ULONG2: return sizeof(vec2ul); case OSP_ULONG3: return sizeof(vec3ul); case OSP_ULONG4: return sizeof(vec4ul); case OSP_FLOAT: return sizeof(float); case OSP_FLOAT2: return sizeof(vec2f); case OSP_FLOAT3: return sizeof(vec3f); case OSP_FLOAT4: return sizeof(vec4f); case OSP_FLOAT3A: return sizeof(vec3fa); case OSP_DOUBLE: return sizeof(double); }; std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType " << (int)type; throw std::runtime_error(error.str()); } OSPDataType typeForString(const char *string) { if (string == NULL) return(OSP_UNKNOWN); if (strcmp(string, "char" ) == 0) return(OSP_CHAR); if (strcmp(string, "double") == 0) return(OSP_DOUBLE); if (strcmp(string, "float" ) == 0) return(OSP_FLOAT); if (strcmp(string, "float2") == 0) return(OSP_FLOAT2); if (strcmp(string, "float3") == 0) return(OSP_FLOAT3); if (strcmp(string, "float4") == 0) return(OSP_FLOAT4); if (strcmp(string, "int" ) == 0) return(OSP_INT); if (strcmp(string, "int2" ) == 0) return(OSP_INT2); if (strcmp(string, "int3" ) == 0) return(OSP_INT3); if (strcmp(string, "int4" ) == 0) return(OSP_INT4); if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR); if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2); if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3); if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4); if (strcmp(string, "ushort") == 0) return(OSP_USHORT); if (strcmp(string, "uint" ) == 0) return(OSP_UINT); if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2); if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3); if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4); return(OSP_UNKNOWN); } size_t sizeOf(const OSPTextureFormat type) { switch (type) { case OSP_TEXTURE_RGBA8: case OSP_TEXTURE_SRGBA: return sizeof(uint32); case OSP_TEXTURE_RGBA32F: return sizeof(vec4f); case OSP_TEXTURE_RGB8: case OSP_TEXTURE_SRGB: return sizeof(vec3uc); case OSP_TEXTURE_RGB32F: return sizeof(vec3f); case OSP_TEXTURE_R8: return sizeof(uint8); case OSP_TEXTURE_R32F: return sizeof(float); } std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat " << (int)type; throw std::runtime_error(error.str()); } } // ::ospray <|endoftext|>
<commit_before>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include <memory> #include <jni.h> #include "core/android/EngineAndroid.hpp" #include "core/android/WindowResourceAndroid.hpp" #include "core/Engine.hpp" #include "events/EventDispatcher.hpp" #include "input/android/InputManagerAndroid.hpp" #include "utils/Log.hpp" static std::unique_ptr<ouzel::EngineAndroid> engine; extern "C" JNIEXPORT jint JNIEXPORT JNI_OnLoad(JavaVM* javaVM, void*) { engine.reset(new ouzel::EngineAndroid(javaVM)); return JNI_VERSION_1_6; } extern "C" JNIEXPORT void JNIEXPORT JNI_OnUnload(JavaVM*, void*) { engine->exit(); engine.reset(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onCreate(JNIEnv*, jclass, jobject mainActivity) { engine->onCreate(mainActivity); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceCreated(JNIEnv*, jclass, jobject surface) { try { engine->onSurfaceCreated(surface); if (!engine->isActive()) engine->run(); } catch (const std::exception& e) { ouzel::Log(ouzel::Log::Level::ERR) << e.what(); return EXIT_FAILURE; } catch (...) { return EXIT_FAILURE; } } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceDestroyed(JNIEnv*, jclass) { engine->onSurfaceDestroyed(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceChanged(JNIEnv*, jclass, jobject, jint width, jint height) { ouzel::WindowResourceAndroid* windowAndroid = static_cast<ouzel::WindowResourceAndroid*>(engine->getWindow()->getResource()); windowAndroid->handleResize(ouzel::Size2(static_cast<float>(width), static_cast<float>(height))); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onStart(JNIEnv*, jclass) { // Do nothing } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onPause(JNIEnv*, jclass) { engine->pause(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onResume(JNIEnv*, jclass) { engine->resume(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onConfigurationChanged(JNIEnv*, jclass, jobject newConfig) { engine->onConfigurationChanged(newConfig); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onLowMemory(JNIEnv*, jclass) { ouzel::Event event; event.type = ouzel::Event::Type::LOW_MEMORY; engine->getEventDispatcher()->postEvent(event); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onBackPressed(JNIEnv*, jclass) { engine->getInputManager()->keyPress(ouzel::input::KeyboardKey::MENU, 0); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onKeyDown(JNIEnv*, jclass, jint keyCode) { engine->getInputManager()->keyPress(ouzel::input::InputManagerAndroid::convertKeyCode(keyCode), 0); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onKeyUp(JNIEnv*, jclass, jint keyCode) { engine->getInputManager()->keyRelease(ouzel::input::InputManagerAndroid::convertKeyCode(keyCode), 0); } extern "C" JNIEXPORT jboolean JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onTouchEvent(JNIEnv*, jclass, jobject event) { ouzel::input::InputManagerAndroid* inputAndroid = static_cast<ouzel::input::InputManagerAndroid*>(engine->getInputManager()); return inputAndroid->handleTouchEvent(event); } <commit_msg>Don't return values from Android surface created method<commit_after>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include <memory> #include <jni.h> #include "core/android/EngineAndroid.hpp" #include "core/android/WindowResourceAndroid.hpp" #include "core/Engine.hpp" #include "events/EventDispatcher.hpp" #include "input/android/InputManagerAndroid.hpp" #include "utils/Log.hpp" static std::unique_ptr<ouzel::EngineAndroid> engine; extern "C" JNIEXPORT jint JNIEXPORT JNI_OnLoad(JavaVM* javaVM, void*) { engine.reset(new ouzel::EngineAndroid(javaVM)); return JNI_VERSION_1_6; } extern "C" JNIEXPORT void JNIEXPORT JNI_OnUnload(JavaVM*, void*) { engine->exit(); engine.reset(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onCreate(JNIEnv*, jclass, jobject mainActivity) { engine->onCreate(mainActivity); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceCreated(JNIEnv*, jclass, jobject surface) { try { engine->onSurfaceCreated(surface); if (!engine->isActive()) engine->run(); } catch (const std::exception& e) { ouzel::Log(ouzel::Log::Level::ERR) << e.what(); } } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceDestroyed(JNIEnv*, jclass) { engine->onSurfaceDestroyed(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onSurfaceChanged(JNIEnv*, jclass, jobject, jint width, jint height) { ouzel::WindowResourceAndroid* windowAndroid = static_cast<ouzel::WindowResourceAndroid*>(engine->getWindow()->getResource()); windowAndroid->handleResize(ouzel::Size2(static_cast<float>(width), static_cast<float>(height))); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onStart(JNIEnv*, jclass) { // Do nothing } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onPause(JNIEnv*, jclass) { engine->pause(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onResume(JNIEnv*, jclass) { engine->resume(); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onConfigurationChanged(JNIEnv*, jclass, jobject newConfig) { engine->onConfigurationChanged(newConfig); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onLowMemory(JNIEnv*, jclass) { ouzel::Event event; event.type = ouzel::Event::Type::LOW_MEMORY; engine->getEventDispatcher()->postEvent(event); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onBackPressed(JNIEnv*, jclass) { engine->getInputManager()->keyPress(ouzel::input::KeyboardKey::MENU, 0); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onKeyDown(JNIEnv*, jclass, jint keyCode) { engine->getInputManager()->keyPress(ouzel::input::InputManagerAndroid::convertKeyCode(keyCode), 0); } extern "C" JNIEXPORT void JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onKeyUp(JNIEnv*, jclass, jint keyCode) { engine->getInputManager()->keyRelease(ouzel::input::InputManagerAndroid::convertKeyCode(keyCode), 0); } extern "C" JNIEXPORT jboolean JNICALL Java_org_ouzelengine_OuzelLibJNIWrapper_onTouchEvent(JNIEnv*, jclass, jobject event) { ouzel::input::InputManagerAndroid* inputAndroid = static_cast<ouzel::input::InputManagerAndroid*>(engine->getInputManager()); return inputAndroid->handleTouchEvent(event); } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "Renderer.h" #include "core/Engine.h" #include "Texture.h" #include "Shader.h" #include "RenderTarget.h" #include "BlendState.h" #include "MeshBuffer.h" #include "IndexBuffer.h" #include "VertexBuffer.h" #include "events/EventHandler.h" #include "events/EventDispatcher.h" #include "core/Window.h" #include "utils/Log.h" namespace ouzel { namespace graphics { Renderer::Renderer(Driver aDriver): driver(aDriver), activeDrawQueueFinished(false), refillDrawQueue(true), projectionTransform(Matrix4::IDENTITY), renderTargetProjectionTransform(Matrix4::IDENTITY), clearColor(Color::BLACK), dirty(false) { } Renderer::~Renderer() { } void Renderer::free() { activeDrawQueue.clear(); } bool Renderer::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, TextureFilter newTextureFilter, PixelFormat newBackBufferFormat, bool newVerticalSync, uint32_t newDepthBits) { window = newWindow; size = newSize; sampleCount = newSampleCount; textureFilter = newTextureFilter; backBufferFormat = newBackBufferFormat; verticalSync = newVerticalSync; depthBits = newDepthBits; return true; } bool Renderer::update() { return true; } bool Renderer::present() { if (dirty) { uploadData.size = size; uploadData.clearColor = clearColor; uploadData.clearColorBuffer = clearColorBuffer; uploadData.clearDepthBuffer = clearDepthBuffer; if (!update()) { return false; } } ++currentFrame; if (activeDrawQueueFinished) { drawQueue = std::move(activeDrawQueue); activeDrawQueue.reserve(drawQueue.size()); drawCallCount = static_cast<uint32_t>(drawQueue.size()); std::set<ResourcePtr> resources; { std::lock_guard<std::mutex> lock(updateMutex); resources = std::move(updateSet); updateSet.clear(); for (const ResourcePtr& resource : resources) { // prepare data for upload resource->update(); } } for (const ResourcePtr& resource : resources) { // upload data to GPU if (!resource->upload()) { return false; } } activeDrawQueueFinished = false; refillDrawQueue = true; } if (!generateScreenshots()) { return false; } return true; } void Renderer::setClearColorBuffer(bool clear) { clearColorBuffer = clear; dirty = true; } void Renderer::setClearDepthBuffer(bool clear) { clearDepthBuffer = clear; dirty = true; } void Renderer::setClearColor(Color color) { clearColor = color; dirty = true; } void Renderer::setSize(const Size2& newSize) { if (size != newSize) { size = newSize; Event event; event.type = Event::Type::WINDOW_RESOLUTION_CHANGE; event.windowEvent.window = window; event.windowEvent.size = size; sharedEngine->getEventDispatcher()->postEvent(event); dirty = true; } } std::vector<Size2> Renderer::getSupportedResolutions() const { return std::vector<Size2>(); } bool Renderer::addDrawCommand(const std::vector<TexturePtr>& textures, const ShaderPtr& shader, const std::vector<std::vector<float>>& pixelShaderConstants, const std::vector<std::vector<float>>& vertexShaderConstants, const BlendStatePtr& blendState, const MeshBufferPtr& meshBuffer, uint32_t indexCount, DrawMode drawMode, uint32_t startIndex, const RenderTargetPtr& renderTarget, const Rectangle& viewport, bool depthWrite, bool depthTest, bool wireframe, bool scissorTestEnabled, const Rectangle& scissorTest) { if (!shader) { Log(Log::Level::ERR) << "No shader passed to render queue"; return false; } if (!meshBuffer || !meshBuffer->getIndexBuffer() || !meshBuffer->getVertexBuffer() || shader->getVertexAttributes() != meshBuffer->getVertexBuffer()->getVertexAttributes()) { Log(Log::Level::ERR) << "Invalid mesh buffer passed to render queue"; return false; } activeDrawQueue.push_back({ textures, shader, pixelShaderConstants, vertexShaderConstants, blendState, meshBuffer, (indexCount > 0) ? indexCount : meshBuffer->getIndexBuffer()->getIndexCount() - startIndex, drawMode, startIndex, renderTarget, viewport, depthWrite, depthTest, wireframe, scissorTestEnabled, scissorTest }); return true; } void Renderer::flushDrawCommands() { refillDrawQueue = false; activeDrawQueueFinished = true; } bool Renderer::saveScreenshot(const std::string& filename) { std::lock_guard<std::mutex> lock(screenshotMutex); screenshotQueue.push(filename); return true; } void Renderer::scheduleUpdate(const ResourcePtr& resource) { std::lock_guard<std::mutex> lock(updateMutex); updateSet.insert(resource); } bool Renderer::generateScreenshots() { for (;;) { std::string filename; { std::lock_guard<std::mutex> lock(screenshotMutex); if (screenshotQueue.empty()) break; filename = screenshotQueue.front(); screenshotQueue.pop(); } if (!generateScreenshot(filename)) { return false; } } return true; } bool Renderer::generateScreenshot(const std::string&) { return true; } } // namespace graphics } // namespace ouzel <commit_msg>Set dirty to false<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "Renderer.h" #include "core/Engine.h" #include "Texture.h" #include "Shader.h" #include "RenderTarget.h" #include "BlendState.h" #include "MeshBuffer.h" #include "IndexBuffer.h" #include "VertexBuffer.h" #include "events/EventHandler.h" #include "events/EventDispatcher.h" #include "core/Window.h" #include "utils/Log.h" namespace ouzel { namespace graphics { Renderer::Renderer(Driver aDriver): driver(aDriver), activeDrawQueueFinished(false), refillDrawQueue(true), projectionTransform(Matrix4::IDENTITY), renderTargetProjectionTransform(Matrix4::IDENTITY), clearColor(Color::BLACK), dirty(false) { } Renderer::~Renderer() { } void Renderer::free() { activeDrawQueue.clear(); } bool Renderer::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, TextureFilter newTextureFilter, PixelFormat newBackBufferFormat, bool newVerticalSync, uint32_t newDepthBits) { window = newWindow; size = newSize; sampleCount = newSampleCount; textureFilter = newTextureFilter; backBufferFormat = newBackBufferFormat; verticalSync = newVerticalSync; depthBits = newDepthBits; return true; } bool Renderer::update() { return true; } bool Renderer::present() { if (dirty) { uploadData.size = size; uploadData.clearColor = clearColor; uploadData.clearColorBuffer = clearColorBuffer; uploadData.clearDepthBuffer = clearDepthBuffer; if (!update()) { return false; } dirty = false; } ++currentFrame; if (activeDrawQueueFinished) { drawQueue = std::move(activeDrawQueue); activeDrawQueue.reserve(drawQueue.size()); drawCallCount = static_cast<uint32_t>(drawQueue.size()); std::set<ResourcePtr> resources; { std::lock_guard<std::mutex> lock(updateMutex); resources = std::move(updateSet); updateSet.clear(); for (const ResourcePtr& resource : resources) { // prepare data for upload resource->update(); } } for (const ResourcePtr& resource : resources) { // upload data to GPU if (!resource->upload()) { return false; } } activeDrawQueueFinished = false; refillDrawQueue = true; } if (!generateScreenshots()) { return false; } return true; } void Renderer::setClearColorBuffer(bool clear) { clearColorBuffer = clear; dirty = true; } void Renderer::setClearDepthBuffer(bool clear) { clearDepthBuffer = clear; dirty = true; } void Renderer::setClearColor(Color color) { clearColor = color; dirty = true; } void Renderer::setSize(const Size2& newSize) { if (size != newSize) { size = newSize; Event event; event.type = Event::Type::WINDOW_RESOLUTION_CHANGE; event.windowEvent.window = window; event.windowEvent.size = size; sharedEngine->getEventDispatcher()->postEvent(event); dirty = true; } } std::vector<Size2> Renderer::getSupportedResolutions() const { return std::vector<Size2>(); } bool Renderer::addDrawCommand(const std::vector<TexturePtr>& textures, const ShaderPtr& shader, const std::vector<std::vector<float>>& pixelShaderConstants, const std::vector<std::vector<float>>& vertexShaderConstants, const BlendStatePtr& blendState, const MeshBufferPtr& meshBuffer, uint32_t indexCount, DrawMode drawMode, uint32_t startIndex, const RenderTargetPtr& renderTarget, const Rectangle& viewport, bool depthWrite, bool depthTest, bool wireframe, bool scissorTestEnabled, const Rectangle& scissorTest) { if (!shader) { Log(Log::Level::ERR) << "No shader passed to render queue"; return false; } if (!meshBuffer || !meshBuffer->getIndexBuffer() || !meshBuffer->getVertexBuffer() || shader->getVertexAttributes() != meshBuffer->getVertexBuffer()->getVertexAttributes()) { Log(Log::Level::ERR) << "Invalid mesh buffer passed to render queue"; return false; } activeDrawQueue.push_back({ textures, shader, pixelShaderConstants, vertexShaderConstants, blendState, meshBuffer, (indexCount > 0) ? indexCount : meshBuffer->getIndexBuffer()->getIndexCount() - startIndex, drawMode, startIndex, renderTarget, viewport, depthWrite, depthTest, wireframe, scissorTestEnabled, scissorTest }); return true; } void Renderer::flushDrawCommands() { refillDrawQueue = false; activeDrawQueueFinished = true; } bool Renderer::saveScreenshot(const std::string& filename) { std::lock_guard<std::mutex> lock(screenshotMutex); screenshotQueue.push(filename); return true; } void Renderer::scheduleUpdate(const ResourcePtr& resource) { std::lock_guard<std::mutex> lock(updateMutex); updateSet.insert(resource); } bool Renderer::generateScreenshots() { for (;;) { std::string filename; { std::lock_guard<std::mutex> lock(screenshotMutex); if (screenshotQueue.empty()) break; filename = screenshotQueue.front(); screenshotQueue.pop(); } if (!generateScreenshot(filename)) { return false; } } return true; } bool Renderer::generateScreenshot(const std::string&) { return true; } } // namespace graphics } // namespace ouzel <|endoftext|>
<commit_before>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " with index " << childSegment->getArrayIndex() << " and start position " << childSegment->getStartPosition() << " and sequence " << childSegment->getSequence()->getName() << " has length " << childSegment->getLength() << " but parent with index " << bottomSegment->getArrayIndex() << " and start position " << bottomSegment->getStartPosition() << " in sequence " << bottomSegment->getSequence()->getName() << " has length " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { stringstream ss; ss << "Parent / child index mismatch:\n" << genome->getName() << "[" << bottomSegment->getArrayIndex() << "]" << " links to " << childGenome->getName() << "[" << childIndex << "] but \n" << childGenome->getName() << "[" << childSegment->getArrayIndex() << "] links to " << genome->getName() << "[" << childSegment->getParentIndex() << "]"; throw hal_exception(ss.str()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " which is out of range since genome has " << genome->getNumBottomSegments() << " bottom segments"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } if (paralogyIndex == topSegment->getArrayIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has paralogy index " << topSegment->getNextParalogyIndex() << " which isn't allowed"; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } } <commit_msg>add test for DNA array presence to validate instead of crashing on LOD hals that have no DNA sequence info<commit_after>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " with index " << childSegment->getArrayIndex() << " and start position " << childSegment->getStartPosition() << " and sequence " << childSegment->getSequence()->getName() << " has length " << childSegment->getLength() << " but parent with index " << bottomSegment->getArrayIndex() << " and start position " << bottomSegment->getStartPosition() << " in sequence " << bottomSegment->getSequence()->getName() << " has length " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { stringstream ss; ss << "Parent / child index mismatch:\n" << genome->getName() << "[" << bottomSegment->getArrayIndex() << "]" << " links to " << childGenome->getName() << "[" << childIndex << "] but \n" << childGenome->getName() << "[" << childSegment->getArrayIndex() << "] links to " << genome->getName() << "[" << childSegment->getParentIndex() << "]"; throw hal_exception(ss.str()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " which is out of range since genome has " << genome->getNumBottomSegments() << " bottom segments"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } if (paralogyIndex == topSegment->getArrayIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has paralogy index " << topSegment->getNextParalogyIndex() << " which isn't allowed"; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); if (sequence->getGenome()->containsDNAArray() == true) { for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } } <|endoftext|>
<commit_before>#include <QtPlugin> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include "kernel.h" #include "geos/geom/Coordinate.h" #include "coordinate.h" #include "location.h" #include "internalmodule.h" #include "ilwisdata.h" #include "range.h" #include "connectorinterface.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwisobjectfactory.h" #include "internalilwisobjectfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogexplorer.h" #include "catalogconnector.h" #include "internalrastercoverageconnector.h" #include "internalfeaturecoverageconnector.h" #include "internaltableconnector.h" #include "projection.h" #include "projectionimplementation.h" #include "projectionfactory.h" #include "internalprjmplfactory.h" #include "internalgeoreferenceconnector.h" #include "internaldomain.h" #include "internalcoordinatesystemconnector.h" using namespace Ilwis; using namespace Internal; InternalModule::InternalModule(QObject *parent) : Module(parent, "InternalModule", "iv40","1.0") { } QString InternalModule::getInterfaceVersion() const { return "iv40"; } void InternalModule::prepare() { InternalIlwisObjectFactory *ifactory = new InternalIlwisObjectFactory(); kernel()->addFactory(ifactory); ConnectorFactory *factory = kernel()->factory<ConnectorFactory>("ilwis::ConnectorFactory"); if (!factory) return ; factory->addCreator(itCATALOG,"internal",CatalogConnector::create); factory->addCreator(itRASTER,"internal", InternalRasterCoverageConnector::create); factory->addCreator(itTABLE,"internal", InternalTableConnector::create); factory->addCreator(itFEATURE,"internal", InternalFeatureCoverageConnector::create); factory->addCreator(itGEOREF,"internal", InternalGeoReferenceConnector::create); factory->addCreator(itDOMAIN,"internal", InternalDomainConnector::create); factory->addCreator(itCOORDSYSTEM,"internal", InternalCoordinatesystemConnector::create); FactoryInterface *projfactory = new ProjectionImplFactory(); projfactory->prepare(); kernel()->addFactory(projfactory ); QSqlQuery db(kernel()->database()); bool ok = createItems(db,"projection", itPROJECTION); ok &= createItems(db,"ellipsoid", itELLIPSOID); ok &= createItems(db,"datum", itGEODETICDATUM); ok &= createItems(db,"numericdomain", itNUMERICDOMAIN); ok &= createPcs(db); ok &= createSpecialDomains(); QString url = QString("ilwis://internalcatalog/unknown"); Resource resource(url, itBOUNDSONLYCSY); resource.code("unknown"); resource.name("unknown", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); mastercatalog()->addItems({resource}); url = QString("ilwis://internalcatalog/undetermined"); resource = Resource(url, itGEOREF); resource.code("undetermined"); resource.name("undetermined", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); mastercatalog()->addItems({resource}); IlwisObject::addTypeFunction(InternalModule::ilwisType); } QString InternalModule::name() const { return "Internal Connector connector plugin"; } QString InternalModule::version() const { return "1.0"; } bool InternalModule::createSpecialDomains() { std::vector<Resource> resources; QString url = QString("ilwis://internalcatalog/code=domain:text"); Resource resource(url, itTEXTDOMAIN); resource.code("text"); resource.name("Text domain", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); resources.push_back(resource); url = QString("ilwis://internalcatalog/code=domain:color"); Resource colorResource(url, itCOLORDOMAIN); colorResource.code("color"); colorResource.name("Color domain", false); colorResource.addContainer(QUrl("ilwis://internalcatalog")); colorResource.prepare(); resources.push_back(colorResource); return mastercatalog()->addItems(resources); } bool InternalModule::createPcs(QSqlQuery& db) { QString query = QString("Select * from projectedcsy"); if ( db.exec(query)) { std::vector<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); QString name = rec.value("name").toString(); QString url = QString("ilwis://tables/projectedcsy?code=%1").arg(code); Resource resource(url, itCONVENTIONALCOORDSYSTEM); resource.code(code); resource.name(name, false); resource["wkt"] = name; resource.addContainer(QUrl("ilwis://system")); items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } bool InternalModule::createItems(QSqlQuery& db, const QString& table, IlwisTypes type) { QString query = QString("Select * from %1").arg(table); if ( db.exec(query)) { std::vector<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); IlwisTypes extType = rec.value("extendedtype").toLongLong(); QString url = QString("ilwis://tables/%1?code=%2").arg(table,code); Resource resource(url, type); if ( type == itNUMERICDOMAIN) // for valuedomain name=code resource.name(rec.value("code").toString(), false); else resource.name(rec.value("name").toString(), false); resource.code(code); resource.setExtendedType(extType); resource.setDescription(rec.value("description").toString()); resource.addContainer(QUrl("ilwis://system")); QString wkt = rec.value("wkt").toString(); if ( wkt != "" && wkt != sUNDEF) resource["wkt"] = wkt; items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } IlwisTypes InternalModule::ilwisType(const QString &name) { if ( name == sUNDEF) return itUNKNOWN; QString objectlocation = name; if ( !name.contains(QRegExp("\\\\|/"))) { objectlocation = "ilwis://internalcatalog/" + name; } Resource res = mastercatalog()->name2Resource(objectlocation); return res.ilwisType(); } <commit_msg>added colorpalette as new color itemdomain<commit_after>#include <QtPlugin> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include "kernel.h" #include "geos/geom/Coordinate.h" #include "coordinate.h" #include "location.h" #include "internalmodule.h" #include "ilwisdata.h" #include "range.h" #include "connectorinterface.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwisobjectfactory.h" #include "internalilwisobjectfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogexplorer.h" #include "catalogconnector.h" #include "internalrastercoverageconnector.h" #include "internalfeaturecoverageconnector.h" #include "internaltableconnector.h" #include "projection.h" #include "projectionimplementation.h" #include "projectionfactory.h" #include "internalprjmplfactory.h" #include "internalgeoreferenceconnector.h" #include "internaldomain.h" #include "internalcoordinatesystemconnector.h" using namespace Ilwis; using namespace Internal; InternalModule::InternalModule(QObject *parent) : Module(parent, "InternalModule", "iv40","1.0") { } QString InternalModule::getInterfaceVersion() const { return "iv40"; } void InternalModule::prepare() { InternalIlwisObjectFactory *ifactory = new InternalIlwisObjectFactory(); kernel()->addFactory(ifactory); ConnectorFactory *factory = kernel()->factory<ConnectorFactory>("ilwis::ConnectorFactory"); if (!factory) return ; factory->addCreator(itCATALOG,"internal",CatalogConnector::create); factory->addCreator(itRASTER,"internal", InternalRasterCoverageConnector::create); factory->addCreator(itTABLE,"internal", InternalTableConnector::create); factory->addCreator(itFEATURE,"internal", InternalFeatureCoverageConnector::create); factory->addCreator(itGEOREF,"internal", InternalGeoReferenceConnector::create); factory->addCreator(itDOMAIN,"internal", InternalDomainConnector::create); factory->addCreator(itCOORDSYSTEM,"internal", InternalCoordinatesystemConnector::create); FactoryInterface *projfactory = new ProjectionImplFactory(); projfactory->prepare(); kernel()->addFactory(projfactory ); QSqlQuery db(kernel()->database()); bool ok = createItems(db,"projection", itPROJECTION); ok &= createItems(db,"ellipsoid", itELLIPSOID); ok &= createItems(db,"datum", itGEODETICDATUM); ok &= createItems(db,"numericdomain", itNUMERICDOMAIN); ok &= createPcs(db); ok &= createSpecialDomains(); QString url = QString("ilwis://internalcatalog/unknown"); Resource resource(url, itBOUNDSONLYCSY); resource.code("unknown"); resource.name("unknown", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); mastercatalog()->addItems({resource}); url = QString("ilwis://internalcatalog/undetermined"); resource = Resource(url, itGEOREF); resource.code("undetermined"); resource.name("undetermined", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); mastercatalog()->addItems({resource}); IlwisObject::addTypeFunction(InternalModule::ilwisType); } QString InternalModule::name() const { return "Internal Connector connector plugin"; } QString InternalModule::version() const { return "1.0"; } bool InternalModule::createSpecialDomains() { std::vector<Resource> resources; QString url = QString("ilwis://internalcatalog/code=domain:text"); Resource resource(url, itTEXTDOMAIN); resource.code("text"); resource.name("Text domain", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); resources.push_back(resource); url = QString("ilwis://internalcatalog/code=domain:color"); Resource colorResource(url, itCOLORDOMAIN); colorResource.code("color"); colorResource.name("Color domain", false); colorResource.addContainer(QUrl("ilwis://internalcatalog")); colorResource.prepare(); resources.push_back(colorResource); url = QString("ilwis://internalcatalog/code=domain:colorpalette"); Resource paletteResource(url, itITEMDOMAIN); paletteResource.code("colorpalette"); paletteResource.name("Color Palette domain", false); paletteResource.addContainer(QUrl("ilwis://internalcatalog")); paletteResource.prepare(); resources.push_back(paletteResource); return mastercatalog()->addItems(resources); } bool InternalModule::createPcs(QSqlQuery& db) { QString query = QString("Select * from projectedcsy"); if ( db.exec(query)) { std::vector<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); QString name = rec.value("name").toString(); QString url = QString("ilwis://tables/projectedcsy?code=%1").arg(code); Resource resource(url, itCONVENTIONALCOORDSYSTEM); resource.code(code); resource.name(name, false); resource["wkt"] = name; resource.addContainer(QUrl("ilwis://system")); items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } bool InternalModule::createItems(QSqlQuery& db, const QString& table, IlwisTypes type) { QString query = QString("Select * from %1").arg(table); if ( db.exec(query)) { std::vector<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); IlwisTypes extType = rec.value("extendedtype").toLongLong(); QString url = QString("ilwis://tables/%1?code=%2").arg(table,code); Resource resource(url, type); if ( type == itNUMERICDOMAIN) // for valuedomain name=code resource.name(rec.value("code").toString(), false); else resource.name(rec.value("name").toString(), false); resource.code(code); resource.setExtendedType(extType); resource.setDescription(rec.value("description").toString()); resource.addContainer(QUrl("ilwis://system")); QString wkt = rec.value("wkt").toString(); if ( wkt != "" && wkt != sUNDEF) resource["wkt"] = wkt; items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } IlwisTypes InternalModule::ilwisType(const QString &name) { if ( name == sUNDEF) return itUNKNOWN; QString objectlocation = name; if ( !name.contains(QRegExp("\\\\|/"))) { objectlocation = "ilwis://internalcatalog/" + name; } Resource res = mastercatalog()->name2Resource(objectlocation); return res.ilwisType(); } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_STATE_HPP #define SOL_STATE_HPP #include "state_view.hpp" namespace sol { class state : private std::unique_ptr<lua_State, void(*)(lua_State*)>, public state_view { private: typedef std::unique_ptr<lua_State, void(*)(lua_State*)> unique_base; public: state(lua_CFunction panic = detail::atpanic) : unique_base(luaL_newstate(), lua_close), state_view(unique_base::get()) { set_panic(panic); } using state_view::get; }; } // sol #endif // SOL_STATE_HPP <commit_msg>pre-empty luajit exception handlers (turns out we really need it)<commit_after>// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_STATE_HPP #define SOL_STATE_HPP #include "state_view.hpp" namespace sol { class state : private std::unique_ptr<lua_State, void(*)(lua_State*)>, public state_view { private: typedef std::unique_ptr<lua_State, void(*)(lua_State*)> unique_base; public: state(lua_CFunction panic = detail::atpanic) : unique_base(luaL_newstate(), lua_close), state_view(unique_base::get()) { set_panic(panic); stack::luajit_exception_handler(unique_base::get()); } using state_view::get; }; } // sol #endif // SOL_STATE_HPP <|endoftext|>
<commit_before>#include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <cmath> #include <iostream> #include <vector> struct sound_generator { void play(int frequency, sf::Time duration) { unsigned constexpr sample_rate{44100}; unsigned const samples_size{static_cast<unsigned>(sample_rate * duration.asSeconds())}; std::vector<sf::Int16> samples(samples_size); unsigned const amplitude{30000}; double const two_pi{2 * 4 * std::atan(1)}; double const increment{static_cast<double>(frequency) / sample_rate}; double x{}; for (unsigned i{}; i < samples_size; ++i) { samples[i] = amplitude * std::sin(x * two_pi); x += increment; } if (not sound_buffer.loadFromSamples(samples.data(), samples_size, 1, sample_rate)) throw "Failed to load buffer"; sound.setBuffer(sound_buffer); sound.play(); } void stop() { sound.stop(); } sf::SoundBuffer sound_buffer; sf::Sound sound; }; void wait() { for (;;) sf::sleep(sf::milliseconds(100)); } unsigned find_inaudible(unsigned start, unsigned stop, unsigned step) { sound_generator gen; for (unsigned i{start}; i < stop; i += step) { gen.play(i, sf::milliseconds(500)); while (gen.sound.getStatus() == sf::SoundSource::Status::Playing) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return)) return i; sf::sleep(sf::milliseconds(10)); } } return stop; } int main() try { std::cout << "Press <Return> once you cannot hear the sound any more." << std::flush; unsigned const start{1000}; unsigned const stop{24000}; unsigned const step{500}; unsigned const result = find_inaudible(start, stop, step); std::cout << "You stopped hearing sound at " << result << " Hz frequency\n"; } catch (...) { std::cerr << "An error occurred\n"; return 1; } <commit_msg>Remove dead code<commit_after>#include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <cmath> #include <iostream> #include <vector> struct sound_generator { void play(int frequency, sf::Time duration) { unsigned constexpr sample_rate{44100}; unsigned const samples_size{static_cast<unsigned>(sample_rate * duration.asSeconds())}; std::vector<sf::Int16> samples(samples_size); unsigned const amplitude{30000}; double const two_pi{2 * 4 * std::atan(1)}; double const increment{static_cast<double>(frequency) / sample_rate}; double x{}; for (unsigned i{}; i < samples_size; ++i) { samples[i] = amplitude * std::sin(x * two_pi); x += increment; } if (not sound_buffer.loadFromSamples(samples.data(), samples_size, 1, sample_rate)) throw "Failed to load buffer"; sound.setBuffer(sound_buffer); sound.play(); } void stop() { sound.stop(); } sf::SoundBuffer sound_buffer; sf::Sound sound; }; unsigned find_inaudible(unsigned start, unsigned stop, unsigned step) { sound_generator gen; for (unsigned i{start}; i < stop; i += step) { gen.play(i, sf::milliseconds(500)); while (gen.sound.getStatus() == sf::SoundSource::Status::Playing) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return)) return i; sf::sleep(sf::milliseconds(10)); } } return stop; } int main() try { std::cout << "Press <Return> once you cannot hear the sound any more." << std::flush; unsigned const start{1000}; unsigned const stop{24000}; unsigned const step{500}; unsigned const result = find_inaudible(start, stop, step); std::cout << "You stopped hearing sound at " << result << " Hz frequency\n"; } catch (...) { std::cerr << "An error occurred\n"; return 1; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <mutex> #include <iostream> #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Event.h" #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Frameworks/Service/Main.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Frameworks::Service; using Characters::String; using Memory::Optional; using Containers::Sequence; /// *** TODO **** /// add option to log to LOGGER instead of stderr!!! /// (we have TODO adding wrapper of service backend which writes to syslog. Use that). // OR - maybe - just always do logging. Thats probably better, and have a flag in service wrapper // about log level? No - maybe thats obvihs too. Mabe just upagrade service code to use logger!!! // I think that would always - or nearly always - be desirable. Maybe make configurable. But no need // as a user can always use their own servcie impl! // namespace { struct AppRep_ : Main::IApplicationRep { AppRep_ () { } virtual ~AppRep_ () { } public: virtual void MainLoop () override { Execution::Sleep (1 * 24 * 60 * 60); // wait 1 day ... simple test.... } virtual Main::ServiceDescription GetServiceDescription () const override { Main::ServiceDescription t; t.fPrettyName = L"Test Service"; t.fRegistrationName = L"Test-Service"; return t; } }; } #if 0 usage --start, or --stop or --status or --restart #endif int main (int argc, const char* argv[]) { Sequence<String> args = Execution::ParseCommandLine (argc, argv); shared_ptr<Main::IServiceIntegrationRep> serviceIntegrationRep = Main::mkDefaultServiceIntegrationRep (); if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"run2Idle"); })) { // note - cannot use 'contains' because we need MatchesCommandLineArgument matching... serviceIntegrationRep = shared_ptr<Main::IServiceIntegrationRep> (new Main::RunTilIdleService ()); } Main m (shared_ptr<AppRep_> (new AppRep_ ()), serviceIntegrationRep); if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"status"); })) { cout << m.GetServiceStatusMessage ().AsUTF8<string> (); return EXIT_SUCCESS; } else if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"help"); })) { //ShowUsage_ (); return EXIT_SUCCESS; } try { m.Run (args); } catch (const std::exception& e) { cerr << "FAILED: (std::exception): '" << e.what () << endl; return EXIT_FAILURE; } catch (const Execution::StringException& e) { cerr << "FAILED: (Execution::StringException): '" << Characters::WideStringToNarrowSDKString (e.As<wstring> ()) << endl; return EXIT_FAILURE; } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>simplify arg handling in SampleService/Sources/SampleService.cpp with new (Execution::MatchesCommandLineArgument overloads<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <mutex> #include <iostream> #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Event.h" #include "Stroika/Foundation/Execution/Sleep.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Frameworks/Service/Main.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Frameworks::Service; using Characters::String; using Memory::Optional; using Containers::Sequence; /// *** TODO **** /// add option to log to LOGGER instead of stderr!!! /// (we have TODO adding wrapper of service backend which writes to syslog. Use that). // OR - maybe - just always do logging. Thats probably better, and have a flag in service wrapper // about log level? No - maybe thats obvihs too. Mabe just upagrade service code to use logger!!! // I think that would always - or nearly always - be desirable. Maybe make configurable. But no need // as a user can always use their own servcie impl! // namespace { struct AppRep_ : Main::IApplicationRep { AppRep_ () { } virtual ~AppRep_ () { } public: virtual void MainLoop () override { Execution::Sleep (1 * 24 * 60 * 60); // wait 1 day ... simple test.... } virtual Main::ServiceDescription GetServiceDescription () const override { Main::ServiceDescription t; t.fPrettyName = L"Test Service"; t.fRegistrationName = L"Test-Service"; return t; } }; } #if 0 usage --start, or --stop or --status or --restart #endif int main (int argc, const char* argv[]) { Sequence<String> args = Execution::ParseCommandLine (argc, argv); shared_ptr<Main::IServiceIntegrationRep> serviceIntegrationRep = Main::mkDefaultServiceIntegrationRep (); if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"run2Idle"); })) { // note - cannot use 'contains' because we need MatchesCommandLineArgument matching... serviceIntegrationRep = shared_ptr<Main::IServiceIntegrationRep> (new Main::RunTilIdleService ()); } Main m (shared_ptr<AppRep_> (new AppRep_ ()), serviceIntegrationRep); #if 1 if (Execution::MatchesCommandLineArgument (args, L"status")) { cout << m.GetServiceStatusMessage ().AsUTF8<string> (); return EXIT_SUCCESS; } else if (Execution::MatchesCommandLineArgument (args, L"help")) { //ShowUsage_ (); return EXIT_SUCCESS; } #else if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"status"); })) { cout << m.GetServiceStatusMessage ().AsUTF8<string> (); return EXIT_SUCCESS; } else if (args.ApplyUntilTrue ([] (const String & i) { return Execution::MatchesCommandLineArgument (i, L"help"); })) { //ShowUsage_ (); return EXIT_SUCCESS; } #endif try { m.Run (args); } catch (const std::exception& e) { cerr << "FAILED: (std::exception): '" << e.what () << endl; return EXIT_FAILURE; } catch (const Execution::StringException& e) { cerr << "FAILED: (Execution::StringException): '" << Characters::WideStringToNarrowSDKString (e.As<wstring> ()) << endl; return EXIT_FAILURE; } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <stddef.h> #include <stdio.h> #include <string.h> #include <malloc.h> #include <sys/dirent.h> #include <vector> #include <algorithm> #include "ui.h" #include "common.h" struct ui_alphabetize { inline bool operator() (char* a, char* b) { return strcasecmp(a, b) < 0; } }; bool uiIsDirectory(char* path) { DIR *dir = opendir(path); if(!dir) { return false; } closedir(dir); return true; } std::vector<char*>* uiGetDirectoryContents(const char* directory, const char* extensionFilter) { std::vector<char*>* contents = new std::vector<char*>(); char slash[strlen(directory) + 2]; snprintf(slash, sizeof(slash), "%s/", directory); DIR *dir = opendir(slash); if(dir != NULL) { while(true) { struct dirent *ent = readdir(dir); if(ent == NULL) { break; } char path[strlen(directory) + strlen(ent->d_name) + 2]; snprintf(path, strlen(directory) + strlen(ent->d_name) + 2, "%s/%s", directory, ent->d_name); if(uiIsDirectory(path)) { contents->push_back(strdup(ent->d_name)); } else { const char *dot = strrchr(path, '.'); if(dot && dot != path && strcmp(dot + 1, extensionFilter) == 0) { contents->push_back(strdup(ent->d_name)); } } } closedir(dir); contents->push_back(strdup(".")); contents->push_back(strdup("..")); std::sort(contents->begin(), contents->end(), ui_alphabetize()); } else { return NULL; } return contents; } std::vector<char*>* uiTitlesToVector(App* apps, u32 count) { std::vector<char*>* contents = new std::vector<char*>(); if(count == 0) { contents->push_back(strdup("None")); } else { for(u32 title = 0; title < count; title++) { contents->push_back(sdprintf("%08lx - %s, %s, %s", apps[title].uniqueId, apps[title].productCode, app_get_platform_name(apps[title].platform), app_get_category_name(apps[title].category))); } } std::sort(contents->begin(), contents->end(), ui_alphabetize()); return contents; } void uiFreeVectorContents(std::vector<char*>* contents) { for(std::vector<char*>::iterator it = contents->begin(); it != contents->end(); it++) { free((char*) *it); } } UIResult uiDisplaySelector(char** selected, std::vector<char*>* contents, MediaType destination, Mode mode) { const char* selectCia = mode == INSTALL ? "Select a CIA to install." : "Select a CIA to delete."; const char* pressL = "Press L to switch destinations."; const char* pressR = "Press R to switch between installing and deleting."; const char* destString = destination == NAND ? "Destination: NAND" : "Destination: SD"; const char* modeString = mode == INSTALL ? "Mode: Install" : "Mode: Delete"; unsigned int cursor = 0; unsigned int scroll = 0; int horizScroll = 0; u64 horizEndTime = 0; UIResult result = SUCCESS; while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_A)) { *selected = contents->at(cursor); result = SUCCESS; break; } if(input_is_pressed(BUTTON_B)) { result = BACK; break; } if(input_is_pressed(BUTTON_L)) { result = SWITCH_DEST; break; } if(input_is_pressed(BUTTON_R)) { result = SWITCH_MODE; break; } if(input_is_pressed(BUTTON_DOWN) && cursor < contents->size() - 1) { cursor++; int diff = cursor - scroll; if(diff >= 20) { scroll++; } horizScroll = 0; horizEndTime = 0; } if(input_is_pressed(BUTTON_UP) && cursor > 0) { cursor--; int diff = cursor - scroll; if(diff < 0) { scroll--; } horizScroll = 0; horizEndTime = 0; } screen_begin_draw(); screen_clear(0, 0, 0); int screenWidth = screen_get_width(); int i = 0; for(std::vector<char*>::iterator it = contents->begin() + scroll; it != contents->end(); it++) { u8 color = 255; int offset = 0; if(i + scroll == cursor) { screen_fill(0, i * 12, screenWidth, 8, 255, 255, 255); color = 0; int width = strlen(*it) * 8; if(width > screenWidth) { if(-horizScroll + screenWidth >= width) { if(horizEndTime == 0) { horizEndTime = platform_get_time(); } else if(platform_get_time() - horizEndTime >= 4000) { horizScroll = 0; horizEndTime = 0; } } else { horizScroll -= 1; } } offset = horizScroll; } screen_draw_string(*it, offset, i * 12, color, color, color); i++; if(i >= 20) { break; } } screen_end_draw(); screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(selectCia, (screen_get_width() - screen_get_str_width(selectCia)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2 - screen_get_str_height(selectCia), 255, 255, 255); screen_draw_string(pressL, (screen_get_width() - screen_get_str_width(pressL)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2, 255, 255, 255); screen_draw_string(pressR, (screen_get_width() - screen_get_str_width(pressR)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2 + screen_get_str_height(pressR), 255, 255, 255); screen_draw_string(destString, 0, screen_get_height() - screen_get_str_height(destString), 255, 255, 255); screen_draw_string(modeString, screen_get_width() - screen_get_str_width(modeString), screen_get_height() - screen_get_str_height(modeString), 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } if(!platform_is_running()) { result = EXIT_APP; } return result; } UIResult uiSelectFile(char** selected, const char* directory, const char* extension, MediaType* destination, Mode* mode) { std::vector<char*>* contents = uiGetDirectoryContents(directory, extension); UIResult result; while(true) { char* selectedEntry = NULL; UIResult res = uiDisplaySelector(&selectedEntry, contents, *destination, *mode); if(res == SWITCH_DEST) { if(*destination == NAND) { *destination = SD; } else { *destination = NAND; } continue; } else if(res == BACK || (selectedEntry != NULL && strcmp(selectedEntry, "..") == 0)) { if(strcmp(directory, "sdmc:") != 0) { result = BACK; break; } else { continue; } } else if(res != SUCCESS) { result = res; break; } if(strcmp(selectedEntry, ".") == 0) { continue; } char* path = (char*) malloc(strlen(directory) + strlen(selectedEntry) + 2); snprintf(path, strlen(directory) + strlen(selectedEntry) + 2, "%s/%s", directory, selectedEntry); if(uiIsDirectory(path)) { char *select; UIResult dirRes = uiSelectFile(&select, path, extension, destination, mode); free(path); if(dirRes == BACK) { continue; } result = dirRes; *selected = select; break; } else { result = SUCCESS; *selected = path; break; } } uiFreeVectorContents(contents); delete(contents); return result; } UIResult uiSelectTitle(App* selected, MediaType* destination, Mode* mode) { u32 appCount; App* apps = app_list(*destination, &appCount); std::vector<char*>* contents = uiTitlesToVector(apps, appCount); UIResult result; while(true) { char* selectedEntry = NULL; UIResult res = uiDisplaySelector(&selectedEntry, contents, *destination, *mode); if(selectedEntry != NULL && strcmp(selectedEntry, "None") == 0) { continue; } if(res == BACK) { continue; } else if(res == SWITCH_DEST) { if(*destination == NAND) { *destination = SD; } else { *destination = NAND; } uiFreeVectorContents(contents); delete(contents); free(apps); apps = app_list(*destination, &appCount); contents = uiTitlesToVector(apps, appCount); continue; } else if(res != SUCCESS) { result = res; break; } for(u32 i = 0; i < appCount; i++) { char* data = sdprintf("%08lx - %s, %s, %s", apps[i].uniqueId, apps[i].productCode, app_get_platform_name(apps[i].platform), app_get_category_name(apps[i].category)); if(strcmp(selectedEntry, data) == 0) { *selected = apps[i]; free(data); break; } free(data); } if(selected == NULL) { continue; } result = SUCCESS; break; } uiFreeVectorContents(contents); delete(contents); free(apps); return result; } bool uiDisplayInstallProgress(int progress) { char* msg = sdprintf("Installing: [ ] %03d%%", progress); const char* cancel = "Press B to cancel."; for(int pos = 13; pos < 13 + (progress / 4); pos++) { msg[pos] = '|'; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_draw_string(cancel, (screen_get_width() - screen_get_str_width(cancel)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2 + (screen_get_str_height(msg) * 2), 255, 255, 255); screen_end_draw(); screen_swap_buffers_quick(); free(msg); input_poll(); return !input_is_pressed(BUTTON_B); } void uiDisplayDeleting() { const char* msg = "Deleting title..."; screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } void uiDisplayResult(bool install, bool state) { const char* msg = install ? (state ? "Install succeeded! Press start." : "Install failed! Press start.") : (state ? "Delete succeeded! Press start." : "Delete failed! Press start."); while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_START)) { break; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } } bool uiPromptOperation(Mode mode) { char* msg = sdprintf("%s the selected title?", mode == INSTALL ? "Install" : "Delete"); const char* prompt = "Press A to confirm, B to cancel."; while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_A)) { free(msg); return true; } if(input_is_pressed(BUTTON_B)) { free(msg); return false; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_draw_string(prompt, (screen_get_width() - screen_get_str_width(prompt)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2 + screen_get_str_height(msg), 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } free(msg); return false; } <commit_msg>Space out text in UI prompts.<commit_after>#include <stddef.h> #include <stdio.h> #include <string.h> #include <malloc.h> #include <sys/dirent.h> #include <vector> #include <algorithm> #include "ui.h" #include "common.h" struct ui_alphabetize { inline bool operator() (char* a, char* b) { return strcasecmp(a, b) < 0; } }; bool uiIsDirectory(char* path) { DIR *dir = opendir(path); if(!dir) { return false; } closedir(dir); return true; } std::vector<char*>* uiGetDirectoryContents(const char* directory, const char* extensionFilter) { std::vector<char*>* contents = new std::vector<char*>(); char slash[strlen(directory) + 2]; snprintf(slash, sizeof(slash), "%s/", directory); DIR *dir = opendir(slash); if(dir != NULL) { while(true) { struct dirent *ent = readdir(dir); if(ent == NULL) { break; } char path[strlen(directory) + strlen(ent->d_name) + 2]; snprintf(path, strlen(directory) + strlen(ent->d_name) + 2, "%s/%s", directory, ent->d_name); if(uiIsDirectory(path)) { contents->push_back(strdup(ent->d_name)); } else { const char *dot = strrchr(path, '.'); if(dot && dot != path && strcmp(dot + 1, extensionFilter) == 0) { contents->push_back(strdup(ent->d_name)); } } } closedir(dir); contents->push_back(strdup(".")); contents->push_back(strdup("..")); std::sort(contents->begin(), contents->end(), ui_alphabetize()); } else { return NULL; } return contents; } std::vector<char*>* uiTitlesToVector(App* apps, u32 count) { std::vector<char*>* contents = new std::vector<char*>(); if(count == 0) { contents->push_back(strdup("None")); } else { for(u32 title = 0; title < count; title++) { contents->push_back(sdprintf("%08lx - %s, %s, %s", apps[title].uniqueId, apps[title].productCode, app_get_platform_name(apps[title].platform), app_get_category_name(apps[title].category))); } } std::sort(contents->begin(), contents->end(), ui_alphabetize()); return contents; } void uiFreeVectorContents(std::vector<char*>* contents) { for(std::vector<char*>::iterator it = contents->begin(); it != contents->end(); it++) { free((char*) *it); } } UIResult uiDisplaySelector(char** selected, std::vector<char*>* contents, MediaType destination, Mode mode) { const char* selectCia = mode == INSTALL ? "Select a CIA to install." : "Select a CIA to delete."; const char* pressL = "Press L to switch destinations."; const char* pressR = "Press R to switch between installing and deleting."; const char* destString = destination == NAND ? "Destination: NAND" : "Destination: SD"; const char* modeString = mode == INSTALL ? "Mode: Install" : "Mode: Delete"; unsigned int cursor = 0; unsigned int scroll = 0; int horizScroll = 0; u64 horizEndTime = 0; UIResult result = SUCCESS; while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_A)) { *selected = contents->at(cursor); result = SUCCESS; break; } if(input_is_pressed(BUTTON_B)) { result = BACK; break; } if(input_is_pressed(BUTTON_L)) { result = SWITCH_DEST; break; } if(input_is_pressed(BUTTON_R)) { result = SWITCH_MODE; break; } if(input_is_pressed(BUTTON_DOWN) && cursor < contents->size() - 1) { cursor++; int diff = cursor - scroll; if(diff >= 20) { scroll++; } horizScroll = 0; horizEndTime = 0; } if(input_is_pressed(BUTTON_UP) && cursor > 0) { cursor--; int diff = cursor - scroll; if(diff < 0) { scroll--; } horizScroll = 0; horizEndTime = 0; } screen_begin_draw(); screen_clear(0, 0, 0); int screenWidth = screen_get_width(); int i = 0; for(std::vector<char*>::iterator it = contents->begin() + scroll; it != contents->end(); it++) { u8 color = 255; int offset = 0; if(i + scroll == cursor) { screen_fill(0, i * 12, screenWidth, 8, 255, 255, 255); color = 0; int width = strlen(*it) * 8; if(width > screenWidth) { if(-horizScroll + screenWidth >= width) { if(horizEndTime == 0) { horizEndTime = platform_get_time(); } else if(platform_get_time() - horizEndTime >= 4000) { horizScroll = 0; horizEndTime = 0; } } else { horizScroll -= 1; } } offset = horizScroll; } screen_draw_string(*it, offset, i * 12, color, color, color); i++; if(i >= 20) { break; } } screen_end_draw(); screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(selectCia, (screen_get_width() - screen_get_str_width(selectCia)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2 - screen_get_str_height(selectCia), 255, 255, 255); screen_draw_string(pressL, (screen_get_width() - screen_get_str_width(pressL)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2, 255, 255, 255); screen_draw_string(pressR, (screen_get_width() - screen_get_str_width(pressR)) / 2, (screen_get_height() - screen_get_str_height(pressL)) / 2 + screen_get_str_height(pressR), 255, 255, 255); screen_draw_string(destString, 0, screen_get_height() - screen_get_str_height(destString), 255, 255, 255); screen_draw_string(modeString, screen_get_width() - screen_get_str_width(modeString), screen_get_height() - screen_get_str_height(modeString), 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } if(!platform_is_running()) { result = EXIT_APP; } return result; } UIResult uiSelectFile(char** selected, const char* directory, const char* extension, MediaType* destination, Mode* mode) { std::vector<char*>* contents = uiGetDirectoryContents(directory, extension); UIResult result; while(true) { char* selectedEntry = NULL; UIResult res = uiDisplaySelector(&selectedEntry, contents, *destination, *mode); if(res == SWITCH_DEST) { if(*destination == NAND) { *destination = SD; } else { *destination = NAND; } continue; } else if(res == BACK || (selectedEntry != NULL && strcmp(selectedEntry, "..") == 0)) { if(strcmp(directory, "sdmc:") != 0) { result = BACK; break; } else { continue; } } else if(res != SUCCESS) { result = res; break; } if(strcmp(selectedEntry, ".") == 0) { continue; } char* path = (char*) malloc(strlen(directory) + strlen(selectedEntry) + 2); snprintf(path, strlen(directory) + strlen(selectedEntry) + 2, "%s/%s", directory, selectedEntry); if(uiIsDirectory(path)) { char *select; UIResult dirRes = uiSelectFile(&select, path, extension, destination, mode); free(path); if(dirRes == BACK) { continue; } result = dirRes; *selected = select; break; } else { result = SUCCESS; *selected = path; break; } } uiFreeVectorContents(contents); delete(contents); return result; } UIResult uiSelectTitle(App* selected, MediaType* destination, Mode* mode) { u32 appCount; App* apps = app_list(*destination, &appCount); std::vector<char*>* contents = uiTitlesToVector(apps, appCount); UIResult result; while(true) { char* selectedEntry = NULL; UIResult res = uiDisplaySelector(&selectedEntry, contents, *destination, *mode); if(selectedEntry != NULL && strcmp(selectedEntry, "None") == 0) { continue; } if(res == BACK) { continue; } else if(res == SWITCH_DEST) { if(*destination == NAND) { *destination = SD; } else { *destination = NAND; } uiFreeVectorContents(contents); delete(contents); free(apps); apps = app_list(*destination, &appCount); contents = uiTitlesToVector(apps, appCount); continue; } else if(res != SUCCESS) { result = res; break; } for(u32 i = 0; i < appCount; i++) { char* data = sdprintf("%08lx - %s, %s, %s", apps[i].uniqueId, apps[i].productCode, app_get_platform_name(apps[i].platform), app_get_category_name(apps[i].category)); if(strcmp(selectedEntry, data) == 0) { *selected = apps[i]; free(data); break; } free(data); } if(selected == NULL) { continue; } result = SUCCESS; break; } uiFreeVectorContents(contents); delete(contents); free(apps); return result; } bool uiDisplayInstallProgress(int progress) { char* msg = sdprintf("Installing: [ ] %03d%%", progress); const char* cancel = "Press B to cancel."; for(int pos = 13; pos < 13 + (progress / 4); pos++) { msg[pos] = '|'; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2 - screen_get_str_height(msg), 255, 255, 255); screen_draw_string(cancel, (screen_get_width() - screen_get_str_width(cancel)) / 2, (screen_get_height() - screen_get_str_height(cancel)) / 2 + screen_get_str_height(cancel), 255, 255, 255); screen_end_draw(); screen_swap_buffers_quick(); free(msg); input_poll(); return !input_is_pressed(BUTTON_B); } void uiDisplayDeleting() { const char* msg = "Deleting title..."; screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } void uiDisplayResult(bool install, bool state) { const char* msg = install ? (state ? "Install succeeded! Press start." : "Install failed! Press start.") : (state ? "Delete succeeded! Press start." : "Delete failed! Press start."); while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_START)) { break; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } } bool uiPromptOperation(Mode mode) { char* msg = sdprintf("%s the selected title?", mode == INSTALL ? "Install" : "Delete"); const char* prompt = "Press A to confirm, B to cancel."; while(platform_is_running()) { input_poll(); if(input_is_pressed(BUTTON_A)) { free(msg); return true; } if(input_is_pressed(BUTTON_B)) { free(msg); return false; } screen_begin_draw_info(); screen_clear(0, 0, 0); screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2 - screen_get_str_height(msg), 255, 255, 255); screen_draw_string(prompt, (screen_get_width() - screen_get_str_width(prompt)) / 2, (screen_get_height() - screen_get_str_height(prompt)) / 2 + screen_get_str_height(prompt), 255, 255, 255); screen_end_draw(); screen_swap_buffers(); } free(msg); return false; } <|endoftext|>
<commit_before>#include "sfsmisc.h" #include "dhash_prot.h" #include "dhash.h" #include "crypt.h" #include <sys/time.h> float avg_lookupRPCs; static ptr<aclnt> p2pclnt; static bigint *IDs; static void **data; static str control_socket; static FILE *outfile; int out = 0; int out_op = 0; int OPS_OUT = 1024; void afetch_cb (dhash_res *res, chordID key, char *buf, int i, struct timeval start, clnt_stat err); void afetch_cb2 (dhash_res *res, char *buf, unsigned int *read, int i, struct timeval start, clnt_stat err); ref<aclnt> cp2p () { int fd; if (p2pclnt) return p2pclnt; fd = unixsocket_connect (control_socket); if (fd < 0) fatal ("%s: %m\n", control_socket.cstr ()); p2pclnt = aclnt::alloc (axprt_unix::alloc (fd), dhashclnt_program_1); return p2pclnt; } #define MTU 1024 int store_block(chordID key, void *data, unsigned int datasize) { dhash_storeres res; dhash_insertarg *i_arg = New dhash_insertarg (); i_arg->key = key; int n = (MTU < datasize) ? MTU : datasize; i_arg->data.setsize(n); i_arg->type = DHASH_STORE; i_arg->attr.size = datasize; i_arg->offset = 0; memcpy(i_arg->data.base (), (char *)data, n); clnt_stat err = cp2p ()->scall(DHASHPROC_INSERT, i_arg, &res); if (err) warn << "RPC error: " << err << "\n"; if (err) return -err; unsigned int written = n; delete i_arg; chordID source = res.resok->source; while (!res.resok->done) { n = (written + MTU < datasize) ? MTU : datasize - written; dhash_send_arg *sarg = New dhash_send_arg(); sarg->dest = source; sarg->iarg.key = key; sarg->iarg.data.setsize(n); memcpy (sarg->iarg.data.base (), (char *)data + written, n); sarg->iarg.type = DHASH_STORE; sarg->iarg.attr.size = datasize; sarg->iarg.offset = written; clnt_stat err = cp2p ()->scall(DHASHPROC_SEND, sarg, &res); if (err) warn << "RPC error: " << err << "\n"; if (err) return -err; if (res.status != DHASH_OK) return res.status; written += n; delete sarg; }; return DHASH_OK; } int fetch_block(int i, chordID key, int datasize) { dhash_res res; char *buf = New char[datasize]; dhash_fetch_arg arg; arg.key = key; arg.len = MTU; arg.start = 0; int err = cp2p ()->scall(DHASHPROC_LOOKUP, &arg, &res); assert (err == 0); if (res.status != DHASH_OK) warn << "error " << res.status << "fetching data\n"; memcpy(buf, res.resok->res.base (), res.resok->res.size ()); unsigned int read = res.resok->res.size (); while (read < res.resok->attr.size) { arg.len = (read + MTU < res.resok->attr.size) ? MTU : res.resok->attr.size - read; arg.start = read; err = cp2p ()->scall(DHASHPROC_LOOKUP, &arg, &res); if (res.status != DHASH_OK) warn << "error fetching data\n"; memcpy(buf + read, res.resok->res.base (), res.resok->res.size ()); read += res.resok->res.size (); }; #define VERIFY #ifdef VERIFY int diff = memcmp(data[i], buf, datasize); assert (!diff); #endif delete buf; if (err) return -err; else return DHASH_OK; } int fetch_block_async(int i, chordID key, int datasize) { dhash_res *res = New dhash_res (DHASH_OK); char *buf = New char[datasize]; struct timeval start; gettimeofday (&start, NULL); dhash_fetch_arg arg; arg.key = key; arg.len = MTU; arg.start = 0; out++; cp2p ()->call(DHASHPROC_LOOKUP, &arg, res, wrap(&afetch_cb, res, key, buf, i, start)); return 0; } void finish (char *buf, unsigned int *read, struct timeval start, int i, dhash_res *res) { out--; #ifdef VERIFY int diff = memcmp(data[i], buf, *read); assert (!diff); #endif struct timeval end; gettimeofday(&end, NULL); float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0; fprintf(outfile, "%f %d\n", elapsed, res->resok->hops); delete read; delete buf; } void afetch_cb (dhash_res *res, chordID key, char *buf, int i, struct timeval start, clnt_stat err) { if (err) { strbuf sb; rpc_print (sb, key, 5, NULL, " "); str s = sb; fprintf(outfile, "RPC error: %d %s", err, s.cstr()); out--; return; } if (res->status != DHASH_OK) { strbuf sb; rpc_print (sb, key, 5, NULL, " "); str s = sb; fprintf(outfile, "Error: %d %s", res->status, s.cstr()); out--; return; } memcpy(buf, res->resok->res.base (), res->resok->res.size ()); unsigned int *read = New unsigned int(res->resok->res.size ()); unsigned int off = res->resok->res.size (); if (off == res->resok->attr.size) finish (buf, read, start, i, res); while (off < res->resok->attr.size) { ptr<dhash_transfer_arg> arg = New refcounted<dhash_transfer_arg> (); arg->farg.key = key; arg->farg.len = (off + MTU < res->resok->attr.size) ? MTU : res->resok->attr.size - off; arg->farg.start = off; arg->source = res->resok->source; dhash_res *nres = New dhash_res(DHASH_OK); out_op++; cp2p ()->call(DHASHPROC_TRANSFER, arg, nres, wrap(&afetch_cb2, nres, buf, read, i, start)); off += arg->farg.len; }; delete res; } void afetch_cb2 (dhash_res *res, char *buf, unsigned int *read, int i, struct timeval start, clnt_stat err) { if (err) { out_op--; warn << "err: " << err << "\n"; return; } assert(err == 0); assert(res->status == DHASH_OK); memcpy(buf + res->resok->offset, res->resok->res.base (), res->resok->res.size ()); *read += res->resok->res.size (); out_op--; if (*read == res->resok->attr.size) finish (buf, read, start, i, res); delete res; } chordID random_ID () { return random_bigint(NBIT); } //size must be word sized chordID make_block(void *data, int size) { long *rd = (long *)data; for (unsigned int i = 0; i < size/sizeof(long); i++) rd[i] = random(); char id[sha1::hashsize]; sha1_hash (id, rd, size); chordID ID; mpz_set_rawmag_be (&ID, id, sizeof (id)); // For big endian return ID; } void prepare_test_data(int num, int datasize) { IDs = New chordID[num]; data = (void **)malloc(sizeof(void *)*num); for (int i = 0; i < num; i++) { data[i] = malloc(datasize); IDs[i] = make_block(data[i], datasize); } } int store(int num, int size) { for (int i = 0; i < num; i++) { int err = store_block(IDs[i], data[i], size); if (err) warn << "ERROR: " << err << "\n"; } return 0; } int fetch(int num, int size) { for (int i = 0; i < num; i++) { fetch_block_async(i, IDs[i], size); while (out > OPS_OUT) acheck (); } while (out > 0) acheck(); return 0; } void usage(char *progname) { printf("%s: vnode_num control_socket num_trials data_size file <f or s> nops\n", progname); exit(0); } int main (int argc, char **argv) { dhash_fetchiter_res *res = New dhash_fetchiter_res (DHASH_CONTINUE); res = NULL; sfsconst_init (); if (argc < 8) { usage (argv[0]); exit (1); } control_socket = argv[2]; int num = atoi(argv[3]); int datasize = atoi(argv[4]); char *output = argv[5]; if (strcmp(output, "-") == 0) outfile = stdout; else outfile = fopen(output, "w"); if (!outfile) { printf ("could not open %s\n", output); exit(1); } int i = atoi(argv[1]); dhash_stat ares; cp2p ()->scall(DHASHPROC_ACTIVE, &i, &ares); prepare_test_data (num, datasize); OPS_OUT = atoi(argv[7]); struct timeval start; gettimeofday (&start, NULL); if (argv[6][0] == 's') store(num, datasize); else fetch(num, datasize); struct timeval end; gettimeofday (&end, NULL); float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0; fprintf(outfile, "Total Elapsed: %f\n", elapsed); } <commit_msg>added seed parameter<commit_after>#include "sfsmisc.h" #include "dhash_prot.h" #include "dhash.h" #include "crypt.h" #include <sys/time.h> float avg_lookupRPCs; static ptr<aclnt> p2pclnt; static bigint *IDs; static void **data; static str control_socket; static FILE *outfile; int out = 0; int out_op = 0; int OPS_OUT = 1024; void afetch_cb (dhash_res *res, chordID key, char *buf, int i, struct timeval start, clnt_stat err); void afetch_cb2 (dhash_res *res, char *buf, unsigned int *read, int i, struct timeval start, clnt_stat err); ref<aclnt> cp2p () { int fd; if (p2pclnt) return p2pclnt; fd = unixsocket_connect (control_socket); if (fd < 0) fatal ("%s: %m\n", control_socket.cstr ()); p2pclnt = aclnt::alloc (axprt_unix::alloc (fd), dhashclnt_program_1); return p2pclnt; } #define MTU 1024 int store_block(chordID key, void *data, unsigned int datasize) { dhash_storeres res; dhash_insertarg *i_arg = New dhash_insertarg (); i_arg->key = key; int n = (MTU < datasize) ? MTU : datasize; i_arg->data.setsize(n); i_arg->type = DHASH_STORE; i_arg->attr.size = datasize; i_arg->offset = 0; memcpy(i_arg->data.base (), (char *)data, n); clnt_stat err = cp2p ()->scall(DHASHPROC_INSERT, i_arg, &res); if (err) warn << "RPC error: " << err << "\n"; if (err) return -err; unsigned int written = n; delete i_arg; chordID source = res.resok->source; while (!res.resok->done) { n = (written + MTU < datasize) ? MTU : datasize - written; dhash_send_arg *sarg = New dhash_send_arg(); sarg->dest = source; sarg->iarg.key = key; sarg->iarg.data.setsize(n); memcpy (sarg->iarg.data.base (), (char *)data + written, n); sarg->iarg.type = DHASH_STORE; sarg->iarg.attr.size = datasize; sarg->iarg.offset = written; clnt_stat err = cp2p ()->scall(DHASHPROC_SEND, sarg, &res); if (err) warn << "RPC error: " << err << "\n"; if (err) return -err; if (res.status != DHASH_OK) return res.status; written += n; delete sarg; }; return DHASH_OK; } int fetch_block(int i, chordID key, int datasize) { dhash_res res; char *buf = New char[datasize]; dhash_fetch_arg arg; arg.key = key; arg.len = MTU; arg.start = 0; int err = cp2p ()->scall(DHASHPROC_LOOKUP, &arg, &res); assert (err == 0); if (res.status != DHASH_OK) warn << "error " << res.status << "fetching data\n"; memcpy(buf, res.resok->res.base (), res.resok->res.size ()); unsigned int read = res.resok->res.size (); while (read < res.resok->attr.size) { arg.len = (read + MTU < res.resok->attr.size) ? MTU : res.resok->attr.size - read; arg.start = read; err = cp2p ()->scall(DHASHPROC_LOOKUP, &arg, &res); if (res.status != DHASH_OK) warn << "error fetching data\n"; memcpy(buf + read, res.resok->res.base (), res.resok->res.size ()); read += res.resok->res.size (); }; #define VERIFY #ifdef VERIFY int diff = memcmp(data[i], buf, datasize); assert (!diff); #endif delete buf; if (err) return -err; else return DHASH_OK; } int fetch_block_async(int i, chordID key, int datasize) { dhash_res *res = New dhash_res (DHASH_OK); char *buf = New char[datasize]; struct timeval start; gettimeofday (&start, NULL); dhash_fetch_arg arg; arg.key = key; arg.len = MTU; arg.start = 0; out++; cp2p ()->call(DHASHPROC_LOOKUP, &arg, res, wrap(&afetch_cb, res, key, buf, i, start)); return 0; } void finish (char *buf, unsigned int *read, struct timeval start, int i, dhash_res *res) { out--; #ifdef VERIFY int diff = memcmp(data[i], buf, *read); assert (!diff); #endif struct timeval end; gettimeofday(&end, NULL); float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0; fprintf(outfile, "%f %d\n", elapsed, res->resok->hops); delete read; delete buf; } void afetch_cb (dhash_res *res, chordID key, char *buf, int i, struct timeval start, clnt_stat err) { if (err) { strbuf sb; rpc_print (sb, key, 5, NULL, " "); str s = sb; fprintf(outfile, "RPC error: %d %s", err, s.cstr()); out--; return; } if (res->status != DHASH_OK) { strbuf sb; rpc_print (sb, key, 5, NULL, " "); str s = sb; fprintf(outfile, "Error: %d %s", res->status, s.cstr()); out--; return; } memcpy(buf, res->resok->res.base (), res->resok->res.size ()); unsigned int *read = New unsigned int(res->resok->res.size ()); unsigned int off = res->resok->res.size (); if (off == res->resok->attr.size) finish (buf, read, start, i, res); while (off < res->resok->attr.size) { ptr<dhash_transfer_arg> arg = New refcounted<dhash_transfer_arg> (); arg->farg.key = key; arg->farg.len = (off + MTU < res->resok->attr.size) ? MTU : res->resok->attr.size - off; arg->farg.start = off; arg->source = res->resok->source; dhash_res *nres = New dhash_res(DHASH_OK); out_op++; cp2p ()->call(DHASHPROC_TRANSFER, arg, nres, wrap(&afetch_cb2, nres, buf, read, i, start)); off += arg->farg.len; }; delete res; } void afetch_cb2 (dhash_res *res, char *buf, unsigned int *read, int i, struct timeval start, clnt_stat err) { if (err) { out_op--; warn << "err: " << err << "\n"; return; } assert(err == 0); assert(res->status == DHASH_OK); memcpy(buf + res->resok->offset, res->resok->res.base (), res->resok->res.size ()); *read += res->resok->res.size (); out_op--; if (*read == res->resok->attr.size) finish (buf, read, start, i, res); delete res; } //size must be word sized chordID make_block(void *data, int size) { long *rd = (long *)data; for (unsigned int i = 0; i < size/sizeof(long); i++) rd[i] = random(); char id[sha1::hashsize]; sha1_hash (id, rd, size); chordID ID; mpz_set_rawmag_be (&ID, id, sizeof (id)); // For big endian return ID; } void prepare_test_data(int num, int datasize) { IDs = New chordID[num]; data = (void **)malloc(sizeof(void *)*num); for (int i = 0; i < num; i++) { data[i] = malloc(datasize); IDs[i] = make_block(data[i], datasize); } } int store(int num, int size) { for (int i = 0; i < num; i++) { int err = store_block(IDs[i], data[i], size); if (err) warn << "ERROR: " << err << "\n"; } return 0; } int fetch(int num, int size) { for (int i = 0; i < num; i++) { fetch_block_async(i, IDs[i], size); while (out > OPS_OUT) acheck (); } while (out > 0) acheck(); return 0; } void usage(char *progname) { printf("%s: vnode_num control_socket num_trials data_size file <f or s> nops seed\n", progname); exit(0); } int main (int argc, char **argv) { dhash_fetchiter_res *res = New dhash_fetchiter_res (DHASH_CONTINUE); res = NULL; sfsconst_init (); if (argc < 9) { usage (argv[0]); exit (1); } control_socket = argv[2]; int num = atoi(argv[3]); int datasize = atoi(argv[4]); char *output = argv[5]; if (strcmp(output, "-") == 0) outfile = stdout; else outfile = fopen(output, "w"); if (!outfile) { printf ("could not open %s\n", output); exit(1); } int i = atoi(argv[1]); dhash_stat ares; cp2p ()->scall(DHASHPROC_ACTIVE, &i, &ares); unsigned int seed = strtoul (argv[8], NULL, 10); srandom (seed); prepare_test_data (num, datasize); OPS_OUT = atoi(argv[7]); struct timeval start; gettimeofday (&start, NULL); if (argv[6][0] == 's') store(num, datasize); else fetch(num, datasize); struct timeval end; gettimeofday (&end, NULL); float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0; fprintf(outfile, "Total Elapsed: %f\n", elapsed); } <|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareButton.h" #include "../../Player/FlareMenuManager.h" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareButton::Construct(const FArguments& InArgs) { // Setup IsPressed = false; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Arguments Icon = InArgs._Icon; IsToggle = InArgs._Toggle; IsSmallToggleIcons = InArgs._SmallToggleIcons; IsTransparent = InArgs._Transparent; OnClicked = InArgs._OnClicked; Color = InArgs._Color; Text = InArgs._Text; HelpText = InArgs._HelpText; IsDisabled = InArgs._IsDisabled; Width = InArgs._Width * Theme.ButtonWidth; Height = InArgs._Height * Theme.ButtonHeight; // Structure ChildSlot .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ // Button (behaviour only, no display) SAssignNew(InternalButton, SButton) .OnClicked(this, &SFlareButton::OnButtonClicked) .ContentPadding(FMargin(0)) .ButtonStyle(FFlareStyleSet::Get(), "Flare.CoreButton") [ SNew(SVerticalBox) // Upper border + SVerticalBox::Slot() .AutoHeight() [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] // Main line + SVerticalBox::Slot() .AutoHeight() [ // Left border SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Fill) [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] // Main content box + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(Width) .HeightOverride(Height) .Padding(FMargin(0)) [ // Button background SNew(SBorder) .Padding(FMargin(0)) .BorderImage(this, &SFlareButton::GetBackgroundBrush) [ SNew(SHorizontalBox) // Toggle light + SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) .VAlign(VAlign_Fill) [ SNew(SImage) .Image(this, &SFlareButton::GetDecoratorBrush) ] // Content box and inner container + SHorizontalBox::Slot() [ SAssignNew(InnerContainer, SBorder) .HAlign(HAlign_Left) .VAlign(VAlign_Center) .BorderImage(new FSlateNoResource) ] ] ] ] // Right border + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Fill) [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] ] // Lower border + SVerticalBox::Slot() .AutoHeight() [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] ] ]; // Construct text content if we need to if (InArgs._Text.IsSet()) { TSharedPtr<SVerticalBox> IconBox; InnerContainer->SetPadding(IsTransparent ? FMargin(0) : Theme.ButtonPadding); InnerContainer->SetContent( SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() .Padding(FMargin(3, 0)) [ SAssignNew(IconBox, SVerticalBox) ] // Text + SHorizontalBox::Slot() .VAlign(VAlign_Center) [ SAssignNew(TextBlock, STextBlock) .TextStyle(&Theme.TextFont) .Font(this, &SFlareButton::GetTextStyle) .Text(InArgs._Text) .ColorAndOpacity(this, &SFlareButton::GetMainColor) ] ); if (Icon.IsSet() || IsToggle) { IconBox->AddSlot() .VAlign(VAlign_Center) [ SNew(SImage) .Image(this, &SFlareButton::GetIconBrush) ]; } } else { InnerContainer->SetHAlign(HAlign_Fill); InnerContainer->SetVAlign(VAlign_Fill); } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareButton::SetActive(bool State) { IsPressed = State; } bool SFlareButton::IsActive() const { return IsPressed; } void SFlareButton::SetDisabled(bool State) { IsDisabled.Set(State); } void SFlareButton::SetText(FText NewText) { if (TextBlock.IsValid()) { Text.Set(NewText); TextBlock->SetText(Text); } } void SFlareButton::SetHelpText(FText NewText) { HelpText.Set(NewText); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareButton::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); InternalButton->SetButtonStyle(&FFlareStyleSet::Get().GetWidgetStyle<FButtonStyle>("Flare.ActiveCoreButton")); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->ShowTooltip(this, Text.Get(), HelpText.Get()); } } void SFlareButton::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); InternalButton->SetButtonStyle(&FFlareStyleSet::Get().GetWidgetStyle<FButtonStyle>("Flare.CoreButton")); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } const FSlateBrush* SFlareButton::GetDecoratorBrush() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (IsTransparent) { return &Theme.InvisibleBrush; } else if (WasDisabled) { return &Theme.ButtonDisabledDecorator; } else if (IsToggle) { return (IsPressed ? &Theme.ButtonActiveDecorator : &Theme.ButtonDecorator); } else if (IsPressed) { return &Theme.ButtonActiveDecorator; } else { return NULL; } } const FSlateBrush* SFlareButton::GetIconBrush() const { if (Icon.IsSet()) { return Icon.Get(); } else if (IsToggle) { if (IsSmallToggleIcons) { return (IsPressed ? FFlareStyleSet::GetIcon("OK_Small") : FFlareStyleSet::GetIcon("Disabled_Small")); } else { return (IsPressed ? FFlareStyleSet::GetIcon("OK") : FFlareStyleSet::GetIcon("Disabled")); } } else { return NULL; } } const FSlateBrush* SFlareButton::GetBackgroundBrush() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (WasDisabled) { return &Theme.ButtonDisabledBackground; } else if (IsTransparent) { return (IsHovered() ? &Theme.NearInvisibleBrush : &Theme.InvisibleBrush); } else { return (IsHovered() ? &Theme.ButtonActiveBackground : &Theme.ButtonBackground); } } FSlateColor SFlareButton::GetMainColor() const { return Color.Get(); } FSlateFontInfo SFlareButton::GetTextStyle() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); if (Text.IsSet() || Text.IsBound()) { float TextLength = Text.Get().ToString().Len(); float ButtonWidth = GetDesiredSize().X; if (TextLength > 0.09 * ButtonWidth || IsSmallToggleIcons) { return Theme.SmallFont.Font; } } return Theme.TextFont.Font; } FReply SFlareButton::OnButtonClicked() { bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (!WasDisabled && IsHovered()) { if (IsToggle) { IsPressed = !IsPressed; } if (OnClicked.IsBound() == true) { OnClicked.Execute(); } } return FReply::Handled(); } <commit_msg>Hide button tooltips when clicked to fix issues with self-disappearing buttons<commit_after> #include "../../Flare.h" #include "FlareButton.h" #include "../../Player/FlareMenuManager.h" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareButton::Construct(const FArguments& InArgs) { // Setup IsPressed = false; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Arguments Icon = InArgs._Icon; IsToggle = InArgs._Toggle; IsSmallToggleIcons = InArgs._SmallToggleIcons; IsTransparent = InArgs._Transparent; OnClicked = InArgs._OnClicked; Color = InArgs._Color; Text = InArgs._Text; HelpText = InArgs._HelpText; IsDisabled = InArgs._IsDisabled; Width = InArgs._Width * Theme.ButtonWidth; Height = InArgs._Height * Theme.ButtonHeight; // Structure ChildSlot .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ // Button (behaviour only, no display) SAssignNew(InternalButton, SButton) .OnClicked(this, &SFlareButton::OnButtonClicked) .ContentPadding(FMargin(0)) .ButtonStyle(FFlareStyleSet::Get(), "Flare.CoreButton") [ SNew(SVerticalBox) // Upper border + SVerticalBox::Slot() .AutoHeight() [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] // Main line + SVerticalBox::Slot() .AutoHeight() [ // Left border SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Fill) [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] // Main content box + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(Width) .HeightOverride(Height) .Padding(FMargin(0)) [ // Button background SNew(SBorder) .Padding(FMargin(0)) .BorderImage(this, &SFlareButton::GetBackgroundBrush) [ SNew(SHorizontalBox) // Toggle light + SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) .VAlign(VAlign_Fill) [ SNew(SImage) .Image(this, &SFlareButton::GetDecoratorBrush) ] // Content box and inner container + SHorizontalBox::Slot() [ SAssignNew(InnerContainer, SBorder) .HAlign(HAlign_Left) .VAlign(VAlign_Center) .BorderImage(new FSlateNoResource) ] ] ] ] // Right border + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Fill) [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] ] // Lower border + SVerticalBox::Slot() .AutoHeight() [ SNew(SImage).Image(&Theme.ButtonBorderBrush) ] ] ]; // Construct text content if we need to if (InArgs._Text.IsSet()) { TSharedPtr<SVerticalBox> IconBox; InnerContainer->SetPadding(IsTransparent ? FMargin(0) : Theme.ButtonPadding); InnerContainer->SetContent( SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() .Padding(FMargin(3, 0)) [ SAssignNew(IconBox, SVerticalBox) ] // Text + SHorizontalBox::Slot() .VAlign(VAlign_Center) [ SAssignNew(TextBlock, STextBlock) .TextStyle(&Theme.TextFont) .Font(this, &SFlareButton::GetTextStyle) .Text(InArgs._Text) .ColorAndOpacity(this, &SFlareButton::GetMainColor) ] ); if (Icon.IsSet() || IsToggle) { IconBox->AddSlot() .VAlign(VAlign_Center) [ SNew(SImage) .Image(this, &SFlareButton::GetIconBrush) ]; } } else { InnerContainer->SetHAlign(HAlign_Fill); InnerContainer->SetVAlign(VAlign_Fill); } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareButton::SetActive(bool State) { IsPressed = State; } bool SFlareButton::IsActive() const { return IsPressed; } void SFlareButton::SetDisabled(bool State) { IsDisabled.Set(State); } void SFlareButton::SetText(FText NewText) { if (TextBlock.IsValid()) { Text.Set(NewText); TextBlock->SetText(Text); } } void SFlareButton::SetHelpText(FText NewText) { HelpText.Set(NewText); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareButton::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); InternalButton->SetButtonStyle(&FFlareStyleSet::Get().GetWidgetStyle<FButtonStyle>("Flare.ActiveCoreButton")); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->ShowTooltip(this, Text.Get(), HelpText.Get()); } } void SFlareButton::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); InternalButton->SetButtonStyle(&FFlareStyleSet::Get().GetWidgetStyle<FButtonStyle>("Flare.CoreButton")); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } const FSlateBrush* SFlareButton::GetDecoratorBrush() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (IsTransparent) { return &Theme.InvisibleBrush; } else if (WasDisabled) { return &Theme.ButtonDisabledDecorator; } else if (IsToggle) { return (IsPressed ? &Theme.ButtonActiveDecorator : &Theme.ButtonDecorator); } else if (IsPressed) { return &Theme.ButtonActiveDecorator; } else { return NULL; } } const FSlateBrush* SFlareButton::GetIconBrush() const { if (Icon.IsSet()) { return Icon.Get(); } else if (IsToggle) { if (IsSmallToggleIcons) { return (IsPressed ? FFlareStyleSet::GetIcon("OK_Small") : FFlareStyleSet::GetIcon("Disabled_Small")); } else { return (IsPressed ? FFlareStyleSet::GetIcon("OK") : FFlareStyleSet::GetIcon("Disabled")); } } else { return NULL; } } const FSlateBrush* SFlareButton::GetBackgroundBrush() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (WasDisabled) { return &Theme.ButtonDisabledBackground; } else if (IsTransparent) { return (IsHovered() ? &Theme.NearInvisibleBrush : &Theme.InvisibleBrush); } else { return (IsHovered() ? &Theme.ButtonActiveBackground : &Theme.ButtonBackground); } } FSlateColor SFlareButton::GetMainColor() const { return Color.Get(); } FSlateFontInfo SFlareButton::GetTextStyle() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); if (Text.IsSet() || Text.IsBound()) { float TextLength = Text.Get().ToString().Len(); float ButtonWidth = GetDesiredSize().X; if (TextLength > 0.09 * ButtonWidth || IsSmallToggleIcons) { return Theme.SmallFont.Font; } } return Theme.TextFont.Font; } FReply SFlareButton::OnButtonClicked() { bool WasDisabled = (IsDisabled.IsBound() || IsDisabled.IsSet()) && IsDisabled.Get(); if (!WasDisabled && IsHovered()) { if (IsToggle) { IsPressed = !IsPressed; } AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } if (OnClicked.IsBound() == true) { OnClicked.Execute(); } } return FReply::Handled(); } <|endoftext|>
<commit_before>/* Copyright 2017-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "Mercurial.h" #include "ChildProcess.h" #include "Logging.h" #include "watchman.h" // Capability indicating support for the mercurial SCM W_CAP_REG("scm-hg") namespace watchman { using Options = ChildProcess::Options; Mercurial::infoCache::infoCache(std::string path) : dirStatePath(path) { memset(&dirstate, 0, sizeof(dirstate)); } w_string Mercurial::infoCache::lookupMergeBase(const std::string& commitId) { if (dotChanged()) { watchman::log( watchman::DBG, "Blowing mergeBases cache because dirstate changed\n"); mergeBases.clear(); return nullptr; } auto it = mergeBases.find(commitId); if (it != mergeBases.end()) { watchman::log(watchman::DBG, "mergeBases cache hit for ", commitId, "\n"); return it->second; } watchman::log(watchman::DBG, "mergeBases cache miss for ", commitId, "\n"); return nullptr; } bool Mercurial::infoCache::dotChanged() { struct stat st; bool result; if (stat(dirStatePath.c_str(), &st)) { memset(&st, 0, sizeof(st)); // Failed to stat, so assume that it changed watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") failed\n"); result = true; } else if ( st.st_size != dirstate.st_size || st.WATCHMAN_ST_TIMESPEC(m).tv_sec != dirstate.WATCHMAN_ST_TIMESPEC(m).tv_sec || st.WATCHMAN_ST_TIMESPEC(m).tv_nsec != dirstate.WATCHMAN_ST_TIMESPEC(m).tv_nsec) { watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") info differs\n"); result = true; } else { result = false; watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") info same\n"); } memcpy(&dirstate, &st, sizeof(st)); return result; } Mercurial::Mercurial(w_string_piece rootPath, w_string_piece scmRoot) : SCM(rootPath, scmRoot), cache_(infoCache(to<std::string>(getSCMRoot(), "/.hg/dirstate"))) {} w_string Mercurial::mergeBaseWith(w_string_piece commitId) const { std::string idString(commitId.data(), commitId.size()); { auto cache = cache_.wlock(); auto result = cache->lookupMergeBase(idString); if (result) { watchman::log( watchman::DBG, "Using cached mergeBase value of ", result, " for commitId ", commitId, " because dirstate file is unchanged\n"); return result; } } Options opt; // Ensure that the hgrc doesn't mess with the behavior // of the commands that we're runing. opt.environment().set("HGPLAIN", "1"); opt.pipeStdout(); opt.chdir(getRootPath()); auto revset = to<std::string>("ancestor(.,", commitId, ")"); ChildProcess proc( {"hg", "log", "-T", "{node}", "-r", revset}, std::move(opt)); proc.pipe(STDOUT_FILENO).read.clearNonBlock(); auto status = proc.wait(); if (status) { throw std::runtime_error(to<std::string>( "failed query for the merge base; command returned with status ", status)); } char buf[128]; auto len = read(proc.pipe(STDOUT_FILENO).read.fd(), buf, sizeof(buf)); if (len != 40) { throw std::runtime_error(to<std::string>( "expected merge base to be a 40 character string, got ", w_string_piece(buf, len))); } auto result = w_string(buf, len); { auto cache = cache_.wlock(); cache->mergeBases[idString] = result; } return result; } std::vector<w_string> Mercurial::getFilesChangedSinceMergeBaseWith( w_string_piece commitId) const { Options opt; // Ensure that the hgrc doesn't mess with the behavior // of the commands that we're runing. opt.environment().set("HGPLAIN", "1"); opt.pipeStdout(); opt.chdir(getRootPath()); auto revset = to<std::string>("ancestor(.,", commitId, ")"); ChildProcess proc( {"hg", "status", "-n", "--root-relative", "--rev", commitId}, std::move(opt)); proc.pipe(STDOUT_FILENO).read.clearNonBlock(); std::vector<w_string> res; std::string line; char buf[512]; while (true) { auto len = read(proc.pipe(STDOUT_FILENO).read.fd(), buf, sizeof(buf)); if (len == 0) { break; } if (len < 0) { throw std::system_error( errno, std::generic_category(), "error while reading from hg status pipe"); } auto shortRead = len < int(sizeof(buf)); line.append(buf, len); // Note: mercurial always ends the last line with a newline, // so we only need do line splitting here. size_t start = 0; for (size_t i = 0; i < line.size(); ++i) { if (line[i] == '\n') { len = i - start; if (len > 0) { res.emplace_back(&line[start], len); } start = i + 1; } } if (start > 0) { line.erase(0, start); } if (shortRead) { // A short read means that we got to the end of the pipe data break; } } w_check(line.empty(), "we should have consumed all the data"); auto status = proc.wait(); if (status) { throw std::runtime_error(to<std::string>( "failed query for the hg status; command returned with status ", status)); } return res; } } <commit_msg>fixup windows compilation<commit_after>/* Copyright 2017-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "Mercurial.h" #include "ChildProcess.h" #include "Logging.h" #include "watchman.h" // Capability indicating support for the mercurial SCM W_CAP_REG("scm-hg") namespace watchman { using Options = ChildProcess::Options; Mercurial::infoCache::infoCache(std::string path) : dirStatePath(path) { memset(&dirstate, 0, sizeof(dirstate)); } w_string Mercurial::infoCache::lookupMergeBase(const std::string& commitId) { if (dotChanged()) { watchman::log( watchman::DBG, "Blowing mergeBases cache because dirstate changed\n"); mergeBases.clear(); return nullptr; } auto it = mergeBases.find(commitId); if (it != mergeBases.end()) { watchman::log(watchman::DBG, "mergeBases cache hit for ", commitId, "\n"); return it->second; } watchman::log(watchman::DBG, "mergeBases cache miss for ", commitId, "\n"); return nullptr; } bool Mercurial::infoCache::dotChanged() { struct stat st; bool result; if (lstat(dirStatePath.c_str(), &st)) { memset(&st, 0, sizeof(st)); // Failed to stat, so assume that it changed watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") failed\n"); result = true; } else if ( st.st_size != dirstate.st_size || st.WATCHMAN_ST_TIMESPEC(m).tv_sec != dirstate.WATCHMAN_ST_TIMESPEC(m).tv_sec || st.WATCHMAN_ST_TIMESPEC(m).tv_nsec != dirstate.WATCHMAN_ST_TIMESPEC(m).tv_nsec) { watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") info differs\n"); result = true; } else { result = false; watchman::log( watchman::DBG, "mergeBases stat(", dirStatePath, ") info same\n"); } memcpy(&dirstate, &st, sizeof(st)); return result; } Mercurial::Mercurial(w_string_piece rootPath, w_string_piece scmRoot) : SCM(rootPath, scmRoot), cache_(infoCache(to<std::string>(getSCMRoot(), "/.hg/dirstate"))) {} w_string Mercurial::mergeBaseWith(w_string_piece commitId) const { std::string idString(commitId.data(), commitId.size()); { auto cache = cache_.wlock(); auto result = cache->lookupMergeBase(idString); if (result) { watchman::log( watchman::DBG, "Using cached mergeBase value of ", result, " for commitId ", commitId, " because dirstate file is unchanged\n"); return result; } } Options opt; // Ensure that the hgrc doesn't mess with the behavior // of the commands that we're runing. opt.environment().set("HGPLAIN", "1"); opt.pipeStdout(); opt.chdir(getRootPath()); auto revset = to<std::string>("ancestor(.,", commitId, ")"); ChildProcess proc( {"hg", "log", "-T", "{node}", "-r", revset}, std::move(opt)); proc.pipe(STDOUT_FILENO).read.clearNonBlock(); auto status = proc.wait(); if (status) { throw std::runtime_error(to<std::string>( "failed query for the merge base; command returned with status ", status)); } char buf[128]; auto len = read(proc.pipe(STDOUT_FILENO).read.fd(), buf, sizeof(buf)); if (len != 40) { throw std::runtime_error(to<std::string>( "expected merge base to be a 40 character string, got ", w_string_piece(buf, len))); } auto result = w_string(buf, len); { auto cache = cache_.wlock(); cache->mergeBases[idString] = result; } return result; } std::vector<w_string> Mercurial::getFilesChangedSinceMergeBaseWith( w_string_piece commitId) const { Options opt; // Ensure that the hgrc doesn't mess with the behavior // of the commands that we're runing. opt.environment().set("HGPLAIN", "1"); opt.pipeStdout(); opt.chdir(getRootPath()); auto revset = to<std::string>("ancestor(.,", commitId, ")"); ChildProcess proc( {"hg", "status", "-n", "--root-relative", "--rev", commitId}, std::move(opt)); proc.pipe(STDOUT_FILENO).read.clearNonBlock(); std::vector<w_string> res; std::string line; char buf[512]; while (true) { auto len = read(proc.pipe(STDOUT_FILENO).read.fd(), buf, sizeof(buf)); if (len == 0) { break; } if (len < 0) { throw std::system_error( errno, std::generic_category(), "error while reading from hg status pipe"); } auto shortRead = len < int(sizeof(buf)); line.append(buf, len); // Note: mercurial always ends the last line with a newline, // so we only need do line splitting here. size_t start = 0; for (size_t i = 0; i < line.size(); ++i) { if (line[i] == '\n') { len = i - start; if (len > 0) { res.emplace_back(&line[start], len); } start = i + 1; } } if (start > 0) { line.erase(0, start); } if (shortRead) { // A short read means that we got to the end of the pipe data break; } } w_check(line.empty(), "we should have consumed all the data"); auto status = proc.wait(); if (status) { throw std::runtime_error(to<std::string>( "failed query for the hg status; command returned with status ", status)); } return res; } } <|endoftext|>
<commit_before>// // DiskCopy42.cpp // Clock Signal // // Created by Thomas Harte on 02/06/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #include "MacintoshIMG.hpp" #include <cstring> #include "../../Track/PCMTrack.hpp" #include "../../Track/TrackSerialiser.hpp" #include "../../Encodings/AppleGCR/Encoder.hpp" #include "../../Encodings/AppleGCR/SegmentParser.hpp" /* File format specifications as referenced below are largely sourced from the documentation at https://wiki.68kmla.org/DiskCopy_4.2_format_specification */ using namespace Storage::Disk; MacintoshIMG::MacintoshIMG(const std::string &file_name) : file_(file_name) { // Test 1: is this a raw secctor dump? If so it'll start with // the magic word 0x4C4B (big endian) and be exactly // 819,200 bytes long if double sided, or 409,600 bytes if // single sided. // // Luckily, 0x4c is an invalid string length for the proper // DiskCopy 4.2 format, so there's no ambiguity here. const auto name_length = file_.get8(); if(name_length == 0x4c) { is_diskCopy_file_ = false; if(file_.stats().st_size != 819200 && file_.stats().st_size != 409600) throw Error::InvalidFormat; uint32_t magic_word = file_.get8(); if(magic_word != 0x4b) throw Error::InvalidFormat; file_.seek(0, SEEK_SET); if(file_.stats().st_size == 819200) { encoding_ = Encoding::GCR800; format_ = 0x22; data_ = file_.read(819200); } else { encoding_ = Encoding::GCR400; format_ = 0x02; data_ = file_.read(409600); } } else { // DiskCopy 4.2 it is then: // // File format starts with 64 bytes dedicated to the disk name; // this is a Pascal-style string though there is apparently a // bug in one version of Disk Copy that can cause the length to // be one too high. // // Validate the length, then skip the rest of the string. is_diskCopy_file_ = true; if(name_length > 64) throw Error::InvalidFormat; // Get the length of the data and tag blocks. file_.seek(64, SEEK_SET); const auto data_block_length = file_.get32be(); const auto tag_block_length = file_.get32be(); const auto data_checksum = file_.get32be(); const auto tag_checksum = file_.get32be(); // Don't continue with no data. if(!data_block_length) throw Error::InvalidFormat; // Check that this is a comprehensible disk encoding. const auto encoding = file_.get8(); switch(encoding) { default: throw Error::InvalidFormat; case 0: encoding_ = Encoding::GCR400; break; case 1: encoding_ = Encoding::GCR800; break; case 2: encoding_ = Encoding::MFM720; break; case 3: encoding_ = Encoding::MFM1440; break; } format_ = file_.get8(); // Check the magic number. const auto magic_number = file_.get16be(); if(magic_number != 0x0100) throw Error::InvalidFormat; // Read the data and tags, and verify that enough data // was present. data_ = file_.read(data_block_length); tags_ = file_.read(tag_block_length); if(data_.size() != data_block_length || tags_.size() != tag_block_length) throw Error::InvalidFormat; // Verify the two checksums. const auto computed_data_checksum = checksum(data_); const auto computed_tag_checksum = checksum(tags_, 12); if(computed_tag_checksum != tag_checksum || computed_data_checksum != data_checksum) throw Error::InvalidFormat; } } uint32_t MacintoshIMG::checksum(const std::vector<uint8_t> &data, size_t bytes_to_skip) { uint32_t result = 0; // Checksum algorith is: take each two bytes as a big-endian word; add that to a // 32-bit accumulator and then rotate the accumulator right one position. for(size_t c = bytes_to_skip; c < data.size(); c += 2) { const uint16_t next_word = uint16_t((data[c] << 8) | data[c+1]); result += next_word; result = (result >> 1) | (result << 31); } return result; } HeadPosition MacintoshIMG::get_maximum_head_position() { return HeadPosition(80); } int MacintoshIMG::get_head_count() { // Bit 5 in the format field indicates whether this disk is double // sided, regardless of whether it is GCR or MFM. return 1 + ((format_ & 0x20) >> 5); } bool MacintoshIMG::get_is_read_only() { return file_.get_is_known_read_only(); } std::shared_ptr<::Storage::Disk::Track> MacintoshIMG::get_track_at_position(::Storage::Disk::Track::Address address) { /* The format_ byte has the following meanings: GCR: This byte appears on disk as the GCR format nibble in every sector tag. The low five bits are an interleave factor, either: '2' for 0 8 1 9 2 10 3 11 4 12 5 13 6 14 7 15; or '4' for 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15. Bit 5 indicates double sided or not. MFM: The low five bits provide sector size as a multiple of 256 bytes. Bit 5 indicates double sided or not. */ std::lock_guard<decltype(buffer_mutex_)> buffer_lock(buffer_mutex_); if(encoding_ == Encoding::GCR400 || encoding_ == Encoding::GCR800) { // Perform a GCR encoding. const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(address.position.as_int()); const size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * address.head); if(start_sector*512 >= data_.size()) return nullptr; uint8_t *sector = &data_[512 * start_sector]; uint8_t *tags = tags_.size() ? &tags_[12 * start_sector] : nullptr; Storage::Disk::PCMSegment segment; segment += Encodings::AppleGCR::six_and_two_sync(24); for(int c = 0; c < included_sectors.length; ++c) { // const int interleave_scale = ((format_ & 0x1f) == 4) ? 8 : 4; uint8_t sector_id = uint8_t(c);//uint8_t((c == included_sectors.length - 1) ? c : (c * interleave_scale)%included_sectors.length); uint8_t sector_plus_tags[524]; // Copy in the tags, if provided; otherwise generate them. if(tags) { memcpy(sector_plus_tags, tags, 12); tags += 12; } else { // TODO: fill in tags properly. memset(sector_plus_tags, 0, 12); } // Copy in the sector body. memcpy(&sector_plus_tags[12], sector, 512); sector += 512; // NB: sync lengths below are identical to those for // the Apple II, as I have no idea whatsoever what they // should be. segment += Encodings::AppleGCR::Macintosh::header( format_, uint8_t(address.position.as_int()), sector_id, !!address.head ); segment += Encodings::AppleGCR::six_and_two_sync(7); segment += Encodings::AppleGCR::Macintosh::data(sector_id, sector_plus_tags); segment += Encodings::AppleGCR::six_and_two_sync(20); } // TODO: is there inter-track skew? return std::make_shared<PCMTrack>(segment); } return nullptr; } void MacintoshIMG::set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &tracks) { std::map<Track::Address, std::vector<uint8_t>> tracks_by_address; for(const auto &pair: tracks) { // Determine a data rate for the track. const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(pair.first.position.as_int()); // Rule of thumb here: there are about 6250 bits per sector. const int data_rate = included_sectors.length * 6250; // Decode the track. auto sector_map = Storage::Encodings::AppleGCR::sectors_from_segment( Storage::Disk::track_serialisation(*pair.second, Storage::Time(1, data_rate))); // Rearrange sectors into ascending order. std::vector<uint8_t> track_contents(static_cast<size_t>(524 * included_sectors.length)); for(const auto &sector_pair: sector_map) { const size_t target_address = sector_pair.second.address.sector * 524; if(target_address >= track_contents.size() || sector_pair.second.data.size() != 524) continue; memcpy(&track_contents[target_address], sector_pair.second.data.data(), 524); } // Store for later. tracks_by_address[pair.first] = std::move(track_contents); } // Grab the buffer mutex and update the in-memory buffer. { std::lock_guard<decltype(buffer_mutex_)> buffer_lock(buffer_mutex_); for(const auto &pair: tracks_by_address) { const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(pair.first.position.as_int()); size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * pair.first.head); for(int c = 0; c < included_sectors.length; ++c) { memcpy(&data_[start_sector * 512], &pair.second[size_t(c)*524 + 12], 512); // TODO: the below strongly implies I should keep tags in memory even if I don't write // them out to the file? if(tags_.size()) { memcpy(&data_[start_sector * 12], pair.second.data(), 12); } ++start_sector; } } } // Grab the file lock and write out the new tracks. { std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex()); if(!is_diskCopy_file_) { // Just dump out the new sectors. Grossly lazy, possibly worth improving. file_.seek(0, SEEK_SET); file_.write(data_); } else { // Write out the sectors, and possibly the tags, and update checksums. file_.seek(0x54, SEEK_SET); file_.write(data_); file_.write(tags_); const auto data_checksum = checksum(data_); const auto tag_checksum = checksum(tags_, 12); file_.seek(0x48, SEEK_SET); file_.put_be(data_checksum); file_.put_be(tag_checksum); } } } <commit_msg>Corrects tag preservation.<commit_after>// // DiskCopy42.cpp // Clock Signal // // Created by Thomas Harte on 02/06/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #include "MacintoshIMG.hpp" #include <cstring> #include "../../Track/PCMTrack.hpp" #include "../../Track/TrackSerialiser.hpp" #include "../../Encodings/AppleGCR/Encoder.hpp" #include "../../Encodings/AppleGCR/SegmentParser.hpp" /* File format specifications as referenced below are largely sourced from the documentation at https://wiki.68kmla.org/DiskCopy_4.2_format_specification */ using namespace Storage::Disk; MacintoshIMG::MacintoshIMG(const std::string &file_name) : file_(file_name) { // Test 1: is this a raw secctor dump? If so it'll start with // the magic word 0x4C4B (big endian) and be exactly // 819,200 bytes long if double sided, or 409,600 bytes if // single sided. // // Luckily, 0x4c is an invalid string length for the proper // DiskCopy 4.2 format, so there's no ambiguity here. const auto name_length = file_.get8(); if(name_length == 0x4c) { is_diskCopy_file_ = false; if(file_.stats().st_size != 819200 && file_.stats().st_size != 409600) throw Error::InvalidFormat; uint32_t magic_word = file_.get8(); if(magic_word != 0x4b) throw Error::InvalidFormat; file_.seek(0, SEEK_SET); if(file_.stats().st_size == 819200) { encoding_ = Encoding::GCR800; format_ = 0x22; data_ = file_.read(819200); } else { encoding_ = Encoding::GCR400; format_ = 0x02; data_ = file_.read(409600); } } else { // DiskCopy 4.2 it is then: // // File format starts with 64 bytes dedicated to the disk name; // this is a Pascal-style string though there is apparently a // bug in one version of Disk Copy that can cause the length to // be one too high. // // Validate the length, then skip the rest of the string. is_diskCopy_file_ = true; if(name_length > 64) throw Error::InvalidFormat; // Get the length of the data and tag blocks. file_.seek(64, SEEK_SET); const auto data_block_length = file_.get32be(); const auto tag_block_length = file_.get32be(); const auto data_checksum = file_.get32be(); const auto tag_checksum = file_.get32be(); // Don't continue with no data. if(!data_block_length) throw Error::InvalidFormat; // Check that this is a comprehensible disk encoding. const auto encoding = file_.get8(); switch(encoding) { default: throw Error::InvalidFormat; case 0: encoding_ = Encoding::GCR400; break; case 1: encoding_ = Encoding::GCR800; break; case 2: encoding_ = Encoding::MFM720; break; case 3: encoding_ = Encoding::MFM1440; break; } format_ = file_.get8(); // Check the magic number. const auto magic_number = file_.get16be(); if(magic_number != 0x0100) throw Error::InvalidFormat; // Read the data and tags, and verify that enough data // was present. data_ = file_.read(data_block_length); tags_ = file_.read(tag_block_length); if(data_.size() != data_block_length || tags_.size() != tag_block_length) throw Error::InvalidFormat; // Verify the two checksums. const auto computed_data_checksum = checksum(data_); const auto computed_tag_checksum = checksum(tags_, 12); if(computed_tag_checksum != tag_checksum || computed_data_checksum != data_checksum) throw Error::InvalidFormat; } } uint32_t MacintoshIMG::checksum(const std::vector<uint8_t> &data, size_t bytes_to_skip) { uint32_t result = 0; // Checksum algorith is: take each two bytes as a big-endian word; add that to a // 32-bit accumulator and then rotate the accumulator right one position. for(size_t c = bytes_to_skip; c < data.size(); c += 2) { const uint16_t next_word = uint16_t((data[c] << 8) | data[c+1]); result += next_word; result = (result >> 1) | (result << 31); } return result; } HeadPosition MacintoshIMG::get_maximum_head_position() { return HeadPosition(80); } int MacintoshIMG::get_head_count() { // Bit 5 in the format field indicates whether this disk is double // sided, regardless of whether it is GCR or MFM. return 1 + ((format_ & 0x20) >> 5); } bool MacintoshIMG::get_is_read_only() { return file_.get_is_known_read_only(); } std::shared_ptr<::Storage::Disk::Track> MacintoshIMG::get_track_at_position(::Storage::Disk::Track::Address address) { /* The format_ byte has the following meanings: GCR: This byte appears on disk as the GCR format nibble in every sector tag. The low five bits are an interleave factor, either: '2' for 0 8 1 9 2 10 3 11 4 12 5 13 6 14 7 15; or '4' for 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15. Bit 5 indicates double sided or not. MFM: The low five bits provide sector size as a multiple of 256 bytes. Bit 5 indicates double sided or not. */ std::lock_guard<decltype(buffer_mutex_)> buffer_lock(buffer_mutex_); if(encoding_ == Encoding::GCR400 || encoding_ == Encoding::GCR800) { // Perform a GCR encoding. const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(address.position.as_int()); const size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * address.head); if(start_sector*512 >= data_.size()) return nullptr; uint8_t *sector = &data_[512 * start_sector]; uint8_t *tags = tags_.size() ? &tags_[12 * start_sector] : nullptr; Storage::Disk::PCMSegment segment; segment += Encodings::AppleGCR::six_and_two_sync(24); for(int c = 0; c < included_sectors.length; ++c) { // const int interleave_scale = ((format_ & 0x1f) == 4) ? 8 : 4; uint8_t sector_id = uint8_t(c);//uint8_t((c == included_sectors.length - 1) ? c : (c * interleave_scale)%included_sectors.length); uint8_t sector_plus_tags[524]; // Copy in the tags, if provided; otherwise generate them. if(tags) { memcpy(sector_plus_tags, tags, 12); tags += 12; } else { // TODO: fill in tags properly. memset(sector_plus_tags, 0, 12); } // Copy in the sector body. memcpy(&sector_plus_tags[12], sector, 512); sector += 512; // NB: sync lengths below are identical to those for // the Apple II, as I have no idea whatsoever what they // should be. segment += Encodings::AppleGCR::Macintosh::header( format_, uint8_t(address.position.as_int()), sector_id, !!address.head ); segment += Encodings::AppleGCR::six_and_two_sync(7); segment += Encodings::AppleGCR::Macintosh::data(sector_id, sector_plus_tags); segment += Encodings::AppleGCR::six_and_two_sync(20); } // TODO: is there inter-track skew? return std::make_shared<PCMTrack>(segment); } return nullptr; } void MacintoshIMG::set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &tracks) { std::map<Track::Address, std::vector<uint8_t>> tracks_by_address; for(const auto &pair: tracks) { // Determine a data rate for the track. const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(pair.first.position.as_int()); // Rule of thumb here: there are about 6250 bits per sector. const int data_rate = included_sectors.length * 6250; // Decode the track. auto sector_map = Storage::Encodings::AppleGCR::sectors_from_segment( Storage::Disk::track_serialisation(*pair.second, Storage::Time(1, data_rate))); // Rearrange sectors into ascending order. std::vector<uint8_t> track_contents(static_cast<size_t>(524 * included_sectors.length)); for(const auto &sector_pair: sector_map) { const size_t target_address = sector_pair.second.address.sector * 524; if(target_address >= track_contents.size() || sector_pair.second.data.size() != 524) continue; memcpy(&track_contents[target_address], sector_pair.second.data.data(), 524); } // Store for later. tracks_by_address[pair.first] = std::move(track_contents); } // Grab the buffer mutex and update the in-memory buffer. { std::lock_guard<decltype(buffer_mutex_)> buffer_lock(buffer_mutex_); for(const auto &pair: tracks_by_address) { const auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(pair.first.position.as_int()); size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * pair.first.head); for(int c = 0; c < included_sectors.length; ++c) { const auto sector_plus_tags = &pair.second[size_t(c)*524]; // Copy the 512 bytes that constitute the sector body. memcpy(&data_[start_sector * 512], &sector_plus_tags[12], 512); // Copy the tags if this file can store them. // TODO: add tags to a DiskCopy-format image that doesn't have them, if they contain novel content? if(tags_.size()) { memcpy(&tags_[start_sector * 12], sector_plus_tags, 12); } ++start_sector; } } } // Grab the file lock and write out the new tracks. { std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex()); if(!is_diskCopy_file_) { // Just dump out the new sectors. Grossly lazy, possibly worth improving. file_.seek(0, SEEK_SET); file_.write(data_); } else { // Write out the sectors, and possibly the tags, and update checksums. file_.seek(0x54, SEEK_SET); file_.write(data_); file_.write(tags_); const auto data_checksum = checksum(data_); const auto tag_checksum = checksum(tags_, 12); file_.seek(0x48, SEEK_SET); file_.put_be(data_checksum); file_.put_be(tag_checksum); } } } <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB 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 */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static void read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ void init_errmessage(void) { DBUG_ENTER("init_errmessage"); read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_VOID_RETURN; } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static void read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("No character set information in '%s'. \ You probably haven't reinstalled the latest file version.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_VOID_RETURN; err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <commit_msg>derror.cc: Better English message<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB 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 */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static void read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ void init_errmessage(void) { DBUG_ENTER("init_errmessage"); read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_VOID_RETURN; } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static void read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("Character set information in not found in '%s'. \ Please install the latest version of this file.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_VOID_RETURN; err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <|endoftext|>
<commit_before>/******************************************************************************\ Copyright (c) 2005-2018, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "mfx_samples_config.h" #include "plugin_utils.h" #include "mfxvp8.h" #include <sstream> #include <map> bool AreGuidsEqual(const mfxPluginUID& guid1, const mfxPluginUID& guid2) { for(size_t i = 0; i != sizeof(mfxPluginUID); i++) { if (guid1.Data[i] != guid2.Data[i]) return false; } return true; } mfxStatus ConvertStringToGuid(const msdk_string & strGuid, mfxPluginUID & mfxGuid) { mfxStatus sts = MFX_ERR_NONE; // Check if symbolic GUID value std::map<msdk_string, mfxPluginUID> uid; uid[MSDK_STRING("hevcd_sw")] = MFX_PLUGINID_HEVCD_SW; uid[MSDK_STRING("hevcd_hw")] = MFX_PLUGINID_HEVCD_HW; uid[MSDK_STRING("hevce_sw")] = MFX_PLUGINID_HEVCE_SW; uid[MSDK_STRING("hevce_gacc")] = MFX_PLUGINID_HEVCE_GACC; uid[MSDK_STRING("hevce_hw")] = MFX_PLUGINID_HEVCE_HW; uid[MSDK_STRING("vp8d_hw")] = MFX_PLUGINID_VP8D_HW; uid[MSDK_STRING("vp8e_hw")] = MFX_PLUGINID_VP8E_HW; uid[MSDK_STRING("vp9d_hw")] = MFX_PLUGINID_VP9D_HW; uid[MSDK_STRING("vp9e_hw")] = MFX_PLUGINID_VP9E_HW; uid[MSDK_STRING("camera_hw")] = MFX_PLUGINID_CAMERA_HW; uid[MSDK_STRING("capture_hw")] = MFX_PLUGINID_CAPTURE_HW; uid[MSDK_STRING("ptir_hw")] = MFX_PLUGINID_ITELECINE_HW; uid[MSDK_STRING("h264_la_hw")] = MFX_PLUGINID_H264LA_HW; uid[MSDK_STRING("aacd")] = MFX_PLUGINID_AACD; uid[MSDK_STRING("aace")] = MFX_PLUGINID_AACE; uid[MSDK_STRING("hevce_fei_hw")] = MFX_PLUGINID_HEVCE_FEI_HW; if (uid.find(strGuid) == uid.end()) { mfxGuid = MSDK_PLUGINGUID_NULL; sts = MFX_ERR_UNKNOWN; } else { mfxGuid = uid[strGuid]; sts = MFX_ERR_NONE; } // Check if plain GUID value if (sts) { if (strGuid.size() != 32) { sts = MFX_ERR_UNKNOWN; } else { for (size_t i = 0; i < 16; i++) { unsigned int xx = 0; msdk_stringstream ss; ss << std::hex << strGuid.substr(i * 2, 2); ss >> xx; mfxGuid.Data[i] = (mfxU8)xx; } sts = MFX_ERR_NONE; } } return sts; } const mfxPluginUID & msdkGetPluginUID(mfxIMPL impl, msdkComponentType type, mfxU32 uCodecid) { if (impl == MFX_IMPL_SOFTWARE) { switch(type) { case MSDK_VDECODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCD_SW; } break; case MSDK_VENCODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_SW; } break; } } else if (impl |= MFX_IMPL_HARDWARE) { switch(type) { // On Android implementaion of all decoders is placed in libmfx // That's why we don't need default plugins for these codecs #if !defined(ANDROID) case MSDK_VDECODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCD_HW; case MFX_CODEC_VP8: return MFX_PLUGINID_VP8D_HW; case MFX_CODEC_VP9: return MFX_PLUGINID_VP9D_HW; } break; #endif case MSDK_VENCODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_HW; case MFX_CODEC_VP8: return MFX_PLUGINID_VP8E_HW; } break; #if MFX_VERSION >= 1027 case (MSDK_VENCODE | MSDK_FEI): switch (uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVC_FEI_ENCODE; } break; #endif case MSDK_VENC: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_FEI_HW; // HEVC FEI uses ENC interface } break; } } return MSDK_PLUGINGUID_NULL; } sPluginParams ParsePluginGuid(msdk_char* strPluginGuid) { sPluginParams pluginParams; mfxPluginUID uid; mfxStatus sts = ConvertStringToGuid(strPluginGuid, uid); if (sts == MFX_ERR_NONE) { pluginParams.type = MFX_PLUGINLOAD_TYPE_GUID; pluginParams.pluginGuid = uid; } return pluginParams; } sPluginParams ParsePluginPath(msdk_char* strPluginGuid) { sPluginParams pluginParams; msdk_char tmpVal[MSDK_MAX_FILENAME_LEN]; msdk_opt_read(strPluginGuid, tmpVal); MSDK_MAKE_BYTE_STRING(tmpVal, pluginParams.strPluginPath); pluginParams.type = MFX_PLUGINLOAD_TYPE_FILE; return pluginParams; } <commit_msg>clang: fixes warning<commit_after>/******************************************************************************\ Copyright (c) 2005-2018, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "mfx_samples_config.h" #include "plugin_utils.h" #include "mfxvp8.h" #include <sstream> #include <map> bool AreGuidsEqual(const mfxPluginUID& guid1, const mfxPluginUID& guid2) { for(size_t i = 0; i != sizeof(mfxPluginUID); i++) { if (guid1.Data[i] != guid2.Data[i]) return false; } return true; } mfxStatus ConvertStringToGuid(const msdk_string & strGuid, mfxPluginUID & mfxGuid) { mfxStatus sts = MFX_ERR_NONE; // Check if symbolic GUID value std::map<msdk_string, mfxPluginUID> uid; uid[MSDK_STRING("hevcd_sw")] = MFX_PLUGINID_HEVCD_SW; uid[MSDK_STRING("hevcd_hw")] = MFX_PLUGINID_HEVCD_HW; uid[MSDK_STRING("hevce_sw")] = MFX_PLUGINID_HEVCE_SW; uid[MSDK_STRING("hevce_gacc")] = MFX_PLUGINID_HEVCE_GACC; uid[MSDK_STRING("hevce_hw")] = MFX_PLUGINID_HEVCE_HW; uid[MSDK_STRING("vp8d_hw")] = MFX_PLUGINID_VP8D_HW; uid[MSDK_STRING("vp8e_hw")] = MFX_PLUGINID_VP8E_HW; uid[MSDK_STRING("vp9d_hw")] = MFX_PLUGINID_VP9D_HW; uid[MSDK_STRING("vp9e_hw")] = MFX_PLUGINID_VP9E_HW; uid[MSDK_STRING("camera_hw")] = MFX_PLUGINID_CAMERA_HW; uid[MSDK_STRING("capture_hw")] = MFX_PLUGINID_CAPTURE_HW; uid[MSDK_STRING("ptir_hw")] = MFX_PLUGINID_ITELECINE_HW; uid[MSDK_STRING("h264_la_hw")] = MFX_PLUGINID_H264LA_HW; uid[MSDK_STRING("aacd")] = MFX_PLUGINID_AACD; uid[MSDK_STRING("aace")] = MFX_PLUGINID_AACE; uid[MSDK_STRING("hevce_fei_hw")] = MFX_PLUGINID_HEVCE_FEI_HW; if (uid.find(strGuid) == uid.end()) { mfxGuid = MSDK_PLUGINGUID_NULL; sts = MFX_ERR_UNKNOWN; } else { mfxGuid = uid[strGuid]; sts = MFX_ERR_NONE; } // Check if plain GUID value if (sts) { if (strGuid.size() != 32) { sts = MFX_ERR_UNKNOWN; } else { for (size_t i = 0; i < 16; i++) { unsigned int xx = 0; msdk_stringstream ss; ss << std::hex << strGuid.substr(i * 2, 2); ss >> xx; mfxGuid.Data[i] = (mfxU8)xx; } sts = MFX_ERR_NONE; } } return sts; } const mfxPluginUID & msdkGetPluginUID(mfxIMPL impl, msdkComponentType type, mfxU32 uCodecid) { if (impl == MFX_IMPL_SOFTWARE) { switch(type) { case MSDK_VDECODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCD_SW; } break; case MSDK_VENCODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_SW; } break; } } else { switch(type) { // On Android implementaion of all decoders is placed in libmfx // That's why we don't need default plugins for these codecs #if !defined(ANDROID) case MSDK_VDECODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCD_HW; case MFX_CODEC_VP8: return MFX_PLUGINID_VP8D_HW; case MFX_CODEC_VP9: return MFX_PLUGINID_VP9D_HW; } break; #endif case MSDK_VENCODE: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_HW; case MFX_CODEC_VP8: return MFX_PLUGINID_VP8E_HW; } break; #if MFX_VERSION >= 1027 case (MSDK_VENCODE | MSDK_FEI): switch (uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVC_FEI_ENCODE; } break; #endif case MSDK_VENC: switch(uCodecid) { case MFX_CODEC_HEVC: return MFX_PLUGINID_HEVCE_FEI_HW; // HEVC FEI uses ENC interface } break; } } return MSDK_PLUGINGUID_NULL; } sPluginParams ParsePluginGuid(msdk_char* strPluginGuid) { sPluginParams pluginParams; mfxPluginUID uid; mfxStatus sts = ConvertStringToGuid(strPluginGuid, uid); if (sts == MFX_ERR_NONE) { pluginParams.type = MFX_PLUGINLOAD_TYPE_GUID; pluginParams.pluginGuid = uid; } return pluginParams; } sPluginParams ParsePluginPath(msdk_char* strPluginGuid) { sPluginParams pluginParams; msdk_char tmpVal[MSDK_MAX_FILENAME_LEN]; msdk_opt_read(strPluginGuid, tmpVal); MSDK_MAKE_BYTE_STRING(tmpVal, pluginParams.strPluginPath); pluginParams.type = MFX_PLUGINLOAD_TYPE_FILE; return pluginParams; } <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_DEVICE_HPP #define MFEM_DEVICE_HPP #include "globals.hpp" namespace mfem { /// MFEM backends. /** Individual backends will generally implement only a subset of the kernels implemented by the default CPU backend. */ struct Backend { /** @brief In the documentation below, we use square brackets to indicate the type of the backend: host or device. */ enum Id { /// [host] Default CPU backend: sequential execution on each MPI rank. CPU = 1 << 0, /// [host] OpenMP backend. Enabled when MFEM_USE_OPENMP = YES. OMP = 1 << 1, /// [device] CUDA backend. Enabled when MFEM_USE_CUDA = YES. CUDA = 1 << 2, /** @brief [host] RAJA CPU backend: sequential execution on each MPI rank. Enabled when MFEM_USE_RAJA = YES. */ RAJA_CPU = 1 << 3, /** @brief [host] RAJA OpenMP backend. Enabled when MFEM_USE_RAJA = YES and MFEM_USE_OPENMP = YES. */ RAJA_OMP = 1 << 4, /** @brief [device] RAJA CUDA backend. Enabled when MFEM_USE_RAJA = YES and MFEM_USE_CUDA = YES. */ RAJA_CUDA = 1 << 5, /** @brief [host] OCCA CPU backend: sequential execution on each MPI rank. Enabled when MFEM_USE_OCCA = YES. */ OCCA_CPU = 1 << 6, /// [host] OCCA OpenMP backend. Enabled when MFEM_USE_OCCA = YES. OCCA_OMP = 1 << 7, /** @brief [device] OCCA CUDA backend. Enabled when MFEM_USE_OCCA = YES and MFEM_USE_CUDA = YES. */ OCCA_CUDA = 1 << 8 }; /** @brief Additional useful constants. For example, the *_MASK constants can be used with Device::Allows(). */ enum { /// Number of backends: from (1 << 0) to (1 << (NUM_BACKENDS-1)). NUM_BACKENDS = 9, /// Biwise-OR of all CUDA backends CUDA_MASK = CUDA | RAJA_CUDA | OCCA_CUDA, /// Biwise-OR of all RAJA backends RAJA_MASK = RAJA_CPU | RAJA_OMP | RAJA_CUDA, /// Biwise-OR of all OCCA backends OCCA_MASK = OCCA_CPU | OCCA_OMP | OCCA_CUDA, /// Biwise-OR of all OpenMP backends OMP_MASK = OMP | RAJA_OMP | OCCA_OMP, /// Biwise-OR of all device backends DEVICE_MASK = CUDA_MASK }; }; /** @brief The MFEM Device class that abstracts hardware devices, such as GPUs, and programming models, such as CUDA, OCCA, RAJA and OpenMP. */ /** This class represents a "virtual device" with the following properties: - There a single object of this class which is controlled by its static methods. - Once configured, the object cannot be re-configured during the program lifetime. - MFEM classes use this object to determine where (host or device) to perform an operation and which backend implementation to use. - Multiple backends can be configured at the same time; currently, a fixed priority order is used to select a specific backend from the list of configured backends. See the Backend class and the Configure() method in this class for details. - The device can be disabled to restrict the backend selection to only host backends, see the methods Enable() and Disable(). */ class Device { private: enum MODES {HOST, DEVICE}; MODES mode; int dev = 0; ///< Device ID of the configured device. int ngpu = -1; ///< Number of detected devices; -1: not initialized. unsigned long backends; ///< Bitwise-OR of all configured backends. /** Bitwise-OR mask of all allowed backends. Active backends are all backends minus any device backends when the Device is disabled. */ unsigned long allowed_backends; Device() : mode(Device::HOST), backends(Backend::CPU), allowed_backends(backends) { } Device(Device const&); void operator=(Device const&); static Device& Get() { static Device singleton; return singleton; } /// Setup switcher based on configuration settings void Setup(const int dev = 0); void MarkBackend(Backend::Id b) { backends |= b; } public: /// Configure the Device backends. /** The string parameter @a device must be a comma-separated list of backend string names (see below). The @a dev argument specifies the ID of the actual devices (e.g. GPU) to use. * The available backends are described by the Backend class. * The string name of a backend is the lowercase version of the Backend::Id enumeration constant with '_' replaced by '-', e.g. the string name of 'RAJA_CPU' is 'raja-cpu'. * The 'cpu' backend is always enabled with lowest priority. * The current backend priority from highest to lowest is: 'occa-cuda', 'raja-cuda', 'cuda', 'occa-omp', 'raja-omp', 'omp', 'occa-cpu', 'raja-cpu', 'cpu'. * Multiple backends can be configured at the same time. * Only one 'occa-*' backend can be configured at a time. * The backend 'occa-cuda' enables the 'cuda' backend unless 'raja-cuda' is already enabled. * After this call, the Device will be disabled. */ static void Configure(const std::string &device, const int dev = 0); /// Print the configuration of the MFEM virtual device object. static void Print(std::ostream &out = mfem::out); /// Return true if Configure() has been called previously. static inline bool IsConfigured() { return Get().ngpu >= 0; } /// Return true if an actual device (e.g. GPU) has been configured. static inline bool IsAvailable() { return Get().ngpu > 0; } /// Enable the use of the configured device in the code that follows. /** After this call MFEM classes will use device kernels whenever possible, transferring data automatically to the device, if necessary. If an actual device (e.g. GPU) is not configured, this is a no-op, and the Device will remain disabled. */ static inline void Enable() { if (IsAvailable()) { Get().mode = Device::DEVICE; Get().allowed_backends = Get().backends; } } /// Disable the use of the configured device in the code that follows. /** After this call MFEM classes will only use host kernels, transferring data automatically from the device, if necessary. */ static inline void Disable() { Get().mode = Device::HOST; Get().allowed_backends = Get().backends & ~Backend::DEVICE_MASK; } /// Return true if the Device is enabled. static inline bool IsEnabled() { return Get().mode == DEVICE; } /// The opposite of IsEnabled(). static inline bool IsDisabled() { return !IsEnabled(); } /** @brief Return true if any of the backends in the backend mask, @a b_mask, are allowed. The allowed backends are all configured backends minus the device backends when the Device is disabled. */ /** This method can be used with any of the Backend::Id constants, the Backend::*_MASK, or combinations of those. */ static inline bool Allows(unsigned long b_mask) { return Get().allowed_backends & b_mask; } /// Enable the memory manager static void EnableMemoryManager(); /// Disable the memory manager static void DisableMemoryManager(); /// Return true if the memory manager is enabled static bool IsMemoryManagerEnabled(); ~Device(); }; } // mfem #endif // MFEM_DEVICE_HPP <commit_msg>Device::Disable switches to the CPU backend<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_DEVICE_HPP #define MFEM_DEVICE_HPP #include "globals.hpp" namespace mfem { /// MFEM backends. /** Individual backends will generally implement only a subset of the kernels implemented by the default CPU backend. The goal of the backends is to accelerate data-parallel portions of the code and they can use a device memory space (e.g. GPUs) or share the memory space of the host (OpenMP). */ struct Backend { /** @brief In the documentation below, we use square brackets to indicate the type of the backend: host or device. */ enum Id { /// [host] Default CPU backend: sequential execution on each MPI rank. CPU = 1 << 0, /// [host] OpenMP backend. Enabled when MFEM_USE_OPENMP = YES. OMP = 1 << 1, /// [device] CUDA backend. Enabled when MFEM_USE_CUDA = YES. CUDA = 1 << 2, /** @brief [host] RAJA CPU backend: sequential execution on each MPI rank. Enabled when MFEM_USE_RAJA = YES. */ RAJA_CPU = 1 << 3, /** @brief [host] RAJA OpenMP backend. Enabled when MFEM_USE_RAJA = YES and MFEM_USE_OPENMP = YES. */ RAJA_OMP = 1 << 4, /** @brief [device] RAJA CUDA backend. Enabled when MFEM_USE_RAJA = YES and MFEM_USE_CUDA = YES. */ RAJA_CUDA = 1 << 5, /** @brief [host] OCCA CPU backend: sequential execution on each MPI rank. Enabled when MFEM_USE_OCCA = YES. */ OCCA_CPU = 1 << 6, /// [host] OCCA OpenMP backend. Enabled when MFEM_USE_OCCA = YES. OCCA_OMP = 1 << 7, /** @brief [device] OCCA CUDA backend. Enabled when MFEM_USE_OCCA = YES and MFEM_USE_CUDA = YES. */ OCCA_CUDA = 1 << 8 }; /** @brief Additional useful constants. For example, the *_MASK constants can be used with Device::Allows(). */ enum { /// Number of backends: from (1 << 0) to (1 << (NUM_BACKENDS-1)). NUM_BACKENDS = 9, /// Biwise-OR of all CUDA backends CUDA_MASK = CUDA | RAJA_CUDA | OCCA_CUDA, /// Biwise-OR of all RAJA backends RAJA_MASK = RAJA_CPU | RAJA_OMP | RAJA_CUDA, /// Biwise-OR of all OCCA backends OCCA_MASK = OCCA_CPU | OCCA_OMP | OCCA_CUDA, /// Biwise-OR of all OpenMP backends OMP_MASK = OMP | RAJA_OMP | OCCA_OMP, /// Biwise-OR of all device backends DEVICE_MASK = CUDA_MASK }; }; /** @brief The MFEM Device class abstracts hardware devices, such as GPUs, as well as programming models, such as CUDA, OCCA, RAJA and OpenMP. */ /** This class represents a "virtual device" with the following properties: - There a single object of this class which is controlled by its static methods. - Once configured, the object cannot be re-configured during the program lifetime. - MFEM classes use this object to determine where (host or device) to perform an operation and which backend implementation to use. - Multiple backends can be configured at the same time; currently, a fixed priority order is used to select a specific backend from the list of configured backends. See the Backend class and the Configure() method in this class for details. - The device can be disabled to restrict the backend selection to only the default host CPU backend, see the methods Enable() and Disable(). */ class Device { private: enum MODES {SEQUENTIAL, ACCELERATED}; MODES mode; int dev = 0; ///< Device ID of the configured device. int ngpu = -1; ///< Number of detected devices; -1: not initialized. unsigned long backends; ///< Bitwise-OR of all configured backends. /** Bitwise-OR mask of all allowed backends. All backends are active when the Device is enabled. When the Device is disabled, only the host CPU backend is allowed. */ unsigned long allowed_backends; Device() : mode(Device::SEQUENTIAL), backends(Backend::CPU), allowed_backends(backends) { } Device(Device const&); void operator=(Device const&); static Device& Get() { static Device singleton; return singleton; } /// Setup switcher based on configuration settings void Setup(const int dev = 0); void MarkBackend(Backend::Id b) { backends |= b; } public: /// Configure the Device backends. /** The string parameter @a device must be a comma-separated list of backend string names (see below). The @a dev argument specifies the ID of the actual devices (e.g. GPU) to use. * The available backends are described by the Backend class. * The string name of a backend is the lowercase version of the Backend::Id enumeration constant with '_' replaced by '-', e.g. the string name of 'RAJA_CPU' is 'raja-cpu'. * The 'cpu' backend is always enabled with lowest priority. * The current backend priority from highest to lowest is: 'occa-cuda', 'raja-cuda', 'cuda', 'occa-omp', 'raja-omp', 'omp', 'occa-cpu', 'raja-cpu', 'cpu'. * Multiple backends can be configured at the same time. * Only one 'occa-*' backend can be configured at a time. * The backend 'occa-cuda' enables the 'cuda' backend unless 'raja-cuda' is already enabled. * After this call, the Device will be disabled. */ static void Configure(const std::string &device, const int dev = 0); /// Print the configuration of the MFEM virtual device object. static void Print(std::ostream &out = mfem::out); /// Return true if Configure() has been called previously. static inline bool IsConfigured() { return Get().ngpu >= 0; } /// Return true if an actual device (e.g. GPU) has been configured. static inline bool IsAvailable() { return Get().ngpu > 0; } /// Enable the use of the configured device in the code that follows. /** After this call MFEM classes will use the backend kernels whenever possible, transferring data automatically to the device, if necessary. */ static inline void Enable() { if (IsAvailable()) { Get().mode = Device::ACCELERATED; Get().allowed_backends = Get().backends; } else { Get().mode = Device::SEQUENTIAL; Get().allowed_backends = Backend::CPU; } } /// Disable the use of the configured device in the code that follows. /** After this call MFEM classes will only use default CPU kernels, transferring data automatically from the device, if necessary. */ static inline void Disable() { Get().mode = Device::SEQUENTIAL; Get().allowed_backends = Backend::CPU; } /// Return true if the Device is enabled. static inline bool IsEnabled() { return Get().mode == ACCELERATED; } /// The opposite of IsEnabled(). static inline bool IsDisabled() { return !IsEnabled(); } /** @brief Return true if any of the backends in the backend mask, @a b_mask, are allowed. The allowed backends are all configured backends minus the device backends when the Device is disabled. */ /** This method can be used with any of the Backend::Id constants, the Backend::*_MASK, or combinations of those. */ static inline bool Allows(unsigned long b_mask) { return Get().allowed_backends & b_mask; } /// Enable the memory manager static void EnableMemoryManager(); /// Disable the memory manager static void DisableMemoryManager(); /// Return true if the memory manager is enabled static bool IsMemoryManagerEnabled(); ~Device(); }; } // mfem #endif // MFEM_DEVICE_HPP <|endoftext|>
<commit_before>// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ScenicWindow.cpp: // Implements methods from ScenicWindow // #include "util/fuchsia/ScenicWindow.h" #include <fuchsia/images/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fidl/cpp/interface_ptr.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/channel.h> #include <zircon/status.h> #include "common/debug.h" namespace { async::Loop *GetDefaultLoop() { static async::Loop *defaultLoop = new async::Loop(&kAsyncLoopConfigNeverAttachToThread); return defaultLoop; } zx::channel ConnectToServiceRoot() { zx::channel clientChannel; zx::channel serverChannel; zx_status_t result = zx::channel::create(0, &clientChannel, &serverChannel); ASSERT(result == ZX_OK); result = fdio_service_connect("/svc/.", serverChannel.release()); ASSERT(result == ZX_OK); return clientChannel; } template <typename Interface> zx_status_t ConnectToService(zx_handle_t serviceRoot, fidl::InterfaceRequest<Interface> request) { ASSERT(request.is_valid()); return fdio_service_connect_at(serviceRoot, Interface::Name_, request.TakeChannel().release()); } template <typename Interface> fidl::InterfacePtr<Interface> ConnectToService(zx_handle_t serviceRoot, async_dispatcher_t *dispatcher) { fidl::InterfacePtr<Interface> result; ConnectToService(serviceRoot, result.NewRequest(dispatcher)); return result; } } // namespace ScenicWindow::ScenicWindow() : mLoop(GetDefaultLoop()), mServiceRoot(ConnectToServiceRoot()), mScenic( ConnectToService<fuchsia::ui::scenic::Scenic>(mServiceRoot.get(), mLoop->dispatcher())), mPresenter(ConnectToService<fuchsia::ui::policy::Presenter>(mServiceRoot.get(), mLoop->dispatcher())), mScenicSession(mScenic.get(), mLoop->dispatcher()), mShape(&mScenicSession), mMaterial(&mScenicSession) { mScenicSession.set_error_handler(fit::bind_member(this, &ScenicWindow::onScenicError)); mScenicSession.set_on_frame_presented_handler( fit::bind_member(this, &ScenicWindow::onFramePresented)); } ScenicWindow::~ScenicWindow() { destroy(); } bool ScenicWindow::initialize(const std::string &name, int width, int height) { // Set up scenic resources. mShape.SetShape(scenic::Rectangle(&mScenicSession, width, height)); mShape.SetMaterial(mMaterial); fuchsia::ui::views::ViewToken viewToken; fuchsia::ui::views::ViewHolderToken viewHolderToken; std::tie(viewToken, viewHolderToken) = scenic::NewViewTokenPair(); // Create view. mView = std::make_unique<scenic::View>(&mScenicSession, std::move(viewToken), name); mView->AddChild(mShape); // Present view. mPresenter->PresentView(std::move(viewHolderToken), nullptr); mWidth = width; mHeight = height; resetNativeWindow(); return true; } void ScenicWindow::destroy() { while (mInFlightPresents != 0 && !mLostSession) { mLoop->ResetQuit(); mLoop->Run(); } ASSERT(mInFlightPresents == 0 || mLostSession); mFuchsiaEGLWindow.reset(); } void ScenicWindow::resetNativeWindow() { fuchsia::images::ImagePipe2Ptr imagePipe; uint32_t imagePipeId = mScenicSession.AllocResourceId(); mScenicSession.Enqueue( scenic::NewCreateImagePipe2Cmd(imagePipeId, imagePipe.NewRequest(mLoop->dispatcher()))); zx_handle_t imagePipeHandle = imagePipe.Unbind().TakeChannel().release(); mMaterial.SetTexture(imagePipeId); mScenicSession.ReleaseResource(imagePipeId); present(); mFuchsiaEGLWindow.reset(fuchsia_egl_window_create(imagePipeHandle, mWidth, mHeight)); } EGLNativeWindowType ScenicWindow::getNativeWindow() const { return reinterpret_cast<EGLNativeWindowType>(mFuchsiaEGLWindow.get()); } EGLNativeDisplayType ScenicWindow::getNativeDisplay() const { return EGL_DEFAULT_DISPLAY; } void ScenicWindow::messageLoop() { mLoop->ResetQuit(); mLoop->RunUntilIdle(); } void ScenicWindow::setMousePosition(int x, int y) { UNIMPLEMENTED(); } bool ScenicWindow::setPosition(int x, int y) { UNIMPLEMENTED(); return false; } bool ScenicWindow::resize(int width, int height) { mWidth = width; mHeight = height; fuchsia_egl_window_resize(mFuchsiaEGLWindow.get(), width, height); return true; } void ScenicWindow::setVisible(bool isVisible) {} void ScenicWindow::signalTestEvent() {} void ScenicWindow::present() { while (mInFlightPresents >= kMaxInFlightPresents && !mLostSession) { mLoop->ResetQuit(); mLoop->Run(); } if (mLostSession) { return; } ASSERT(mInFlightPresents < kMaxInFlightPresents); ++mInFlightPresents; mScenicSession.Present2(0, 0, [](fuchsia::scenic::scheduling::FuturePresentationTimes info) {}); } void ScenicWindow::onFramePresented(fuchsia::scenic::scheduling::FramePresentedInfo info) { mInFlightPresents -= info.presentation_infos.size(); ASSERT(mInFlightPresents >= 0); mLoop->Quit(); } void ScenicWindow::onScenicEvents(std::vector<fuchsia::ui::scenic::Event> events) { UNIMPLEMENTED(); } void ScenicWindow::onScenicError(zx_status_t status) { WARN() << "OnScenicError: " << zx_status_get_string(status); mLostSession = true; mLoop->Quit(); } // static OSWindow *OSWindow::New() { return new ScenicWindow; } <commit_msg>Fuchsia: Switch ScenicWindow to use PresentOrReplaceView<commit_after>// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ScenicWindow.cpp: // Implements methods from ScenicWindow // #include "util/fuchsia/ScenicWindow.h" #include <fuchsia/images/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fidl/cpp/interface_ptr.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/channel.h> #include <zircon/status.h> #include "common/debug.h" namespace { async::Loop *GetDefaultLoop() { static async::Loop *defaultLoop = new async::Loop(&kAsyncLoopConfigNeverAttachToThread); return defaultLoop; } zx::channel ConnectToServiceRoot() { zx::channel clientChannel; zx::channel serverChannel; zx_status_t result = zx::channel::create(0, &clientChannel, &serverChannel); ASSERT(result == ZX_OK); result = fdio_service_connect("/svc/.", serverChannel.release()); ASSERT(result == ZX_OK); return clientChannel; } template <typename Interface> zx_status_t ConnectToService(zx_handle_t serviceRoot, fidl::InterfaceRequest<Interface> request) { ASSERT(request.is_valid()); return fdio_service_connect_at(serviceRoot, Interface::Name_, request.TakeChannel().release()); } template <typename Interface> fidl::InterfacePtr<Interface> ConnectToService(zx_handle_t serviceRoot, async_dispatcher_t *dispatcher) { fidl::InterfacePtr<Interface> result; ConnectToService(serviceRoot, result.NewRequest(dispatcher)); return result; } } // namespace ScenicWindow::ScenicWindow() : mLoop(GetDefaultLoop()), mServiceRoot(ConnectToServiceRoot()), mScenic( ConnectToService<fuchsia::ui::scenic::Scenic>(mServiceRoot.get(), mLoop->dispatcher())), mPresenter(ConnectToService<fuchsia::ui::policy::Presenter>(mServiceRoot.get(), mLoop->dispatcher())), mScenicSession(mScenic.get(), mLoop->dispatcher()), mShape(&mScenicSession), mMaterial(&mScenicSession) { mScenicSession.set_error_handler(fit::bind_member(this, &ScenicWindow::onScenicError)); mScenicSession.set_on_frame_presented_handler( fit::bind_member(this, &ScenicWindow::onFramePresented)); } ScenicWindow::~ScenicWindow() { destroy(); } bool ScenicWindow::initialize(const std::string &name, int width, int height) { // Set up scenic resources. mShape.SetShape(scenic::Rectangle(&mScenicSession, width, height)); mShape.SetMaterial(mMaterial); fuchsia::ui::views::ViewToken viewToken; fuchsia::ui::views::ViewHolderToken viewHolderToken; std::tie(viewToken, viewHolderToken) = scenic::NewViewTokenPair(); // Create view. mView = std::make_unique<scenic::View>(&mScenicSession, std::move(viewToken), name); mView->AddChild(mShape); // Present view. mPresenter->PresentOrReplaceView(std::move(viewHolderToken), nullptr); mWidth = width; mHeight = height; resetNativeWindow(); return true; } void ScenicWindow::destroy() { while (mInFlightPresents != 0 && !mLostSession) { mLoop->ResetQuit(); mLoop->Run(); } ASSERT(mInFlightPresents == 0 || mLostSession); mFuchsiaEGLWindow.reset(); } void ScenicWindow::resetNativeWindow() { fuchsia::images::ImagePipe2Ptr imagePipe; uint32_t imagePipeId = mScenicSession.AllocResourceId(); mScenicSession.Enqueue( scenic::NewCreateImagePipe2Cmd(imagePipeId, imagePipe.NewRequest(mLoop->dispatcher()))); zx_handle_t imagePipeHandle = imagePipe.Unbind().TakeChannel().release(); mMaterial.SetTexture(imagePipeId); mScenicSession.ReleaseResource(imagePipeId); present(); mFuchsiaEGLWindow.reset(fuchsia_egl_window_create(imagePipeHandle, mWidth, mHeight)); } EGLNativeWindowType ScenicWindow::getNativeWindow() const { return reinterpret_cast<EGLNativeWindowType>(mFuchsiaEGLWindow.get()); } EGLNativeDisplayType ScenicWindow::getNativeDisplay() const { return EGL_DEFAULT_DISPLAY; } void ScenicWindow::messageLoop() { mLoop->ResetQuit(); mLoop->RunUntilIdle(); } void ScenicWindow::setMousePosition(int x, int y) { UNIMPLEMENTED(); } bool ScenicWindow::setPosition(int x, int y) { UNIMPLEMENTED(); return false; } bool ScenicWindow::resize(int width, int height) { mWidth = width; mHeight = height; fuchsia_egl_window_resize(mFuchsiaEGLWindow.get(), width, height); return true; } void ScenicWindow::setVisible(bool isVisible) {} void ScenicWindow::signalTestEvent() {} void ScenicWindow::present() { while (mInFlightPresents >= kMaxInFlightPresents && !mLostSession) { mLoop->ResetQuit(); mLoop->Run(); } if (mLostSession) { return; } ASSERT(mInFlightPresents < kMaxInFlightPresents); ++mInFlightPresents; mScenicSession.Present2(0, 0, [](fuchsia::scenic::scheduling::FuturePresentationTimes info) {}); } void ScenicWindow::onFramePresented(fuchsia::scenic::scheduling::FramePresentedInfo info) { mInFlightPresents -= info.presentation_infos.size(); ASSERT(mInFlightPresents >= 0); mLoop->Quit(); } void ScenicWindow::onScenicEvents(std::vector<fuchsia::ui::scenic::Event> events) { UNIMPLEMENTED(); } void ScenicWindow::onScenicError(zx_status_t status) { WARN() << "OnScenicError: " << zx_status_get_string(status); mLostSession = true; mLoop->Quit(); } // static OSWindow *OSWindow::New() { return new ScenicWindow; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salvtables.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <vcl/salframe.hxx> #include <vcl/salinst.hxx> #include <vcl/salvd.hxx> #include <vcl/salprn.hxx> #include <vcl/saltimer.hxx> #include <vcl/salogl.hxx> #include <vcl/salimestatus.hxx> #include <vcl/salsys.hxx> #include <vcl/salbmp.hxx> #include <vcl/salobj.hxx> #include <vcl/salmenu.hxx> #include <vcl/salctrlhandle.hxx> // this file contains the virtual destructors of the sal interface // compilers ususally put their vtables where the destructor is SalFrame::~SalFrame() { } // ----------------------------------------------------------------------- // default to full-frame flushes // on ports where partial-flushes are much cheaper this method should be overridden void SalFrame::Flush( const Rectangle& ) { Flush(); } // ----------------------------------------------------------------------- SalInstance::~SalInstance() { } SalTimer::~SalTimer() { } SalOpenGL::~SalOpenGL() { } SalBitmap::~SalBitmap() { } SalI18NImeStatus::~SalI18NImeStatus() { } SalSystem::~SalSystem() { } SalPrinter::~SalPrinter() { } BOOL SalPrinter::StartJob( const String*, const String&, ImplJobSetup*, ImplQPrinter* ) { return FALSE; } SalInfoPrinter::~SalInfoPrinter() { } SalVirtualDevice::~SalVirtualDevice() { } SalObject::~SalObject() { } SalMenu::~SalMenu() { } BOOL SalMenu::ShowNativePopupMenu(FloatingWindow *, const Rectangle&, ULONG ) { return FALSE; }; SalMenuItem::~SalMenuItem() { } SalControlHandle::~SalControlHandle() { } <commit_msg>INTEGRATION: CWS aquaupdateicon (1.13.78); FILE MERGED 2008/07/31 14:06:25 pl 1.13.78.3: fix a warning 2008/07/30 12:17:58 pl 1.13.78.2: #i92043# implement native menu buttons 2008/07/29 17:39:19 pl 1.13.78.1: #i92043# add: native menubar add buttons<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salvtables.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <vcl/salframe.hxx> #include <vcl/salinst.hxx> #include <vcl/salvd.hxx> #include <vcl/salprn.hxx> #include <vcl/saltimer.hxx> #include <vcl/salogl.hxx> #include <vcl/salimestatus.hxx> #include <vcl/salsys.hxx> #include <vcl/salbmp.hxx> #include <vcl/salobj.hxx> #include <vcl/salmenu.hxx> #include <vcl/salctrlhandle.hxx> // this file contains the virtual destructors of the sal interface // compilers ususally put their vtables where the destructor is SalFrame::~SalFrame() { } // ----------------------------------------------------------------------- // default to full-frame flushes // on ports where partial-flushes are much cheaper this method should be overridden void SalFrame::Flush( const Rectangle& ) { Flush(); } // ----------------------------------------------------------------------- SalInstance::~SalInstance() { } SalTimer::~SalTimer() { } SalOpenGL::~SalOpenGL() { } SalBitmap::~SalBitmap() { } SalI18NImeStatus::~SalI18NImeStatus() { } SalSystem::~SalSystem() { } SalPrinter::~SalPrinter() { } BOOL SalPrinter::StartJob( const String*, const String&, ImplJobSetup*, ImplQPrinter* ) { return FALSE; } SalInfoPrinter::~SalInfoPrinter() { } SalVirtualDevice::~SalVirtualDevice() { } SalObject::~SalObject() { } SalMenu::~SalMenu() { } bool SalMenu::ShowNativePopupMenu(FloatingWindow *, const Rectangle&, ULONG ) { return false; } bool SalMenu::AddMenuBarButton( const SalMenuButtonItem& ) { return false; } void SalMenu::RemoveMenuBarButton( USHORT ) { } Rectangle SalMenu::GetMenuBarButtonRectPixel( USHORT, SalFrame* ) { return Rectangle(); } SalMenuItem::~SalMenuItem() { } SalControlHandle::~SalControlHandle() { } <|endoftext|>
<commit_before>#include <Album.h> #include <cassert> using namespace SoundCity; Album::Album(int id, const std::string &title, const std::string &artist, int release) : id(id), artist(artist), title(title), release(release) { assert(&title); assert(&artist); assert(release); }<commit_msg>Mise à jour du assert sur l'année<commit_after>#include <Album.h> #include <cassert> using namespace SoundCity; Album::Album(int id, const std::string &title, const std::string &artist, int release) : id(id), artist(artist), title(title), release(release) { assert(&title); assert(&artist); assert(release > 0); }<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMeshSpatialObjectIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkMeshSpatialObject.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectWriter.h" #include "itkSpatialObjectReader.h" #include "itkMesh.h" #include "itkTetrahedronCell.h" #include "itkHexahedronCell.h" #include "itkQuadraticEdgeCell.h" #include "itkQuadraticTriangleCell.h" #include <itkDefaultDynamicMeshTraits.h> #include <iostream> #include <string> int itkMeshSpatialObjectIOTest(int, char*[]) { typedef itk::DefaultDynamicMeshTraits< float , 3, 3 > MeshTrait; typedef itk::Mesh<float,3,MeshTrait> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< float, CellTraits > CellInterfaceType; typedef itk::TetrahedronCell<CellInterfaceType> TetraCellType; typedef itk::HexahedronCell<CellInterfaceType> HexaCellType; typedef itk::MeshSpatialObject<MeshType> MeshSpatialObjectType; typedef MeshType::PointType PointType; typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Create an itkMesh std::cout << "Creating Mesh File: "; MeshType::Pointer mesh = MeshType::New(); MeshType::CoordRepType testPointCoords[8][3] = { {0,1,2}, {1,2,3}, {2,3,4}, {3,4,5}, {4,5,6}, {5,6,7}, {6,7,8}, {7,8,9}}; unsigned long tetraPoints[4] = {0,1,2,3}; unsigned long hexaPoints[8] = {0,1,2,3,4,5,6,7}; unsigned int i; unsigned int j; for(i=0; i < 8 ; ++i) { mesh->SetPoint(i, PointType(testPointCoords[i])); } mesh->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell1; testCell1.TakeOwnership( new TetraCellType ); testCell1->SetPointIds(tetraPoints); mesh->SetCell(0, testCell1 ); CellAutoPointer testCell2; testCell2.TakeOwnership( new HexaCellType ); testCell2->SetPointIds(hexaPoints); mesh->SetCell(0, testCell1 ); mesh->SetCell(1, testCell2 ); // Add cell links typedef MeshType::CellLinksContainer CellLinksContainerType; CellLinksContainerType::Pointer linkContainer = CellLinksContainerType::New(); MeshType::PointCellLinksContainer pcl; for(j=0;j<3;j++) { for(i=0;i<5;i++) { pcl.insert(j+i); } linkContainer->SetElement(j,pcl); } mesh->SetCellLinks(linkContainer); // Add point data typedef MeshType::PointDataContainer PointDataContainer; PointDataContainer::Pointer pointData = PointDataContainer::New(); float data = 0.1; for(j=0;j<2;j++) { pointData->SetElement(j, data); data += (float)0.1; } mesh->SetPointData(pointData); // Add cell data typedef MeshType::CellDataContainer CellDataContainer; CellDataContainer::Pointer cellData = CellDataContainer::New(); data = 0.9; for(j=0;j<3;j++) { cellData->SetElement(j, data); data -= (float)0.2; } mesh->SetCellData(cellData); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshSO = MeshSpatialObjectType::New(); meshSO->SetMesh(mesh); std::cout<<"[PASSED]"<<std::endl; // Writing the file std::cout<<"Testing Writing MeshSpatialObject: "; typedef itk::SpatialObjectWriter<3,float,MeshTrait> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(meshSO); writer->SetFullFileName("metamesh.txt"); writer->Update(); std::cout<<"[PASSED]"<<std::endl; // Reading the file std::cout<<"Testing Reading MeshSpatialObject: "; typedef itk::SpatialObjectReader<3,float,MeshTrait> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName("metamesh.txt"); reader->Update(); ReaderType::ScenePointer myScene = reader->GetScene(); if(!myScene) { std::cout<<"No Scene : [FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; // Testing the mesh validity MeshSpatialObjectType::ChildrenListType* children = reader->GetGroup()->GetChildren(); if(strcmp((*(children->begin()))->GetTypeName(),"MeshSpatialObject")) { std::cout<<" [FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"Testing Points: "; MeshSpatialObjectType::Pointer meshSO2 = dynamic_cast<MeshSpatialObjectType*>((*(children->begin())).GetPointer()); MeshType::Pointer mesh2 = meshSO2->GetMesh(); // Testing points const MeshType::PointsContainer* points = mesh2->GetPoints(); MeshType::PointsContainer::ConstIterator it_points = points->Begin(); j=0; while(it_points != points->End()) { if((*it_points)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_points)->Index() << " v.s. " << j << std::endl; return EXIT_FAILURE; } for(i=0;i<3;i++) { if(((*it_points)->Value())[i] != j+i) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Value = " << (*it_points)->Value() << std::endl; return EXIT_FAILURE; } } j++; it_points++; } std::cout<<" [PASSED]"<<std::endl; // Testing cells std::cout<<"Testing Cells : "; const MeshType::CellsContainer* cells = mesh2->GetCells(); MeshType::CellsContainer::ConstIterator it_cells = cells->Begin(); j=0; while(it_cells != cells->End()) { MeshType::CellTraits::PointIdConstIterator itptids = (*it_cells)->Value()->GetPointIds(); if((*it_cells)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << (*it_cells)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } unsigned int i=0; while(itptids != (*it_cells)->Value()->PointIdsEnd()) { if(*itptids != i) { std::cout<<" [FAILED]"<<std::endl; std::cout << *itptids << " v.s. " << i << std::endl; return EXIT_FAILURE; } i++; itptids++; } j++; it_cells++; } std::cout<<" [PASSED]"<<std::endl; delete children; // Testing celllinks std::cout<<"Testing CellLinks : "; j=0; typedef MeshType::CellLinksContainer CellLinksContainer; const CellLinksContainer* links = mesh2->GetCellLinks(); MeshType::CellLinksContainer::ConstIterator it_celllinks = links->Begin(); while(it_celllinks != links->End()) { if((*it_celllinks)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_celllinks)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } i =0; MeshType::PointCellLinksContainer::const_iterator it = (*it_celllinks)->Value().begin(); while(it != (*it_celllinks)->Value().end()) { if( (*it) != i) { std::cout<<" [FAILED]"<<std::endl; std::cout << (*it) << " v.s " << i << std::endl;; return EXIT_FAILURE; } i++; it++; } j++; it_celllinks++; } std::cout<<" [PASSED]"<<std::endl; // Testing pointdata std::cout<<"Testing Pointdata : "; j=0; data = 0.1; typedef MeshType::PointDataContainer PointDataContainer; const PointDataContainer* pd = mesh2->GetPointData(); if(pd) { MeshType::PointDataContainer::ConstIterator it_pd = pd->Begin(); while(it_pd != pd->End()) { if((*it_pd)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_pd)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } if(fabs((*it_pd)->Value()-data)>0.001) { std::cout<<" [FAILED]"<<std::endl; std::cout << "value = " << (*it_pd)->Value() << " v.s " << data << std::endl;; return EXIT_FAILURE; } data += float(0.1); it_pd++; j++; } } else { std::cout<<"No Point Data" << std::endl; std::cout << "[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; // Testing celldata std::cout<<"Testing Celldata : "; j=0; data = 0.9; typedef MeshType::CellDataContainer PointDataContainer; const PointDataContainer* pc = mesh2->GetCellData(); if(pc) { MeshType::CellDataContainer::ConstIterator it_pc = pc->Begin(); while(it_pc != pc->End()) { if((*it_pc)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_pc)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } if(fabs((*it_pc)->Value()-data)>0.001) { std::cout<<" [FAILED]"<<std::endl; std::cout << "value = " << (*it_pc)->Value() << " v.s " << data << std::endl;; return EXIT_FAILURE; } data -= float(0.2); it_pc++; j++; } } else { std::cout<<"No Cell Data" << std::endl; std::cout << "[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; std::cout << " [TEST DONE]" << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: SetFileName() should be used instead of SetFullFileName()<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMeshSpatialObjectIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkMeshSpatialObject.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectWriter.h" #include "itkSpatialObjectReader.h" #include "itkMesh.h" #include "itkTetrahedronCell.h" #include "itkHexahedronCell.h" #include "itkQuadraticEdgeCell.h" #include "itkQuadraticTriangleCell.h" #include <itkDefaultDynamicMeshTraits.h> #include <iostream> #include <string> int itkMeshSpatialObjectIOTest(int, char*[]) { typedef itk::DefaultDynamicMeshTraits< float , 3, 3 > MeshTrait; typedef itk::Mesh<float,3,MeshTrait> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< float, CellTraits > CellInterfaceType; typedef itk::TetrahedronCell<CellInterfaceType> TetraCellType; typedef itk::HexahedronCell<CellInterfaceType> HexaCellType; typedef itk::MeshSpatialObject<MeshType> MeshSpatialObjectType; typedef MeshType::PointType PointType; typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Create an itkMesh std::cout << "Creating Mesh File: "; MeshType::Pointer mesh = MeshType::New(); MeshType::CoordRepType testPointCoords[8][3] = { {0,1,2}, {1,2,3}, {2,3,4}, {3,4,5}, {4,5,6}, {5,6,7}, {6,7,8}, {7,8,9}}; unsigned long tetraPoints[4] = {0,1,2,3}; unsigned long hexaPoints[8] = {0,1,2,3,4,5,6,7}; unsigned int i; unsigned int j; for(i=0; i < 8 ; ++i) { mesh->SetPoint(i, PointType(testPointCoords[i])); } mesh->SetCellsAllocationMethod( MeshType::CellsAllocatedDynamicallyCellByCell ); CellAutoPointer testCell1; testCell1.TakeOwnership( new TetraCellType ); testCell1->SetPointIds(tetraPoints); mesh->SetCell(0, testCell1 ); CellAutoPointer testCell2; testCell2.TakeOwnership( new HexaCellType ); testCell2->SetPointIds(hexaPoints); mesh->SetCell(0, testCell1 ); mesh->SetCell(1, testCell2 ); // Add cell links typedef MeshType::CellLinksContainer CellLinksContainerType; CellLinksContainerType::Pointer linkContainer = CellLinksContainerType::New(); MeshType::PointCellLinksContainer pcl; for(j=0;j<3;j++) { for(i=0;i<5;i++) { pcl.insert(j+i); } linkContainer->SetElement(j,pcl); } mesh->SetCellLinks(linkContainer); // Add point data typedef MeshType::PointDataContainer PointDataContainer; PointDataContainer::Pointer pointData = PointDataContainer::New(); float data = 0.1; for(j=0;j<2;j++) { pointData->SetElement(j, data); data += (float)0.1; } mesh->SetPointData(pointData); // Add cell data typedef MeshType::CellDataContainer CellDataContainer; CellDataContainer::Pointer cellData = CellDataContainer::New(); data = 0.9; for(j=0;j<3;j++) { cellData->SetElement(j, data); data -= (float)0.2; } mesh->SetCellData(cellData); // Create the mesh Spatial Object MeshSpatialObjectType::Pointer meshSO = MeshSpatialObjectType::New(); meshSO->SetMesh(mesh); std::cout<<"[PASSED]"<<std::endl; // Writing the file std::cout<<"Testing Writing MeshSpatialObject: "; typedef itk::SpatialObjectWriter<3,float,MeshTrait> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(meshSO); writer->SetFileName("metamesh.txt"); writer->Update(); std::cout<<"[PASSED]"<<std::endl; // Reading the file std::cout<<"Testing Reading MeshSpatialObject: "; typedef itk::SpatialObjectReader<3,float,MeshTrait> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName("metamesh.txt"); reader->Update(); ReaderType::ScenePointer myScene = reader->GetScene(); if(!myScene) { std::cout<<"No Scene : [FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; // Testing the mesh validity MeshSpatialObjectType::ChildrenListType* children = reader->GetGroup()->GetChildren(); if(strcmp((*(children->begin()))->GetTypeName(),"MeshSpatialObject")) { std::cout<<" [FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"Testing Points: "; MeshSpatialObjectType::Pointer meshSO2 = dynamic_cast<MeshSpatialObjectType*>((*(children->begin())).GetPointer()); MeshType::Pointer mesh2 = meshSO2->GetMesh(); // Testing points const MeshType::PointsContainer* points = mesh2->GetPoints(); MeshType::PointsContainer::ConstIterator it_points = points->Begin(); j=0; while(it_points != points->End()) { if((*it_points)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_points)->Index() << " v.s. " << j << std::endl; return EXIT_FAILURE; } for(i=0;i<3;i++) { if(((*it_points)->Value())[i] != j+i) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Value = " << (*it_points)->Value() << std::endl; return EXIT_FAILURE; } } j++; it_points++; } std::cout<<" [PASSED]"<<std::endl; // Testing cells std::cout<<"Testing Cells : "; const MeshType::CellsContainer* cells = mesh2->GetCells(); MeshType::CellsContainer::ConstIterator it_cells = cells->Begin(); j=0; while(it_cells != cells->End()) { MeshType::CellTraits::PointIdConstIterator itptids = (*it_cells)->Value()->GetPointIds(); if((*it_cells)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << (*it_cells)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } unsigned int i=0; while(itptids != (*it_cells)->Value()->PointIdsEnd()) { if(*itptids != i) { std::cout<<" [FAILED]"<<std::endl; std::cout << *itptids << " v.s. " << i << std::endl; return EXIT_FAILURE; } i++; itptids++; } j++; it_cells++; } std::cout<<" [PASSED]"<<std::endl; delete children; // Testing celllinks std::cout<<"Testing CellLinks : "; j=0; typedef MeshType::CellLinksContainer CellLinksContainer; const CellLinksContainer* links = mesh2->GetCellLinks(); MeshType::CellLinksContainer::ConstIterator it_celllinks = links->Begin(); while(it_celllinks != links->End()) { if((*it_celllinks)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_celllinks)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } i =0; MeshType::PointCellLinksContainer::const_iterator it = (*it_celllinks)->Value().begin(); while(it != (*it_celllinks)->Value().end()) { if( (*it) != i) { std::cout<<" [FAILED]"<<std::endl; std::cout << (*it) << " v.s " << i << std::endl;; return EXIT_FAILURE; } i++; it++; } j++; it_celllinks++; } std::cout<<" [PASSED]"<<std::endl; // Testing pointdata std::cout<<"Testing Pointdata : "; j=0; data = 0.1; typedef MeshType::PointDataContainer PointDataContainer; const PointDataContainer* pd = mesh2->GetPointData(); if(pd) { MeshType::PointDataContainer::ConstIterator it_pd = pd->Begin(); while(it_pd != pd->End()) { if((*it_pd)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_pd)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } if(fabs((*it_pd)->Value()-data)>0.001) { std::cout<<" [FAILED]"<<std::endl; std::cout << "value = " << (*it_pd)->Value() << " v.s " << data << std::endl;; return EXIT_FAILURE; } data += float(0.1); it_pd++; j++; } } else { std::cout<<"No Point Data" << std::endl; std::cout << "[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; // Testing celldata std::cout<<"Testing Celldata : "; j=0; data = 0.9; typedef MeshType::CellDataContainer PointDataContainer; const PointDataContainer* pc = mesh2->GetCellData(); if(pc) { MeshType::CellDataContainer::ConstIterator it_pc = pc->Begin(); while(it_pc != pc->End()) { if((*it_pc)->Index() != j) { std::cout<<" [FAILED]"<<std::endl; std::cout << "Index = " << (*it_pc)->Index() << " v.s " << j << std::endl;; return EXIT_FAILURE; } if(fabs((*it_pc)->Value()-data)>0.001) { std::cout<<" [FAILED]"<<std::endl; std::cout << "value = " << (*it_pc)->Value() << " v.s " << data << std::endl;; return EXIT_FAILURE; } data -= float(0.2); it_pc++; j++; } } else { std::cout<<"No Cell Data" << std::endl; std::cout << "[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<" [PASSED]"<<std::endl; std::cout << " [TEST DONE]" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* A BlockEnvironment is created when a block is created. Its primary * operation is call, which activates the code associated with the block. */ #include "block_environment.hpp" #include "objectmemory.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/contexts.hpp" #include "builtin/fixnum.hpp" #include "builtin/symbol.hpp" #include "builtin/task.hpp" #include "builtin/tuple.hpp" namespace rubinius { void BlockEnvironment::call(STATE, Task* task, size_t args) { OBJECT val; if(args > 0) { Tuple* tup = Tuple::create(state, args); for(size_t i = args - 1; i >= 0; i--) { tup->put(state, i, task->pop()); } val = tup; } else { val = Qnil; } task->pop(); // Remove this from the stack. BlockContext* ctx = create_context(state, task->active); task->make_active(ctx); task->push(val); } void BlockEnvironment::call(STATE, Message& msg) { throw std::runtime_error("call2: not implemented"); } BlockContext* BlockEnvironment::create_context(STATE, MethodContext* sender) { BlockContext* ctx = BlockContext::create(state, method->stack_size->to_native()); SET(ctx, sender, sender); SET(ctx, name, (SYMBOL)this); SET(ctx, cm, method); SET(ctx, home, home); ctx->vmm = vmm; ctx->ip = 0; ctx->position_stack(-1); return ctx; } BlockEnvironment* BlockEnvironment::under_context(STATE, CompiledMethod* cm, MethodContext* parent, MethodContext* active, size_t index) { BlockEnvironment* be = (BlockEnvironment*)state->new_object(G(blokenv)); VMMethod* vmm; if((vmm = active->vmm->blocks[index]) == NULL) { vmm = new VMMethod(state, cm); if(active->vmm->type) { vmm->specialize(active->vmm->type); } active->vmm->blocks[index] = vmm; } SET(be, home, parent); SET(be, home_block, active); SET(be, method, cm); SET(be, local_count, cm->local_count); be->vmm = vmm; return be; } } <commit_msg>Don't wrap around to MAX_INT for comparison<commit_after>/* A BlockEnvironment is created when a block is created. Its primary * operation is call, which activates the code associated with the block. */ #include "block_environment.hpp" #include "objectmemory.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/contexts.hpp" #include "builtin/fixnum.hpp" #include "builtin/symbol.hpp" #include "builtin/task.hpp" #include "builtin/tuple.hpp" namespace rubinius { void BlockEnvironment::call(STATE, Task* task, size_t args) { OBJECT val; if(args > 0) { Tuple* tup = Tuple::create(state, args); for(int i = args - 1; i >= 0; i--) { tup->put(state, i, task->pop()); } val = tup; } else { val = Qnil; } task->pop(); // Remove this from the stack. BlockContext* ctx = create_context(state, task->active); task->make_active(ctx); task->push(val); } void BlockEnvironment::call(STATE, Message& msg) { throw std::runtime_error("call2: not implemented"); } BlockContext* BlockEnvironment::create_context(STATE, MethodContext* sender) { BlockContext* ctx = BlockContext::create(state, method->stack_size->to_native()); SET(ctx, sender, sender); SET(ctx, name, (SYMBOL)this); SET(ctx, cm, method); SET(ctx, home, home); ctx->vmm = vmm; ctx->ip = 0; ctx->position_stack(-1); return ctx; } BlockEnvironment* BlockEnvironment::under_context(STATE, CompiledMethod* cm, MethodContext* parent, MethodContext* active, size_t index) { BlockEnvironment* be = (BlockEnvironment*)state->new_object(G(blokenv)); VMMethod* vmm; if((vmm = active->vmm->blocks[index]) == NULL) { vmm = new VMMethod(state, cm); if(active->vmm->type) { vmm->specialize(active->vmm->type); } active->vmm->blocks[index] = vmm; } SET(be, home, parent); SET(be, home_block, active); SET(be, method, cm); SET(be, local_count, cm->local_count); be->vmm = vmm; return be; } } <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Utils/CardSetUtils.hpp> #include <hspp/Actions/Generic.hpp> #include <hspp/Cards/Cards.hpp> using namespace Hearthstonepp; using namespace PlayerTasks; using namespace SimpleTasks; TEST(CoreCardsGen, EX1_066) { GameAgent agent(CardClass::WARRIOR, CardClass::ROGUE, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), true); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), false); } TEST(CoreCardsGen, EX1_306) { GameAgent agent(CardClass::WARLOCK, CardClass::WARRIOR, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Succubus")); Generic::DrawCard(currentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); Generic::DrawCard(opponentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(currentPlayer.GetHand().size(), 0u); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(opponentPlayer.GetHand().size(), 1u); } TEST(CoreCardsGen, CS2_041) { GameAgent agent(CardClass::SHAMAN, CardClass::ROGUE, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); const auto card2 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing")); const auto card3 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card3)); GameAgent::RunTask(opponentPlayer, CombatTask(taskAgent, card3, card1)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 1); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card2, -1, card1)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 2); EXPECT_EQ(currentPlayer.GetField()[0]->GetGameTag(GameTag::TAUNT), 1); } TEST(CoreCardsGen, CS2_088) { GameAgent agent(CardClass::DRUID, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); opponentPlayer.GetHero()->health = 24; const auto card1 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings")); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(opponentPlayer.GetHero()->maxHealth, opponentPlayer.GetHero()->health); } TEST(CoreCardsGen, CS1_112) { GameAgent agent(CardClass::PRIEST, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); currentPlayer.GetHero()->health = 26; const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy")); const auto card2 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre")); const auto card3 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Holy Nova")); const auto card4 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Argent Squire")); const auto card5 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card2)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card4)); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card5)); GameAgent::RunTask(currentPlayer, InitAttackCountTask()); GameAgent::RunTask(currentPlayer, CombatTask(taskAgent, card1, card4)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 4); EXPECT_EQ(opponentPlayer.GetField()[0]->GetGameTag(GameTag::DIVINE_SHIELD), 0); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card3)); EXPECT_EQ(currentPlayer.GetHero()->health, 28); EXPECT_EQ(opponentPlayer.GetHero()->health, 28); EXPECT_EQ(currentPlayer.GetField()[0]->health, 5); EXPECT_EQ(currentPlayer.GetField()[1]->health, 7); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); } TEST(CoreCardsGen, CS1_113) { GameAgent agent(CardClass::PRIEST, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre")); const auto card3 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Mind Control")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(currentPlayer.GetField().size(), 1u); EXPECT_EQ(opponentPlayer.GetField().size(), 1u); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card3, -1, card2)); EXPECT_EQ(currentPlayer.GetField().size(), 2u); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); }<commit_msg>test: Add test code for invalid target in CS1_113 unit test<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Utils/CardSetUtils.hpp> #include <hspp/Actions/Generic.hpp> #include <hspp/Cards/Cards.hpp> using namespace Hearthstonepp; using namespace PlayerTasks; using namespace SimpleTasks; TEST(CoreCardsGen, EX1_066) { GameAgent agent(CardClass::WARRIOR, CardClass::ROGUE, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), true); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), false); } TEST(CoreCardsGen, EX1_306) { GameAgent agent(CardClass::WARLOCK, CardClass::WARRIOR, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Succubus")); Generic::DrawCard(currentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); Generic::DrawCard(opponentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(currentPlayer.GetHand().size(), 0u); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(opponentPlayer.GetHand().size(), 1u); } TEST(CoreCardsGen, CS2_041) { GameAgent agent(CardClass::SHAMAN, CardClass::ROGUE, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze")); const auto card2 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing")); const auto card3 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card3)); GameAgent::RunTask(opponentPlayer, CombatTask(taskAgent, card3, card1)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 1); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card2, -1, card1)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 2); EXPECT_EQ(currentPlayer.GetField()[0]->GetGameTag(GameTag::TAUNT), 1); } TEST(CoreCardsGen, CS2_088) { GameAgent agent(CardClass::DRUID, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); opponentPlayer.GetHero()->health = 24; const auto card1 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings")); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card1)); EXPECT_EQ(opponentPlayer.GetHero()->maxHealth, opponentPlayer.GetHero()->health); } TEST(CoreCardsGen, CS1_112) { GameAgent agent(CardClass::PRIEST, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); currentPlayer.GetHero()->health = 26; const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy")); const auto card2 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre")); const auto card3 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Holy Nova")); const auto card4 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Argent Squire")); const auto card5 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card2)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card4)); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card5)); GameAgent::RunTask(currentPlayer, InitAttackCountTask()); GameAgent::RunTask(currentPlayer, CombatTask(taskAgent, card1, card4)); EXPECT_EQ(currentPlayer.GetField()[0]->health, 4); EXPECT_EQ(opponentPlayer.GetField()[0]->GetGameTag(GameTag::DIVINE_SHIELD), 0); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card3)); EXPECT_EQ(currentPlayer.GetHero()->health, 28); EXPECT_EQ(opponentPlayer.GetHero()->health, 28); EXPECT_EQ(currentPlayer.GetField()[0]->health, 5); EXPECT_EQ(currentPlayer.GetField()[1]->health, 7); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); } TEST(CoreCardsGen, CS1_113) { GameAgent agent(CardClass::PRIEST, CardClass::PALADIN, PlayerType::PLAYER1); TaskAgent& taskAgent = agent.GetTaskAgent(); Player& currentPlayer = agent.GetCurrentPlayer(); Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent(); currentPlayer.SetMaximumMana(10); currentPlayer.SetAvailableMana(10); opponentPlayer.SetMaximumMana(10); opponentPlayer.SetAvailableMana(10); const auto card1 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy")); const auto card2 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre")); const auto card3 = Generic::DrawCard( currentPlayer, Cards::GetInstance().FindCardByName("Mind Control")); const auto card4 = Generic::DrawCard( opponentPlayer, Cards::GetInstance().FindCardByName("Mind Control")); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1)); currentPlayer.SetAvailableMana(10); GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2)); EXPECT_EQ(currentPlayer.GetField().size(), 1u); EXPECT_EQ(opponentPlayer.GetField().size(), 1u); GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card3, -1, card2)); EXPECT_EQ(currentPlayer.GetField().size(), 2u); EXPECT_EQ(opponentPlayer.GetField().size(), 0u); opponentPlayer.SetAvailableMana(10); auto result = GameAgent::RunTask( opponentPlayer, PlayCardTask(taskAgent, card4, -1, currentPlayer.GetHero())); EXPECT_EQ(result, MetaData::PLAY_CARD_INVALID_TARGET); }<|endoftext|>
<commit_before>#include <list> #include <set> #include <iostream> #include "vtrc-asio.h" #include "vtrc-thread-pool.h" #include "vtrc-mutex-typedefs.h" #include "vtrc-memory.h" #include "vtrc-bind.h" #include "vtrc-thread.h" ///// TODO: need some fix here namespace vtrc { namespace common { namespace basio = VTRC_ASIO; typedef vtrc::unique_ptr<vtrc::thread> thread_ptr; struct thread_context { typedef vtrc::shared_ptr<thread_context> shared_type; thread_ptr thread_; }; inline bool operator < ( const thread_context &l, const thread_context &r ) { return l.thread_.get( ) < r.thread_.get( ); } static void exception_default( ) { try { throw; } catch( const std::exception &ex ) { std::cerr << "Exception in thread 0x" << std::hex << vtrc::this_thread::get_id( ) << ". what = " << ex.what( ) ; } catch( ... ) { std::cerr << "Exception '...' in thread 0x" << std::hex << vtrc::this_thread::get_id( ) ; } } typedef std::set<thread_context::shared_type> thread_set_type; struct thread_pool::impl { basio::io_service *ios_; basio::io_service::work *wrk_; bool own_ios_; thread_set_type threads_; thread_set_type stopped_threads_; mutable shared_mutex threads_lock_; thread_pool::exception_handler exception_; // struct interrupt { // static void raise ( ) { throw interrupt( ); } // }; impl( basio::io_service *ios, bool own_ios ) :ios_(ios) ,wrk_(new basio::io_service::work(*ios_)) ,own_ios_(own_ios) ,exception_(&exception_default) { } ~impl( ) { try { if( wrk_ ) { stop( ); } join_all( ); } catch( ... ) { ;;; } if( own_ios_ ) { delete ios_; } } void add( size_t count ) { std::list<thread_context::shared_type> tmp; while( count-- ) { tmp.push_back(create_thread( )); } unique_shared_lock lck(threads_lock_); threads_.insert( tmp.begin( ), tmp.end( ) ); stopped_threads_.clear( ); } void inc( ) { thread_context::shared_type n(create_thread( )); unique_shared_lock lck( threads_lock_ ); threads_.insert( n ); stopped_threads_.clear( ); } thread_context::shared_type create_thread( ) { thread_context::shared_type new_inst( vtrc::make_shared<thread_context>( )); new_inst->thread_.reset( new vtrc::thread(vtrc::bind(&impl::run, this, new_inst))); return new_inst; } // void interrupt_one( ) // { // ios_->post( interrupt::raise ); // } size_t size( ) const { shared_lock lck(threads_lock_); return threads_.size( ); } static bool is_this_id( const thread_ptr &th ) { return vtrc::this_thread::get_id( ) == th->get_id( ); } void join_all( ) { typedef thread_set_type::iterator iterator; thread_set_type tmp; { /// own threads unique_shared_lock lck(threads_lock_); tmp.swap( threads_ ); } /// join for(iterator b(tmp.begin( )), e(tmp.end( )); b!=e; ++b ) { if( (*b)->thread_->joinable( ) && !is_this_id( (*b)->thread_) ) (*b)->thread_->join( ); } /// clean stopped unique_shared_lock lck(threads_lock_); stopped_threads_.clear( ); } void stop( ) { delete wrk_; wrk_ = NULL; ios_->stop( ); unique_shared_lock lck(threads_lock_); stopped_threads_.clear( ); } void move_to_stopped( thread_context::shared_type &thread ) { unique_shared_lock lck(threads_lock_); stopped_threads_.insert( thread ); threads_.erase( thread ); } void run( thread_context::shared_type thread ) { run_impl( thread.get( ) ); // move_to_stopped( thread ); /// must not remove it here; // /// moving to stopped_thread_ } bool run_impl( thread_context * /*context*/ ) { while ( true ) { try { while ( true ) { const size_t count = ios_->run_one( ); if( !count ) return true; /// stopped; } // } catch( const interrupt & ) { // break; } catch( ... ) { exception_( ); } } return false; /// interruped by interrupt::raise or /// boost::thread_interrupted } bool attach( ) { return run_impl( NULL ); } }; thread_pool::thread_pool( ) :impl_(new impl(new basio::io_service, true)) { } thread_pool::thread_pool( size_t init_count ) :impl_(new impl(new basio::io_service, true)) { impl_->add( init_count ); } thread_pool::thread_pool( VTRC_ASIO::io_service &ios, size_t init_count ) :impl_(new impl(&ios, false)) { impl_->add( init_count ); } thread_pool::thread_pool( VTRC_ASIO::io_service &ios ) :impl_(new impl(&ios, false)) { } thread_pool::~thread_pool( ) { delete impl_; } size_t thread_pool::size( ) const { return impl_->size( ); } // void thread_pool::interrupt_one( ) // { // impl_->interrupt_one( ); // } void thread_pool::stop( ) { impl_->stop( ); } void thread_pool::join_all( ) { impl_->join_all( ); } void thread_pool::assign_exception_handler( exception_handler eh ) { impl_->exception_ = eh ? eh : exception_default; } bool thread_pool::attach( ) { return impl_->attach( ); } void thread_pool::add_thread( ) { impl_->inc( ); } void thread_pool::add_threads( size_t count ) { impl_->add(count); } VTRC_ASIO::io_service &thread_pool::get_io_service( ) { return *impl_->ios_; } const VTRC_ASIO::io_service &thread_pool::get_io_service( ) const { return *impl_->ios_; } }} <commit_msg>thread pool<commit_after>#include <list> #include <set> #include <iostream> #include "vtrc-asio.h" #include "vtrc-thread-pool.h" #include "vtrc-mutex-typedefs.h" #include "vtrc-memory.h" #include "vtrc-bind.h" #include "vtrc-thread.h" ///// TODO: need some fix here namespace vtrc { namespace common { namespace basio = VTRC_ASIO; typedef vtrc::unique_ptr<vtrc::thread> thread_ptr; struct thread_context { typedef vtrc::shared_ptr<thread_context> shared_type; thread_ptr thread_; }; inline bool operator < ( const thread_context &l, const thread_context &r ) { return l.thread_.get( ) < r.thread_.get( ); } static void exception_default( ) { try { throw; } catch( const std::exception &ex ) { std::cerr << "Exception in thread 0x" << std::hex << vtrc::this_thread::get_id( ) << ". what = " << ex.what( ) ; } catch( ... ) { std::cerr << "Exception '...' in thread 0x" << std::hex << vtrc::this_thread::get_id( ) ; } } typedef std::set<thread_context::shared_type> thread_set_type; #if 0 struct thread_pool::impl_ { basio::io_service *ios_; basio::io_service::work *wrk_; bool own_ios_; thread_pool::exception_handler exception_; thread_set_type threads_; impl( basio::io_service *ios, bool own_ios ) :ios_(ios) ,wrk_(new basio::io_service::work(*ios_)) ,own_ios_(own_ios) ,exception_(&exception_default) { } ~impl( ) { try { if( wrk_ ) { stop( ); } join_all( ); } catch( ... ) { ;;; } if( own_ios_ ) { delete ios_; } } void add( size_t count ) { std::list<thread_context::shared_type> tmp; while( count-- ) { tmp.push_back(create_thread( )); } unique_shared_lock lck(threads_lock_); threads_.insert( tmp.begin( ), tmp.end( ) ); stopped_threads_.clear( ); } thread_context::shared_type create_thread( ) { thread_context::shared_type new_inst( vtrc::make_shared<thread_context>( )); new_inst->thread_.reset( new vtrc::thread(vtrc::bind(&impl::run, this, new_inst))); return new_inst; } }; #endif struct thread_pool::impl { basio::io_service *ios_; basio::io_service::work *wrk_; bool own_ios_; thread_set_type threads_; thread_set_type stopped_threads_; mutable shared_mutex threads_lock_; thread_pool::exception_handler exception_; // struct interrupt { // static void raise ( ) { throw interrupt( ); } // }; impl( basio::io_service *ios, bool own_ios ) :ios_(ios) ,wrk_(new basio::io_service::work(*ios_)) ,own_ios_(own_ios) ,exception_(&exception_default) { } ~impl( ) { try { if( wrk_ ) { stop( ); } join_all( ); } catch( ... ) { ;;; } if( own_ios_ ) { delete ios_; } } void add( size_t count ) { std::list<thread_context::shared_type> tmp; while( count-- ) { tmp.push_back(create_thread( )); } unique_shared_lock lck(threads_lock_); threads_.insert( tmp.begin( ), tmp.end( ) ); stopped_threads_.clear( ); } void inc( ) { thread_context::shared_type n(create_thread( )); unique_shared_lock lck( threads_lock_ ); threads_.insert( n ); stopped_threads_.clear( ); } thread_context::shared_type create_thread( ) { thread_context::shared_type new_inst( vtrc::make_shared<thread_context>( )); new_inst->thread_.reset( new vtrc::thread(vtrc::bind(&impl::run, this, new_inst))); return new_inst; } // void interrupt_one( ) // { // ios_->post( interrupt::raise ); // } size_t size( ) const { shared_lock lck(threads_lock_); return threads_.size( ); } static bool is_this_id( const thread_ptr &th ) { return vtrc::this_thread::get_id( ) == th->get_id( ); } void join_all( ) { typedef thread_set_type::iterator iterator; thread_set_type tmp; { /// own threads unique_shared_lock lck(threads_lock_); tmp.swap( threads_ ); } /// join for(iterator b(tmp.begin( )), e(tmp.end( )); b!=e; ++b ) { if( (*b)->thread_->joinable( ) && !is_this_id( (*b)->thread_) ) (*b)->thread_->join( ); } /// clean stopped unique_shared_lock lck(threads_lock_); stopped_threads_.clear( ); } void stop( ) { delete wrk_; wrk_ = NULL; ios_->stop( ); unique_shared_lock lck(threads_lock_); stopped_threads_.clear( ); } void move_to_stopped( thread_context::shared_type &thread ) { unique_shared_lock lck(threads_lock_); stopped_threads_.insert( thread ); threads_.erase( thread ); } void run( thread_context::shared_type thread ) { run_impl( thread.get( ) ); // move_to_stopped( thread ); /// must not remove it here; // /// moving to stopped_thread_ } bool run_impl( thread_context * /*context*/ ) { while ( true ) { try { while ( true ) { const size_t count = ios_->run_one( ); if( !count ) return true; /// stopped; } // } catch( const interrupt & ) { // break; } catch( ... ) { exception_( ); } } return false; /// interruped by interrupt::raise or /// boost::thread_interrupted } bool attach( ) { return run_impl( NULL ); } }; thread_pool::thread_pool( ) :impl_(new impl(new basio::io_service, true)) { } thread_pool::thread_pool( size_t init_count ) :impl_(new impl(new basio::io_service, true)) { impl_->add( init_count ); } thread_pool::thread_pool( VTRC_ASIO::io_service &ios, size_t init_count ) :impl_(new impl(&ios, false)) { impl_->add( init_count ); } thread_pool::thread_pool( VTRC_ASIO::io_service &ios ) :impl_(new impl(&ios, false)) { } thread_pool::~thread_pool( ) { delete impl_; } size_t thread_pool::size( ) const { return impl_->size( ); } // void thread_pool::interrupt_one( ) // { // impl_->interrupt_one( ); // } void thread_pool::stop( ) { impl_->stop( ); } void thread_pool::join_all( ) { impl_->join_all( ); } void thread_pool::assign_exception_handler( exception_handler eh ) { impl_->exception_ = eh ? eh : exception_default; } bool thread_pool::attach( ) { return impl_->attach( ); } void thread_pool::add_thread( ) { impl_->inc( ); } void thread_pool::add_threads( size_t count ) { impl_->add(count); } VTRC_ASIO::io_service &thread_pool::get_io_service( ) { return *impl_->ios_; } const VTRC_ASIO::io_service &thread_pool::get_io_service( ) const { return *impl_->ios_; } }} <|endoftext|>
<commit_before>// ****************************************************************************************** // * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com * // ****************************************************************************************** #define playerMenuDialog 55500 #define playerMenuPlayerSkin 55501 #define playerMenuPlayerGun 55502 #define playerMenuPlayerItems 55503 #define playerMenuPlayerPos 55504 #define playerMenuPlayerList 55505 #define playerMenuSpectateButton 55506 #define playerMenuPlayerObject 55507 #define playerMenuPlayerHealth 55508 #define playerMenuWarnMessage 55509 #define playerMenuPlayerUID 55510 #define playerMenuPlayerBank 55511 class PlayersMenu { idd = playerMenuDialog; movingEnable = false; enableSimulation = true; class controlsBackground { class MainBackground: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.60 * safezoneW; h = 0.661111 * safezoneH; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.45,0.005,0,1)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.60 * safezoneW; h = 0.05 * safezoneH; }; class DialogTitleText: w_RscText { idc = -1; text = "Player Menu"; font = "PuristaMedium"; sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; x = 0.20 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.0844792 * safezoneW; h = 0.0448148 * safezoneH; }; class PlayerUIDText: w_RscText { idc = playerMenuPlayerUID; text = "UID:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.215 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerObjectText: w_RscText { idc = playerMenuPlayerObject; text = "Slot:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.235 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerSkinText: w_RscText { idc = playerMenuPlayerSkin; text = "Skin:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.255 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerGunText: w_RscText { idc = playerMenuPlayerGun; text = "Money:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.275 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerBankText: w_RscText { idc = playerMenuPlayerBank; text = "Money:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.295 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerItemsText: w_RscText { idc = playerMenuPlayerItems; text = "Items:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.315 * safezoneH + safezoneY; w = 0.40 * safezoneW; h = 0.04 * safezoneH; }; class PlayerHealthText: w_RscText { idc = playerMenuPlayerHealth; text = "Health:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.335 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerPosistionText: w_RscText { idc = playerMenuPlayerPos; text = "Position:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.355 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; }; class controls { class PlayerEditBox:w_RscEdit { idc=playerMenuWarnMessage; x = 0.60 * safezoneW + safezoneX; y = 0.745 * safezoneH + safezoneY; w = 0.175 * safezoneW; h = 0.045 * safezoneH; colorDisabled[] = {1,1,1,0.3}; }; class PlayerListBox: w_RscList { idc = playerMenuPlayerList; onLBSelChanged="[2,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";"; x = 0.2 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.315 * safezoneW; h = 0.45 * safezoneH; }; class SpectateButton: w_RscButton { idc = playerMenuSpectateButton; text = "Spectate"; onButtonClick = "[0] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.2 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class SlayButton: w_RscButton { idc = -1; text = "Slay"; onButtonClick = "[2] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.2 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class UnlockTeamSwitchButton: w_RscButton { idc = -1; text = "Unlock Team Switch"; onButtonClick = "[3] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.255 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.11 * safezoneW; h = 0.04 * safezoneH; }; class UnlockTeamKillerButton: w_RscButton { idc = -1; text = "Unlock Team Kill"; onButtonClick = "[4] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.255 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.11 * safezoneW; h = 0.04 * safezoneH; }; class RemoveAllMoneyButton: w_RscButton { idc = -1; text = "Remove Money"; onButtonClick = "[5] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.3705 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.105 * safezoneW; h = 0.04 * safezoneH; }; class RemoveAllWeaponsButton: w_RscButton { idc = -1; text = "Remove All"; onButtonClick = "[6] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.3705 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.105 * safezoneW; h = 0.04 * safezoneH; }; class CheckPlayerGearButton: w_RscButton { idc = -1; text = "Hurt"; onButtonClick = "[7] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.482 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class WarnButton: w_RscButton { idc = -1; text = "Warn"; onButtonClick = "[1] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.600 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; /* class KickButton: w_RscButton { idc = -1; text = "Kick"; onButtonClick = "[8] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.625 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; */ }; }; <commit_msg>Resize<commit_after>// ****************************************************************************************** // * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com * // ****************************************************************************************** #define playerMenuDialog 55500 #define playerMenuPlayerSkin 55501 #define playerMenuPlayerGun 55502 #define playerMenuPlayerItems 55503 #define playerMenuPlayerPos 55504 #define playerMenuPlayerList 55505 #define playerMenuSpectateButton 55506 #define playerMenuPlayerObject 55507 #define playerMenuPlayerHealth 55508 #define playerMenuWarnMessage 55509 #define playerMenuPlayerUID 55510 #define playerMenuPlayerBank 55511 class PlayersMenu { idd = playerMenuDialog; movingEnable = false; enableSimulation = true; class controlsBackground { class MainBackground: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.60 * safezoneW; h = 0.661111 * safezoneH; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.45,0.005,0,1)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.60 * safezoneW; h = 0.05 * safezoneH; }; class DialogTitleText: w_RscText { idc = -1; text = "Player Menu"; font = "PuristaMedium"; sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; x = 0.20 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.0844792 * safezoneW; h = 0.0448148 * safezoneH; }; class PlayerUIDText: w_RscText { idc = playerMenuPlayerUID; text = "UID:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.215 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerObjectText: w_RscText { idc = playerMenuPlayerObject; text = "Slot:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.235 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerSkinText: w_RscText { idc = playerMenuPlayerSkin; text = "Skin:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.255 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerGunText: w_RscText { idc = playerMenuPlayerGun; text = "Money:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.275 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerBankText: w_RscText { idc = playerMenuPlayerBank; text = "Money:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.295 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerItemsText: w_RscText { idc = playerMenuPlayerItems; text = "Items:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.315 * safezoneH + safezoneY; w = 0.40 * safezoneW; h = 0.04 * safezoneH; }; class PlayerHealthText: w_RscText { idc = playerMenuPlayerHealth; text = "Health:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.335 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; class PlayerPosistionText: w_RscText { idc = playerMenuPlayerPos; text = "Position:"; sizeEx = 0.030; x = 0.52 * safezoneW + safezoneX; y = 0.355 * safezoneH + safezoneY; w = 0.25 * safezoneW; h = 0.04 * safezoneH; }; }; class controls { class PlayerEditBox:w_RscEdit { idc=playerMenuWarnMessage; x = 0.60 * safezoneW + safezoneX; y = 0.745 * safezoneH + safezoneY; w = 0.175 * safezoneW; h = 0.045 * safezoneH; colorDisabled[] = {1,1,1,0.3}; }; class PlayerListBox: w_RscList { idc = playerMenuPlayerList; onLBSelChanged="[2,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";"; x = 0.2 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.315 * safezoneW; h = 0.45 * safezoneH; }; class SpectateButton: w_RscButton { idc = playerMenuSpectateButton; text = "Spectate"; onButtonClick = "[0] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.2 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class SlayButton: w_RscButton { idc = -1; text = "Slay"; onButtonClick = "[2] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.2 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class UnlockTeamSwitchButton: w_RscButton { idc = -1; text = "Unlock Team Switch"; onButtonClick = "[3] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.255 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.11 * safezoneW; h = 0.04 * safezoneH; }; class UnlockTeamKillerButton: w_RscButton { idc = -1; text = "Unlock Team Kill"; onButtonClick = "[4] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.255 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.11 * safezoneW; h = 0.04 * safezoneH; }; class RemoveAllMoneyButton: w_RscButton { idc = -1; text = "Remove Money"; onButtonClick = "[5] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.3705 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.105 * safezoneW; h = 0.04 * safezoneH; }; class RemoveAllWeaponsButton: w_RscButton { idc = -1; text = "Remove All"; onButtonClick = "[6] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.3705 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.105 * safezoneW; h = 0.04 * safezoneH; }; class CheckPlayerGearButton: w_RscButton { idc = -1; text = "Hurt"; onButtonClick = "[7] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.482 * safezoneW + safezoneX; y = 0.748 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class WarnButton: w_RscButton { idc = -1; text = "Warn"; onButtonClick = "[1] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.600 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; class KickButton: w_RscButton { idc = -1; text = "Kick"; onButtonClick = "[8] execVM 'client\systems\adminPanel\playerSelect.sqf'"; x = 0.675 * safezoneW + safezoneX; y = 0.70 * safezoneH + safezoneY; w = 0.05 * safezoneW; h = 0.04 * safezoneH; }; }; }; <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge Torrent"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_id(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) identity << i->name; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>added clients to identify_client<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge Torrent"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_id(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) identity << i->name; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "Pando-")) return "Pando"; if (find_string(PID, "LIME")) return "LimeWire"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "DNA")) return "BitTorrent DNA"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014 Colin Wallace * * 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 "servo.h" #include "testhelper.h" namespace iodrv { void Servo::setServoAngleDegrees(float angle) { highTime = getOnTime(angle); } OutputEvent Servo::peekNextEvent() const { bool nextState = !curState; EventClockT::time_point nextEventTime = lastEventTime + (nextState ? highTime : (cycleLength-highTime)); return OutputEvent(nextEventTime, pin, nextState); } void Servo::consumeNextEvent() { OutputEvent evt = peekNextEvent(); this->curState = evt.state(); this->lastEventTime = evt.time(); } EventClockT::duration Servo::getOnTime(float angle) { //clamp the angle //angle = std::min(minMaxAngle.second, std::max(minMaxAngle.first, angle)); angle = mathutil::clamp(angle, minAngle, maxAngle); //calculate proportion, p, such that angle = angleMin + p*(angleMax-angleMin) float proportion = (angle-minAngle) / (maxAngle - minAngle); //This proportion now nicely maps to the linear scale, [minOnTime, maxOnTime] float fsec = std::chrono::duration<float>(minOnTime).count() + proportion*std::chrono::duration<float>(maxOnTime - minOnTime).count(); return std::chrono::duration_cast<EventClockT::duration>(std::chrono::duration<float>(fsec)); } struct ServoTester { ServoTester() { GIVEN("A TestHelper & IoDrivers tuple") { //create the ioDrivers auto ioDrivers = std::make_tuple( iodrv::Servo(iodrv::IoPin(iodrv::NO_INVERSIONS, iodrv::IoPin::null().primitiveIoPin()), std::chrono::milliseconds(100), //cycle length std::make_pair(std::chrono::milliseconds(1), std::chrono::milliseconds(5)), //min/max duty cycle std::make_pair(0, 360) //min/max angle ), iodrv::IODriver(), iodrv::IODriver(), iodrv::Servo(iodrv::IoPin(iodrv::INVERT_WRITES, iodrv::IoPin::null().primitiveIoPin()), std::chrono::milliseconds(100), //cycle length std::make_pair(std::chrono::milliseconds(2), std::chrono::milliseconds(4)), //min/max duty cycle std::make_pair(90, 180) //min/max angle ), iodrv::IODriver() ); //only give the State references to the ioDrivers so that we can track changes without private member access auto getIoDrivers = [&]() { return std::tie(std::get<0>(ioDrivers)); }; auto helper = makeTestHelper(makeTestMachine(getIoDrivers)); WHEN("Servo0 is set to 90 degrees") { helper.sendCommand("M280 P0 S90.0", "ok"); THEN("Its highTime should be 2 us (25% interpolation of 1, 5)") { helper.requireTimesApproxEqual(std::get<0>(ioDrivers).highTime, std::chrono::milliseconds(2)); } } } } }; SCENARIO("Servo will behave correctly", "[servo]") { ServoTester(); } }<commit_msg>Add more servo tests<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014 Colin Wallace * * 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 "servo.h" #include "testhelper.h" namespace iodrv { void Servo::setServoAngleDegrees(float angle) { highTime = getOnTime(angle); } OutputEvent Servo::peekNextEvent() const { bool nextState = !curState; EventClockT::time_point nextEventTime = lastEventTime + (nextState ? highTime : (cycleLength-highTime)); return OutputEvent(nextEventTime, pin, nextState); } void Servo::consumeNextEvent() { OutputEvent evt = peekNextEvent(); this->curState = evt.state(); this->lastEventTime = evt.time(); } EventClockT::duration Servo::getOnTime(float angle) { //clamp the angle //angle = std::min(minMaxAngle.second, std::max(minMaxAngle.first, angle)); angle = mathutil::clamp(angle, minAngle, maxAngle); //calculate proportion, p, such that angle = angleMin + p*(angleMax-angleMin) float proportion = (angle-minAngle) / (maxAngle - minAngle); //This proportion now nicely maps to the linear scale, [minOnTime, maxOnTime] float fsec = std::chrono::duration<float>(minOnTime).count() + proportion*std::chrono::duration<float>(maxOnTime - minOnTime).count(); return std::chrono::duration_cast<EventClockT::duration>(std::chrono::duration<float>(fsec)); } struct ServoTester { ServoTester() { GIVEN("A TestHelper & IoDrivers tuple") { //create the ioDrivers auto ioDrivers = std::make_tuple( iodrv::Servo(iodrv::IoPin(iodrv::NO_INVERSIONS, iodrv::IoPin::null().primitiveIoPin()), std::chrono::milliseconds(100), //cycle length std::make_pair(std::chrono::milliseconds(1), std::chrono::milliseconds(5)), //min/max duty cycle std::make_pair(0, 360), //min/max angle 0 //default angle ), iodrv::IODriver(), iodrv::IODriver(), iodrv::Servo(iodrv::IoPin(iodrv::INVERT_WRITES, iodrv::IoPin::null().primitiveIoPin()), std::chrono::milliseconds(100), //cycle length std::make_pair(std::chrono::milliseconds(2), std::chrono::milliseconds(3)), //min/max duty cycle std::make_pair(90, 180), //min/max angle 180 //default angle ), iodrv::IODriver() ); //only give the State references to the ioDrivers so that we can track changes without private member access auto getIoDrivers = [&]() { return std::tie(std::get<0>(ioDrivers)); }; auto helper = makeTestHelper(makeTestMachine(getIoDrivers)); WHEN("Servo0 is set to 90 degrees") { helper.sendCommand("M280 P0 S90.0", "ok"); THEN("Its highTime should be 2 ms (25% interpolation of 1, 5) and other servos should not have been affected") { helper.requireTimesApproxEqual(std::get<0>(ioDrivers).highTime, std::chrono::milliseconds(2)); helper.requireTimesApproxEqual(std::get<3>(ioDrivers).highTime, std::chrono::milliseconds(3)); } } WHEN("Servo1 is set to 135 degrees") { helper.sendCommand("M280 P1 S135", "ok"); THEN("Its highTime should be 2.5 ms (50% interpolation of 2, 3) and other servos should not have been affected") { helper.requireTimesApproxEqual(std::get<0>(ioDrivers).highTime, std::chrono::milliseconds(1)); helper.requireTimesApproxEqual(std::get<3>(ioDrivers).highTime, std::chrono::microseconds(2500)); } } } } }; SCENARIO("Servo will behave correctly", "[servo]") { ServoTester(); } }<|endoftext|>
<commit_before>int main() { } <commit_msg>Flush out jitpp-dis a little<commit_after>#include <getopt.h> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> const char *binary_type_str = nullptr; const char *machine_type_str = nullptr; const char *binary_name = nullptr; enum MachineType { TYPE_PPC, TYPE_ARM, }; enum PpcFlags { }; enum ArmFlags { }; struct MachineOption { const char *short_name; const char *long_name; int machine; uint64_t flags; }; const MachineOption predefined_options[] = { "ppc", "PowerPC", TYPE_PPC, 0, "arm", "ARM", TYPE_ARM, 0, }; static void parse_args( int argc, char **argv ) { int option_index = 0; static struct option long_options[] = { { "binary-type", required_argument, 0, 'b' }, { "machine-type", required_argument, 0, 'm' }, }; while( true ) { int c = getopt_long(argc, argv, "b:m:", long_options, &option_index); if( c == -1 ) { break; } switch( c ) { case 'b': binary_type_str = optarg; break; case 'm': machine_type_str = optarg; break; case '?': exit( 1 ); default: exit( 1 ); } } while( optind < argc ) { if( nullptr == binary_name ) { binary_name = argv[optind++]; } else { fprintf( stderr, "Error: Multiple binary files specified\n" ); exit( 1 ); } } } const MachineOption* find_machine_option_for_str( const char *str ) { const int num_machine_types = sizeof(predefined_options) / sizeof(MachineOption); for( int ii = 0; ii < num_machine_types; ii++ ) { if( strcmp(str, predefined_options[ii].short_name) == 0 ) { return &predefined_options[ii]; } } return nullptr; } void print_possible_machines() { const int num_machine_types = sizeof(predefined_options) / sizeof(MachineOption); for( int ii = 0; ii < num_machine_types; ii++ ) { printf( "%10s - %s\n", predefined_options[ii].short_name, predefined_options[ii].long_name ); } } int main( int argc, char **argv ) { parse_args( argc, argv ); if( machine_type_str == nullptr ) { fprintf( stderr, "Error: No machine type specified\n" ); exit( 1 ); } if( strcmp(machine_type_str, "?") == 0 ) { print_possible_machines(); exit( 0 ); } auto machine = find_machine_option_for_str( machine_type_str ); if( nullptr == machine ) { fprintf( stderr, "Error: Unknown machine type \"%s\"\n", machine_type_str ); exit( 1 ); } if( nullptr == binary_name ) { fprintf( stderr, "Error: No binary specified\n" ); exit( 1 ); } printf( "Binary: %s\n", binary_name ); return 0; } <|endoftext|>
<commit_before>#include "best_constant.h" bool is_more_than_two_labels_observed = false; float first_observed_label = FLT_MAX; float second_observed_label = FLT_MAX; bool get_best_constant(vw& all, float& best_constant, float& best_constant_loss) { if ( first_observed_label == FLT_MAX || // no non-test labels observed or function was never called (all.loss == nullptr) || (all.sd == nullptr)) return false; float label1 = first_observed_label; // observed labels might be inside [sd->Min_label, sd->Max_label], so can't use Min/Max float label2 = (second_observed_label == FLT_MAX)?0:second_observed_label; // if only one label observed, second might be 0 if (label1 > label2) {float tmp = label1; label1 = label2; label2 = tmp;} // as don't use min/max - make sure label1 < label2 float label1_cnt; float label2_cnt; if (label1 != label2) { float weighted_labeled_examples = (float)(all.sd->weighted_examples - all.sd->weighted_unlabeled_examples + all.initial_t); label1_cnt = (float) (all.sd->weighted_labels - label2*weighted_labeled_examples)/(label1 - label2); label2_cnt = weighted_labeled_examples - label1_cnt; } else return false; if ( (label1_cnt + label2_cnt) <= 0.) return false; po::parsed_options pos = po::command_line_parser(all.args). style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing). options(all.opts).allow_unregistered().run(); po::variables_map vm = po::variables_map(); po::store(pos, vm); po::notify(vm); string funcName; if(vm.count("loss_function")) funcName = vm["loss_function"].as<string>(); else funcName = "squared"; if(funcName.compare("squared") == 0 || funcName.compare("Huber") == 0 || funcName.compare("classic") == 0) { best_constant = (float) all.sd->weighted_labels / (float) (all.sd->weighted_examples - all.sd->weighted_unlabeled_examples + all.initial_t); //GENERIC. WAS: (label1*label1_cnt + label2*label2_cnt) / (label1_cnt + label2_cnt); } else if (is_more_than_two_labels_observed) { //loss functions below don't have generic formuas for constant yet. return false; } else if(funcName.compare("hinge") == 0) { best_constant = label2_cnt <= label1_cnt ? -1.f: 1.f; } else if(funcName.compare("logistic") == 0) { label1 = -1.; //override {-50, 50} to get proper loss label2 = 1.; if (label1_cnt <= 0) best_constant = 1.; else if (label2_cnt <= 0) best_constant = -1.; else best_constant = log(label2_cnt/label1_cnt); } else if(funcName.compare("quantile") == 0 || funcName.compare("pinball") == 0 || funcName.compare("absolute") == 0) { float tau = 0.5; if(vm.count("quantile_tau")) tau = vm["quantile_tau"].as<float>(); float q = tau*(label1_cnt + label2_cnt); if (q < label2_cnt) best_constant = label2; else best_constant = label1; } else return false; if (!is_more_than_two_labels_observed) best_constant_loss = ( all.loss->getLoss(all.sd, best_constant, label1) * label1_cnt + all.loss->getLoss(all.sd, best_constant, label2) * label2_cnt ) / (label1_cnt + label2_cnt); else best_constant_loss = FLT_MIN; return true; } <commit_msg>use all.vm reference<commit_after>#include "best_constant.h" bool is_more_than_two_labels_observed = false; float first_observed_label = FLT_MAX; float second_observed_label = FLT_MAX; bool get_best_constant(vw& all, float& best_constant, float& best_constant_loss) { if ( first_observed_label == FLT_MAX || // no non-test labels observed or function was never called (all.loss == nullptr) || (all.sd == nullptr)) return false; float label1 = first_observed_label; // observed labels might be inside [sd->Min_label, sd->Max_label], so can't use Min/Max float label2 = (second_observed_label == FLT_MAX)?0:second_observed_label; // if only one label observed, second might be 0 if (label1 > label2) {float tmp = label1; label1 = label2; label2 = tmp;} // as don't use min/max - make sure label1 < label2 float label1_cnt; float label2_cnt; if (label1 != label2) { float weighted_labeled_examples = (float)(all.sd->weighted_examples - all.sd->weighted_unlabeled_examples + all.initial_t); label1_cnt = (float) (all.sd->weighted_labels - label2*weighted_labeled_examples)/(label1 - label2); label2_cnt = weighted_labeled_examples - label1_cnt; } else return false; if ( (label1_cnt + label2_cnt) <= 0.) return false; po::variables_map& vm = all.vm; string funcName; if(vm.count("loss_function")) funcName = vm["loss_function"].as<string>(); else funcName = "squared"; if(funcName.compare("squared") == 0 || funcName.compare("Huber") == 0 || funcName.compare("classic") == 0) { best_constant = (float) all.sd->weighted_labels / (float) (all.sd->weighted_examples - all.sd->weighted_unlabeled_examples + all.initial_t); //GENERIC. WAS: (label1*label1_cnt + label2*label2_cnt) / (label1_cnt + label2_cnt); } else if (is_more_than_two_labels_observed) { //loss functions below don't have generic formuas for constant yet. return false; } else if(funcName.compare("hinge") == 0) { best_constant = label2_cnt <= label1_cnt ? -1.f: 1.f; } else if(funcName.compare("logistic") == 0) { label1 = -1.; //override {-50, 50} to get proper loss label2 = 1.; if (label1_cnt <= 0) best_constant = 1.; else if (label2_cnt <= 0) best_constant = -1.; else best_constant = log(label2_cnt/label1_cnt); } else if(funcName.compare("quantile") == 0 || funcName.compare("pinball") == 0 || funcName.compare("absolute") == 0) { float tau = 0.5; if(vm.count("quantile_tau")) tau = vm["quantile_tau"].as<float>(); float q = tau*(label1_cnt + label2_cnt); if (q < label2_cnt) best_constant = label2; else best_constant = label1; } else return false; if (!is_more_than_two_labels_observed) best_constant_loss = ( all.loss->getLoss(all.sd, best_constant, label1) * label1_cnt + all.loss->getLoss(all.sd, best_constant, label2) * label2_cnt ) / (label1_cnt + label2_cnt); else best_constant_loss = FLT_MIN; return true; } <|endoftext|>
<commit_before>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <fstream> #include <float.h> #ifndef _WIN32 #include <netdb.h> #endif #include <string.h> #include <stdio.h> #include <assert.h> #include <sys/timeb.h> #include "parse_example.h" #include "constant.h" #include "cache.h" #include "simple_label.h" #include "vw.h" #include "gd.h" #include "accumulate.h" #include "memory.h" #include <exception> using namespace std; using namespace LEARNER; #define W_XT 0 // current parameter w(XT) #define W_GT 1 // current gradient g(GT) #define W_ZT 2 // accumulated z(t) = z(t-1) + g(t) + sigma*w(t) #define W_G2 3 // accumulated gradient squre n(t) = n(t-1) + g(t)*g(t) /********************************************************************/ /* mem & w definition ***********************************************/ /********************************************************************/ // w[0] = current weight // w[1] = current first derivative // w[2] = accumulated zt // w[3] = accumulated g2 namespace FTRL { //nonrentrant struct ftrl { vw* all; // set by initializer // evaluation file pointer FILE* fo; bool progressive_validation; }; void update_accumulated_state(weight* w, float alpha) { double ng2 = w[W_G2] + w[W_GT]*w[W_GT]; double sigma = (sqrt(ng2) - sqrt(w[W_G2]))/ alpha; w[W_ZT] += w[W_GT] - sigma * w[W_XT]; w[W_G2] = ng2; } // use in gradient prediction void quad_grad_update(weight* weights, feature& page_feature, v_array<feature> &offer_features, size_t mask, float g, float alpha) { size_t halfhash = quadratic_constant * page_feature.weight_index; float update = g * page_feature.x; for (feature* ele = offer_features.begin; ele != offer_features.end; ele++) { weight* w=&weights[(halfhash + ele->weight_index) & mask]; w[W_GT] = update * ele->x; update_accumulated_state(w, alpha); } } void cubic_grad_update(weight* weights, feature& f0, feature& f1, v_array<feature> &cross_features, size_t mask, float g, float alpha) { size_t halfhash = cubic_constant2 * (cubic_constant * f0.weight_index + f1.weight_index); float update = g * f0.x * f1.x; for (feature* ele = cross_features.begin; ele != cross_features.end; ele++) { weight* w=&weights[(halfhash + ele->weight_index) & mask]; w[W_GT] = update * ele->x; update_accumulated_state(w, alpha); } } float ftrl_predict(vw& all, example& ec) { ec.partial_prediction = GD::inline_predict(all, ec); return GD::finalize_prediction(all.sd, ec.partial_prediction); } float predict_and_gradient(vw& all, example& ec) { float fp = ftrl_predict(all, ec); ec.updated_prediction = fp; //label_data* ld = (label_data*)ec.ld; label_data& ld = ec.l.simple; all.set_minmax(all.sd, ld.label); float loss_grad = all.loss->first_derivative(all.sd, fp, ld.label) * ld.weight; size_t mask = all.reg.weight_mask; weight* weights = all.reg.weight_vector; for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) { feature *f = ec.atomics[*i].begin; for (; f != ec.atomics[*i].end; f++) { weight* w = &weights[f->weight_index & mask]; w[W_GT] = loss_grad * f->x; // += -> = update_accumulated_state(w, all.ftrl_alpha); } } // bi-gram feature for (vector<string>::iterator i = all.pairs.begin(); i != all.pairs.end(); i++) { if (ec.atomics[(int)(*i)[0]].size() > 0) { v_array<feature> temp = ec.atomics[(int)(*i)[0]]; for (; temp.begin != temp.end; temp.begin++) quad_grad_update(weights, *temp.begin, ec.atomics[(int)(*i)[1]], mask, loss_grad, all.ftrl_alpha); } } // tri-gram feature for (vector<string>::iterator i = all.triples.begin(); i != all.triples.end();i++) { if ((ec.atomics[(int)(*i)[0]].size() == 0) || (ec.atomics[(int)(*i)[1]].size() == 0) || (ec.atomics[(int)(*i)[2]].size() == 0)) { continue; } v_array<feature> temp1 = ec.atomics[(int)(*i)[0]]; for (; temp1.begin != temp1.end; temp1.begin++) { v_array<feature> temp2 = ec.atomics[(int)(*i)[1]]; for (; temp2.begin != temp2.end; temp2.begin++) cubic_grad_update(weights, *temp1.begin, *temp2.begin, ec.atomics[(int)(*i)[2]], mask, loss_grad, all.ftrl_alpha); } } return fp; } inline float sign(float w){ if (w < 0.) return -1.; else return 1.;} void update_weight(vw& all, example& ec) { size_t mask = all.reg.weight_mask; weight* weights = all.reg.weight_vector; for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) { feature *f = ec.atomics[*i].begin; for (; f != ec.atomics[*i].end; f++) { weight* w = &weights[f->weight_index & mask]; float flag = sign(w[W_ZT]); float fabs_zt = w[W_ZT] * flag; if (fabs_zt <= all.l1_lambda) { w[W_XT] = 0.; } else { double step = 1/(all.l2_lambda + (all.ftrl_beta + sqrt(w[W_G2]))/all.ftrl_alpha); w[W_XT] = step * flag * (all.l1_lambda - fabs_zt); } } } } void evaluate_example(vw& all, ftrl& b , example& ec) { //label_data* ld = (label_data*)ec.ld; label_data& ld = ec.l.simple; ec.loss = all.loss->getLoss(all.sd, ec.updated_prediction, ld.label) * ld.weight; if (b.progressive_validation) { float v = 1./(1 + exp(-ec.updated_prediction)); fprintf(b.fo, "%.6f\t%d\n", v, (int)(ld.label * ld.weight)); } } //void learn(void* a, void* d, example* ec) { void learn(ftrl& a, learner& base, example& ec) { vw* all = a.all; assert(ec.in_use); // predict w*x, compute gradient, update accumulate state predict_and_gradient(*all, ec); // evaluate, statistic evaluate_example(*all, a, ec); // update weight update_weight(*all, ec); } void save_load_online_state(vw& all, io_buf& model_file, bool read, bool text) { char buff[512]; int text_len = sprintf(buff, "sum_loss %f\n", all.sd->sum_loss); bin_text_read_write_fixed(model_file,(char*)&all.sd->sum_loss, sizeof(all.sd->sum_loss), "", read, buff, text_len, text); text_len = sprintf(buff, "weighted_examples %f\n", all.sd->weighted_examples); bin_text_read_write_fixed(model_file,(char*)&all.sd->weighted_examples, sizeof(all.sd->weighted_examples), "", read, buff, text_len, text); text_len = sprintf(buff, "weighted_labels %f\n", all.sd->weighted_labels); bin_text_read_write_fixed(model_file,(char*)&all.sd->weighted_labels, sizeof(all.sd->weighted_labels), "", read, buff, text_len, text); text_len = sprintf(buff, "example_number %u\n", (uint32_t)all.sd->example_number); bin_text_read_write_fixed(model_file,(char*)&all.sd->example_number, sizeof(all.sd->example_number), "", read, buff, text_len, text); text_len = sprintf(buff, "total_features %u\n", (uint32_t)all.sd->total_features); bin_text_read_write_fixed(model_file,(char*)&all.sd->total_features, sizeof(all.sd->total_features), "", read, buff, text_len, text); uint32_t length = 1 << all.num_bits; uint32_t stride = all.reg.stride_shift; uint32_t i = 0; size_t brw = 1; do { brw = 1; weight* v; if (read) { // read binary brw = bin_read_fixed(model_file, (char*)&i, sizeof(i),""); if (brw > 0) { assert (i< length); v = &(all.reg.weight_vector[stride*i]); brw += bin_read_fixed(model_file, (char*)v, 4*sizeof(*v), ""); } } else { // write binary or text // save w[W_XT], w[W_ZT], w[W_G2] if any of them is not zero v = &(all.reg.weight_vector[stride*i]); if (v[W_XT] !=0. || v[W_ZT] !=0. || v[W_G2] !=0.) { text_len = sprintf(buff, "%d", i); brw = bin_text_write_fixed(model_file,(char *)&i, sizeof (i), buff, text_len, text); text_len = sprintf(buff, ":%f %f %f %f\n", *v, *(v+1), *(v+2), *(v+3)); brw += bin_text_write_fixed(model_file, (char *)v, 4*sizeof (*v), buff, text_len, text); } // end if } // end else if (!read) { i++; } } while ((!read && i < length) || (read && brw >0)); } //void save_load(void* in, void* d, io_buf& model_file, bool read, bool text) { void save_load(ftrl& b, io_buf& model_file, bool read, bool text) { vw* all = b.all; if (read) { initialize_regressor(*all); } if (model_file.files.size() > 0) { bool resume = all->save_resume; char buff[512]; uint32_t text_len = sprintf(buff, ":%d\n", resume); bin_text_read_write_fixed(model_file,(char *)&resume, sizeof (resume), "", read, buff, text_len, text); if (resume) { save_load_online_state(*all, model_file, read, text); } else { GD::save_load_regressor(*all, model_file, read, text); } } } // placeholder void predict(ftrl& b, learner& base, example& ec) { vw* all = b.all; //((label_data*) ec.ld)->prediction = ftrl_predict(*all,ec); ec.l.simple.prediction = ftrl_predict(*all,ec); } //void finish(void* a, void* d) { void finish(ftrl& b) { } learner* setup(vw& all, po::variables_map& vm) { ftrl* b = (ftrl*)calloc_or_die(1, sizeof(ftrl)); b->all = &all; po::options_description ftrl_opts("FTRL options"); vm = add_options(all, ftrl_opts); all.ftrl = true; all.reg.stride_shift = 2; // NOTE: for more parameter storage b->progressive_validation = false; if (vm.count("progressive_validation")) { std::string filename = vm["progressive_validation"].as<string>(); b->fo = fopen(filename.c_str(), "w"); assert(b->fo != NULL); b->progressive_validation = true; } learner* l = new learner(b, 1 << all.reg.stride_shift); l->set_learn<ftrl, learn>(); l->set_predict<ftrl, predict>(); l->set_save_load<ftrl,save_load>(); l->set_finish<ftrl,finish>(); return l; } } // end namespace <commit_msg>removed dummy finish funtion<commit_after>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <fstream> #include <float.h> #ifndef _WIN32 #include <netdb.h> #endif #include <string.h> #include <stdio.h> #include <assert.h> #include <sys/timeb.h> #include "parse_example.h" #include "constant.h" #include "cache.h" #include "simple_label.h" #include "vw.h" #include "gd.h" #include "accumulate.h" #include "memory.h" #include <exception> using namespace std; using namespace LEARNER; #define W_XT 0 // current parameter w(XT) #define W_GT 1 // current gradient g(GT) #define W_ZT 2 // accumulated z(t) = z(t-1) + g(t) + sigma*w(t) #define W_G2 3 // accumulated gradient squre n(t) = n(t-1) + g(t)*g(t) /********************************************************************/ /* mem & w definition ***********************************************/ /********************************************************************/ // w[0] = current weight // w[1] = current first derivative // w[2] = accumulated zt // w[3] = accumulated g2 namespace FTRL { //nonrentrant struct ftrl { vw* all; // set by initializer // evaluation file pointer FILE* fo; bool progressive_validation; }; void update_accumulated_state(weight* w, float alpha) { double ng2 = w[W_G2] + w[W_GT]*w[W_GT]; double sigma = (sqrt(ng2) - sqrt(w[W_G2]))/ alpha; w[W_ZT] += w[W_GT] - sigma * w[W_XT]; w[W_G2] = ng2; } // use in gradient prediction void quad_grad_update(weight* weights, feature& page_feature, v_array<feature> &offer_features, size_t mask, float g, float alpha) { size_t halfhash = quadratic_constant * page_feature.weight_index; float update = g * page_feature.x; for (feature* ele = offer_features.begin; ele != offer_features.end; ele++) { weight* w=&weights[(halfhash + ele->weight_index) & mask]; w[W_GT] = update * ele->x; update_accumulated_state(w, alpha); } } void cubic_grad_update(weight* weights, feature& f0, feature& f1, v_array<feature> &cross_features, size_t mask, float g, float alpha) { size_t halfhash = cubic_constant2 * (cubic_constant * f0.weight_index + f1.weight_index); float update = g * f0.x * f1.x; for (feature* ele = cross_features.begin; ele != cross_features.end; ele++) { weight* w=&weights[(halfhash + ele->weight_index) & mask]; w[W_GT] = update * ele->x; update_accumulated_state(w, alpha); } } float ftrl_predict(vw& all, example& ec) { ec.partial_prediction = GD::inline_predict(all, ec); return GD::finalize_prediction(all.sd, ec.partial_prediction); } float predict_and_gradient(vw& all, example& ec) { float fp = ftrl_predict(all, ec); ec.updated_prediction = fp; //label_data* ld = (label_data*)ec.ld; label_data& ld = ec.l.simple; all.set_minmax(all.sd, ld.label); float loss_grad = all.loss->first_derivative(all.sd, fp, ld.label) * ld.weight; size_t mask = all.reg.weight_mask; weight* weights = all.reg.weight_vector; for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) { feature *f = ec.atomics[*i].begin; for (; f != ec.atomics[*i].end; f++) { weight* w = &weights[f->weight_index & mask]; w[W_GT] = loss_grad * f->x; // += -> = update_accumulated_state(w, all.ftrl_alpha); } } // bi-gram feature for (vector<string>::iterator i = all.pairs.begin(); i != all.pairs.end(); i++) { if (ec.atomics[(int)(*i)[0]].size() > 0) { v_array<feature> temp = ec.atomics[(int)(*i)[0]]; for (; temp.begin != temp.end; temp.begin++) quad_grad_update(weights, *temp.begin, ec.atomics[(int)(*i)[1]], mask, loss_grad, all.ftrl_alpha); } } // tri-gram feature for (vector<string>::iterator i = all.triples.begin(); i != all.triples.end();i++) { if ((ec.atomics[(int)(*i)[0]].size() == 0) || (ec.atomics[(int)(*i)[1]].size() == 0) || (ec.atomics[(int)(*i)[2]].size() == 0)) { continue; } v_array<feature> temp1 = ec.atomics[(int)(*i)[0]]; for (; temp1.begin != temp1.end; temp1.begin++) { v_array<feature> temp2 = ec.atomics[(int)(*i)[1]]; for (; temp2.begin != temp2.end; temp2.begin++) cubic_grad_update(weights, *temp1.begin, *temp2.begin, ec.atomics[(int)(*i)[2]], mask, loss_grad, all.ftrl_alpha); } } return fp; } inline float sign(float w){ if (w < 0.) return -1.; else return 1.;} void update_weight(vw& all, example& ec) { size_t mask = all.reg.weight_mask; weight* weights = all.reg.weight_vector; for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) { feature *f = ec.atomics[*i].begin; for (; f != ec.atomics[*i].end; f++) { weight* w = &weights[f->weight_index & mask]; float flag = sign(w[W_ZT]); float fabs_zt = w[W_ZT] * flag; if (fabs_zt <= all.l1_lambda) { w[W_XT] = 0.; } else { double step = 1/(all.l2_lambda + (all.ftrl_beta + sqrt(w[W_G2]))/all.ftrl_alpha); w[W_XT] = step * flag * (all.l1_lambda - fabs_zt); } } } } void evaluate_example(vw& all, ftrl& b , example& ec) { //label_data* ld = (label_data*)ec.ld; label_data& ld = ec.l.simple; ec.loss = all.loss->getLoss(all.sd, ec.updated_prediction, ld.label) * ld.weight; if (b.progressive_validation) { float v = 1./(1 + exp(-ec.updated_prediction)); fprintf(b.fo, "%.6f\t%d\n", v, (int)(ld.label * ld.weight)); } } //void learn(void* a, void* d, example* ec) { void learn(ftrl& a, learner& base, example& ec) { vw* all = a.all; assert(ec.in_use); // predict w*x, compute gradient, update accumulate state predict_and_gradient(*all, ec); // evaluate, statistic evaluate_example(*all, a, ec); // update weight update_weight(*all, ec); } void save_load_online_state(vw& all, io_buf& model_file, bool read, bool text) { char buff[512]; int text_len = sprintf(buff, "sum_loss %f\n", all.sd->sum_loss); bin_text_read_write_fixed(model_file,(char*)&all.sd->sum_loss, sizeof(all.sd->sum_loss), "", read, buff, text_len, text); text_len = sprintf(buff, "weighted_examples %f\n", all.sd->weighted_examples); bin_text_read_write_fixed(model_file,(char*)&all.sd->weighted_examples, sizeof(all.sd->weighted_examples), "", read, buff, text_len, text); text_len = sprintf(buff, "weighted_labels %f\n", all.sd->weighted_labels); bin_text_read_write_fixed(model_file,(char*)&all.sd->weighted_labels, sizeof(all.sd->weighted_labels), "", read, buff, text_len, text); text_len = sprintf(buff, "example_number %u\n", (uint32_t)all.sd->example_number); bin_text_read_write_fixed(model_file,(char*)&all.sd->example_number, sizeof(all.sd->example_number), "", read, buff, text_len, text); text_len = sprintf(buff, "total_features %u\n", (uint32_t)all.sd->total_features); bin_text_read_write_fixed(model_file,(char*)&all.sd->total_features, sizeof(all.sd->total_features), "", read, buff, text_len, text); uint32_t length = 1 << all.num_bits; uint32_t stride = all.reg.stride_shift; uint32_t i = 0; size_t brw = 1; do { brw = 1; weight* v; if (read) { // read binary brw = bin_read_fixed(model_file, (char*)&i, sizeof(i),""); if (brw > 0) { assert (i< length); v = &(all.reg.weight_vector[stride*i]); brw += bin_read_fixed(model_file, (char*)v, 4*sizeof(*v), ""); } } else { // write binary or text // save w[W_XT], w[W_ZT], w[W_G2] if any of them is not zero v = &(all.reg.weight_vector[stride*i]); if (v[W_XT] !=0. || v[W_ZT] !=0. || v[W_G2] !=0.) { text_len = sprintf(buff, "%d", i); brw = bin_text_write_fixed(model_file,(char *)&i, sizeof (i), buff, text_len, text); text_len = sprintf(buff, ":%f %f %f %f\n", *v, *(v+1), *(v+2), *(v+3)); brw += bin_text_write_fixed(model_file, (char *)v, 4*sizeof (*v), buff, text_len, text); } // end if } // end else if (!read) { i++; } } while ((!read && i < length) || (read && brw >0)); } //void save_load(void* in, void* d, io_buf& model_file, bool read, bool text) { void save_load(ftrl& b, io_buf& model_file, bool read, bool text) { vw* all = b.all; if (read) { initialize_regressor(*all); } if (model_file.files.size() > 0) { bool resume = all->save_resume; char buff[512]; uint32_t text_len = sprintf(buff, ":%d\n", resume); bin_text_read_write_fixed(model_file,(char *)&resume, sizeof (resume), "", read, buff, text_len, text); if (resume) { save_load_online_state(*all, model_file, read, text); } else { GD::save_load_regressor(*all, model_file, read, text); } } } // placeholder void predict(ftrl& b, learner& base, example& ec) { vw* all = b.all; //((label_data*) ec.ld)->prediction = ftrl_predict(*all,ec); ec.l.simple.prediction = ftrl_predict(*all,ec); } learner* setup(vw& all, po::variables_map& vm) { ftrl* b = (ftrl*)calloc_or_die(1, sizeof(ftrl)); b->all = &all; po::options_description ftrl_opts("FTRL options"); vm = add_options(all, ftrl_opts); all.ftrl = true; all.reg.stride_shift = 2; // NOTE: for more parameter storage b->progressive_validation = false; if (vm.count("progressive_validation")) { std::string filename = vm["progressive_validation"].as<string>(); b->fo = fopen(filename.c_str(), "w"); assert(b->fo != NULL); b->progressive_validation = true; } learner* l = new learner(b, 1 << all.reg.stride_shift); l->set_learn<ftrl, learn>(); l->set_predict<ftrl, predict>(); l->set_save_load<ftrl,save_load>(); return l; } } // end namespace <|endoftext|>
<commit_before>/* Copyright (c) 2013 Fabian Schuiki */ #pragma once #include <cassert> #define GLADUS_HAS_BINDING namespace gladus { /** A pair of bind() and unbind() calls limited to the scope of the declared * variable. Provides a convenient exception-safe way of using OpenGL resources * that implement a bind/unbind pattern. May not be nested. */ template <typename T> struct scoped_bind { typedef T type; T& object; scoped_bind(T& object): object(object) { is_bound = false; bind(); } ~scoped_bind() { if (is_bound) unbind(); } void bind() { assert(!is_bound); object.bind(); is_bound = true; } void unbind() { assert(is_bound); object.unbind(); is_bound = false; } private: bool is_bound; }; /** A pair of use() and unuse() calls limited to the scope of the declared * variable. Provides a convenient exception-safe way of using OpenGL resources * that implement a use/unuse pattern. May not be nested. */ template <typename T> struct scoped_use { typedef T type; T& object; scoped_use(T& object): object(object) { is_used = false; use(); } ~scoped_use() { if (is_used) unuse(); } void use() { assert(!is_used); object.use(); is_used = true; } void unuse() { assert(is_used); object.unuse(); is_used = false; } private: bool is_used; }; } // namespace gladus <commit_msg>scoped bind and use now take a const ref<commit_after>/* Copyright (c) 2013 Fabian Schuiki */ #pragma once #include <cassert> #define GLADUS_HAS_BINDING namespace gladus { /** A pair of bind() and unbind() calls limited to the scope of the declared * variable. Provides a convenient exception-safe way of using OpenGL resources * that implement a bind/unbind pattern. May not be nested. */ template <typename T> struct scoped_bind { typedef T type; const T& object; scoped_bind(const T& object): object(object) { is_bound = false; bind(); } ~scoped_bind() { if (is_bound) unbind(); } void bind() { assert(!is_bound); object.bind(); is_bound = true; } void unbind() { assert(is_bound); object.unbind(); is_bound = false; } private: bool is_bound; }; /** A pair of use() and unuse() calls limited to the scope of the declared * variable. Provides a convenient exception-safe way of using OpenGL resources * that implement a use/unuse pattern. May not be nested. */ template <typename T> struct scoped_use { typedef T type; const T& object; scoped_use(const T& object): object(object) { is_used = false; use(); } ~scoped_use() { if (is_used) unuse(); } void use() { assert(!is_used); object.use(); is_used = true; } void unuse() { assert(is_used); object.unuse(); is_used = false; } private: bool is_used; }; } // namespace gladus <|endoftext|>
<commit_before>/** * Copyright (c) 2015, Lehigh University * All rights reserved. * See COPYING for license. * * This file implements the program that finds the best resultant snake * (evaluated by the F-funtion) under different values of low SNR threshold t * and penalizing factor c. If a ground truth snake is present, it also * computes the Vertex Error and Hausdorff distance of these best snakes. */ #include <iostream> #include <cstdlib> #include <vector> #include <map> #include <set> #include <fstream> #include "boost/program_options.hpp" #include "boost/filesystem.hpp" #include "./multisnake.h" #include "./utility.h" namespace po = boost::program_options; namespace fs = boost::filesystem; typedef std::vector<fs::path> Paths; typedef std::map<std::pair<double, double>, double> TCFMap; typedef std::map<std::string, TCFMap> FValuesMap; typedef std::map<std::pair<double, double>, std::string> TCFilenameMap; typedef std::map<std::pair<double, double>, std::pair<double, double> > TCErrorMap; typedef std::set<std::string> StringSet; void CreateSortedSnakePaths(const fs::path &snake_dir, Paths &snake_paths); void ComputeFilenameFValuesMap(soax::Multisnake &ms, const Paths &snake_paths, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, FValuesMap &fmap); void ComputeBestSnakes(soax::Multisnake &ms, const FValuesMap &fmap, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, bool gt, TCFilenameMap &tc_filenames, TCErrorMap &tc_errors, StringSet &candidate_filenames); void PrintFMap(const FValuesMap &fmap); void PrintTCFMap(const TCFMap &m); void PrintTCFilenameMap(const TCFilenameMap &m, std::ostream &os); std::string GetBestFilename(const FValuesMap &m, double t, double c, double &min_f); void PrintTCErrorMap(const TCFilenameMap &filename_map, const TCErrorMap &error_map, std::ostream &os); int main(int argc, char **argv) { try { po::options_description generic("Generic options"); generic.add_options() ("version,v", "Print version and exit") ("help,h", "Print help and exit"); po::options_description required("Required options"); required.add_options() ("image,i", po::value<std::string>()->required(), "Path of input image") ("snake,s", po::value<std::string>()->required(), "Directory of resultant snake files") ("output,o", po::value<std::string>()->required(), "Path of output candidate file"); std::vector<double> t_range(3, 0.0), c_range(3, 0.0); t_range[0] = 1.0; // start t_range[1] = 0.1; // step t_range[2] = 4.0; // end c_range[0] = 1.0; // start c_range[1] = 0.1; // step c_range[2] = 4.0; // end po::options_description optional("Optional options"); optional.add_options() ("rnear,n", po::value<int>()->default_value(3), "Inner radius of local background annulus") ("rfar,f", po::value<int>()->default_value(6), "Outer radius of local background annulus") ("t-range,t", po::value<std::vector<double> >(&t_range)->multitoken(), "Range of low SNR threshold (start step end)" " Default: 1.0 0.1 4.0") ("c-range,c", po::value<std::vector<double> >(&c_range)->multitoken(), "Range of penalizing factor (start step end)" " Default: 1.0 0.1 4.0") ("ground-truth,g", po::value<std::string>(), "Path of the ground truth snake") ("error,e", po::value<std::string>(), "Path of the output 'tc-candidate-error' file"); po::options_description all("Allowed options"); all.add(generic).add(required).add(optional); po::variables_map vm; po::store(parse_command_line(argc, argv, all), vm); if (vm.count("version")) { const std::string version_msg( "Best Snake 3.7.0 \n" "Copyright (C) 2015-2021, Lehigh University."); std::cout << version_msg << std::endl; return EXIT_SUCCESS; } if (vm.count("help")) { std::cout << "Usage for best_snake: \n" << all; return EXIT_SUCCESS; } po::notify(vm); if (vm.count("ground-truth") && !vm.count("error")) { std::cerr << "Path of output 'tc-candidate-error' file is needed" " when ground truth is provided." << std::endl; return EXIT_FAILURE; } try { fs::path snake_dir(vm["snake"].as<std::string>()); if (fs::exists(snake_dir)) { soax::Multisnake ms; ms.LoadImage(vm["image"].as<std::string>()); Paths snake_paths; CreateSortedSnakePaths(snake_dir, snake_paths); FValuesMap fmap; int rnear = vm["rnear"].as<int>(); int rfar = vm["rfar"].as<int>(); std::cout << rnear << std::endl; std::cout << rfar << std::endl; std::cout << "t-range: " << t_range[0] << ' ' << t_range[1] << ' ' << t_range[2] << std::endl; std::cout << "c-range: " << c_range[0] << ' ' << c_range[1] << ' ' << c_range[2] << std::endl; ComputeFilenameFValuesMap(ms, snake_paths, rnear, rfar, t_range, c_range, fmap); if (vm.count("ground-truth")) { ms.LoadGroundTruthSnakes(vm["ground-truth"].as<std::string>()); std::cout << ms.GetNumberOfComparingSnakes1() << " ground truth snakes loaded." << std::endl; } StringSet candidate_filenames; TCFilenameMap tc_filenames; TCErrorMap tc_errors; ComputeBestSnakes(ms, fmap, rnear, rfar, t_range, c_range, vm.count("ground-truth"), tc_filenames, tc_errors, candidate_filenames); std::ofstream candidate_file(vm["output"].as<std::string>().c_str()); for (StringSet::const_iterator it = candidate_filenames.begin(); it != candidate_filenames.end(); ++it) { candidate_file << *it << std::endl; } if (vm.count("error")) { std::ofstream tc_error_file(vm["error"].as<std::string>().c_str()); PrintTCErrorMap(tc_filenames, tc_errors, tc_error_file); } } else { std::cout << snake_dir << " does not exist." << std::endl; } } catch (const fs::filesystem_error &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } catch (std::exception &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } void CreateSortedSnakePaths(const fs::path &snake_dir, Paths &snake_paths) { std::copy(fs::directory_iterator(snake_dir), fs::directory_iterator(), back_inserter(snake_paths)); std::sort(snake_paths.begin(), snake_paths.end()); } void ComputeFilenameFValuesMap(soax::Multisnake &ms, const Paths &snake_paths, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, FValuesMap &fmap) { for (Paths::const_iterator it = snake_paths.begin(); it != snake_paths.end(); ++it) { ms.LoadConvergedSnakes(it->string()); soax::DataContainer snrs; ms.ComputeResultSnakesLocalSNRs(rnear, rfar, snrs); TCFMap tcf; for (double t = t_range[0]; t < t_range[2]; t += t_range[1]) { for (double c = c_range[0]; c < c_range[2]; c += c_range[1]) { double fvalue = ms.ComputeFValue(snrs, t, c); tcf[std::make_pair(t, c)] = fvalue; } } fmap[it->string()] = tcf; } } void ComputeBestSnakes(soax::Multisnake &ms, const FValuesMap &fmap, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, bool gt, TCFilenameMap &tc_filenames, TCErrorMap &tc_errors, StringSet &candidate_filenames) { for (double t = t_range[0]; t < t_range[2]; t += t_range[1]) { for (double c = c_range[0]; c < c_range[2]; c += c_range[1]) { double min_f = 1e8; std::string filename = GetBestFilename(fmap, t, c, min_f); tc_filenames[std::make_pair(t, c)] = filename; if ((t + c > 3.0) && (t + c < 6.0)) candidate_filenames.insert(filename); if (gt) { ms.LoadConvergedSnakes(filename); double vertex_error(100.0), hausdorff(100.0); ms.ComputeResultSnakesVertexErrorHausdorffDistance(vertex_error, hausdorff); tc_errors[std::make_pair(t, c)] = std::make_pair(vertex_error, hausdorff); } } } } void PrintFMap(const FValuesMap &fmap) { for (FValuesMap::const_iterator it = fmap.begin(); it != fmap.end(); ++it) { std::cout << it->first << ":\n"; PrintTCFMap(it->second); std::cout << std::endl; } } void PrintTCFMap(const TCFMap &m) { for (TCFMap::const_iterator it = m.begin(); it != m.end(); ++it) { std::cout << "(" << it->first.first << ", " << it->first.second << "): " << it->second << '\t'; } } void PrintTCFilenameMap(const TCFilenameMap &m, std::ostream &os) { for (TCFilenameMap::const_iterator it = m.begin(); it != m.end(); ++it) { os << it->first.first << "\t" << it->first.second << "\t" << it->second << std::endl; } } std::string GetBestFilename(const FValuesMap &m, double t, double c, double &min_f) { std::string filename; min_f = 1e8; for (FValuesMap::const_iterator it = m.begin(); it != m.end(); ++it) { TCFMap::const_iterator f_it = it->second.find(std::make_pair(t, c)); if (f_it != it->second.end()) { if (f_it->second < min_f) { min_f = f_it->second; filename = it->first; } } else { std::cerr << "cannot find F-value for (" << t << ", " << c << ")." << std::endl; } } return filename; } void PrintTCErrorMap(const TCFilenameMap &filename_map, const TCErrorMap &error_map, std::ostream &os) { for (TCFilenameMap::const_iterator it = filename_map.begin(); it != filename_map.end(); ++it) { os << it->first.first << "\t" << it->first.second << "\t" << it->second; TCErrorMap::const_iterator eit = error_map.find(it->first); if (eit != error_map.end()) { os << "\t" << eit->second.first << "\t" << eit->second.second; } os << std::endl; } } <commit_msg>Changed version number to 3.7.1<commit_after>/** * Copyright (c) 2015, Lehigh University * All rights reserved. * See COPYING for license. * * This file implements the program that finds the best resultant snake * (evaluated by the F-funtion) under different values of low SNR threshold t * and penalizing factor c. If a ground truth snake is present, it also * computes the Vertex Error and Hausdorff distance of these best snakes. */ #include <iostream> #include <cstdlib> #include <vector> #include <map> #include <set> #include <fstream> #include "boost/program_options.hpp" #include "boost/filesystem.hpp" #include "./multisnake.h" #include "./utility.h" namespace po = boost::program_options; namespace fs = boost::filesystem; typedef std::vector<fs::path> Paths; typedef std::map<std::pair<double, double>, double> TCFMap; typedef std::map<std::string, TCFMap> FValuesMap; typedef std::map<std::pair<double, double>, std::string> TCFilenameMap; typedef std::map<std::pair<double, double>, std::pair<double, double> > TCErrorMap; typedef std::set<std::string> StringSet; void CreateSortedSnakePaths(const fs::path &snake_dir, Paths &snake_paths); void ComputeFilenameFValuesMap(soax::Multisnake &ms, const Paths &snake_paths, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, FValuesMap &fmap); void ComputeBestSnakes(soax::Multisnake &ms, const FValuesMap &fmap, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, bool gt, TCFilenameMap &tc_filenames, TCErrorMap &tc_errors, StringSet &candidate_filenames); void PrintFMap(const FValuesMap &fmap); void PrintTCFMap(const TCFMap &m); void PrintTCFilenameMap(const TCFilenameMap &m, std::ostream &os); std::string GetBestFilename(const FValuesMap &m, double t, double c, double &min_f); void PrintTCErrorMap(const TCFilenameMap &filename_map, const TCErrorMap &error_map, std::ostream &os); int main(int argc, char **argv) { try { po::options_description generic("Generic options"); generic.add_options() ("version,v", "Print version and exit") ("help,h", "Print help and exit"); po::options_description required("Required options"); required.add_options() ("image,i", po::value<std::string>()->required(), "Path of input image") ("snake,s", po::value<std::string>()->required(), "Directory of resultant snake files") ("output,o", po::value<std::string>()->required(), "Path of output candidate file"); std::vector<double> t_range(3, 0.0), c_range(3, 0.0); t_range[0] = 1.0; // start t_range[1] = 0.1; // step t_range[2] = 4.0; // end c_range[0] = 1.0; // start c_range[1] = 0.1; // step c_range[2] = 4.0; // end po::options_description optional("Optional options"); optional.add_options() ("rnear,n", po::value<int>()->default_value(3), "Inner radius of local background annulus") ("rfar,f", po::value<int>()->default_value(6), "Outer radius of local background annulus") ("t-range,t", po::value<std::vector<double> >(&t_range)->multitoken(), "Range of low SNR threshold (start step end)" " Default: 1.0 0.1 4.0") ("c-range,c", po::value<std::vector<double> >(&c_range)->multitoken(), "Range of penalizing factor (start step end)" " Default: 1.0 0.1 4.0") ("ground-truth,g", po::value<std::string>(), "Path of the ground truth snake") ("error,e", po::value<std::string>(), "Path of the output 'tc-candidate-error' file"); po::options_description all("Allowed options"); all.add(generic).add(required).add(optional); po::variables_map vm; po::store(parse_command_line(argc, argv, all), vm); if (vm.count("version")) { const std::string version_msg( "Best Snake 3.7.1 \n" "Copyright (C) 2015-2021, Lehigh University."); std::cout << version_msg << std::endl; return EXIT_SUCCESS; } if (vm.count("help")) { std::cout << "Usage for best_snake: \n" << all; return EXIT_SUCCESS; } po::notify(vm); if (vm.count("ground-truth") && !vm.count("error")) { std::cerr << "Path of output 'tc-candidate-error' file is needed" " when ground truth is provided." << std::endl; return EXIT_FAILURE; } try { fs::path snake_dir(vm["snake"].as<std::string>()); if (fs::exists(snake_dir)) { soax::Multisnake ms; ms.LoadImage(vm["image"].as<std::string>()); Paths snake_paths; CreateSortedSnakePaths(snake_dir, snake_paths); FValuesMap fmap; int rnear = vm["rnear"].as<int>(); int rfar = vm["rfar"].as<int>(); std::cout << rnear << std::endl; std::cout << rfar << std::endl; std::cout << "t-range: " << t_range[0] << ' ' << t_range[1] << ' ' << t_range[2] << std::endl; std::cout << "c-range: " << c_range[0] << ' ' << c_range[1] << ' ' << c_range[2] << std::endl; ComputeFilenameFValuesMap(ms, snake_paths, rnear, rfar, t_range, c_range, fmap); if (vm.count("ground-truth")) { ms.LoadGroundTruthSnakes(vm["ground-truth"].as<std::string>()); std::cout << ms.GetNumberOfComparingSnakes1() << " ground truth snakes loaded." << std::endl; } StringSet candidate_filenames; TCFilenameMap tc_filenames; TCErrorMap tc_errors; ComputeBestSnakes(ms, fmap, rnear, rfar, t_range, c_range, vm.count("ground-truth"), tc_filenames, tc_errors, candidate_filenames); std::ofstream candidate_file(vm["output"].as<std::string>().c_str()); for (StringSet::const_iterator it = candidate_filenames.begin(); it != candidate_filenames.end(); ++it) { candidate_file << *it << std::endl; } if (vm.count("error")) { std::ofstream tc_error_file(vm["error"].as<std::string>().c_str()); PrintTCErrorMap(tc_filenames, tc_errors, tc_error_file); } } else { std::cout << snake_dir << " does not exist." << std::endl; } } catch (const fs::filesystem_error &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } catch (std::exception &e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; } } void CreateSortedSnakePaths(const fs::path &snake_dir, Paths &snake_paths) { std::copy(fs::directory_iterator(snake_dir), fs::directory_iterator(), back_inserter(snake_paths)); std::sort(snake_paths.begin(), snake_paths.end()); } void ComputeFilenameFValuesMap(soax::Multisnake &ms, const Paths &snake_paths, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, FValuesMap &fmap) { for (Paths::const_iterator it = snake_paths.begin(); it != snake_paths.end(); ++it) { ms.LoadConvergedSnakes(it->string()); soax::DataContainer snrs; ms.ComputeResultSnakesLocalSNRs(rnear, rfar, snrs); TCFMap tcf; for (double t = t_range[0]; t < t_range[2]; t += t_range[1]) { for (double c = c_range[0]; c < c_range[2]; c += c_range[1]) { double fvalue = ms.ComputeFValue(snrs, t, c); tcf[std::make_pair(t, c)] = fvalue; } } fmap[it->string()] = tcf; } } void ComputeBestSnakes(soax::Multisnake &ms, const FValuesMap &fmap, int rnear, int rfar, const std::vector<double> &t_range, const std::vector<double> &c_range, bool gt, TCFilenameMap &tc_filenames, TCErrorMap &tc_errors, StringSet &candidate_filenames) { for (double t = t_range[0]; t < t_range[2]; t += t_range[1]) { for (double c = c_range[0]; c < c_range[2]; c += c_range[1]) { double min_f = 1e8; std::string filename = GetBestFilename(fmap, t, c, min_f); tc_filenames[std::make_pair(t, c)] = filename; if ((t + c > 3.0) && (t + c < 6.0)) candidate_filenames.insert(filename); if (gt) { ms.LoadConvergedSnakes(filename); double vertex_error(100.0), hausdorff(100.0); ms.ComputeResultSnakesVertexErrorHausdorffDistance(vertex_error, hausdorff); tc_errors[std::make_pair(t, c)] = std::make_pair(vertex_error, hausdorff); } } } } void PrintFMap(const FValuesMap &fmap) { for (FValuesMap::const_iterator it = fmap.begin(); it != fmap.end(); ++it) { std::cout << it->first << ":\n"; PrintTCFMap(it->second); std::cout << std::endl; } } void PrintTCFMap(const TCFMap &m) { for (TCFMap::const_iterator it = m.begin(); it != m.end(); ++it) { std::cout << "(" << it->first.first << ", " << it->first.second << "): " << it->second << '\t'; } } void PrintTCFilenameMap(const TCFilenameMap &m, std::ostream &os) { for (TCFilenameMap::const_iterator it = m.begin(); it != m.end(); ++it) { os << it->first.first << "\t" << it->first.second << "\t" << it->second << std::endl; } } std::string GetBestFilename(const FValuesMap &m, double t, double c, double &min_f) { std::string filename; min_f = 1e8; for (FValuesMap::const_iterator it = m.begin(); it != m.end(); ++it) { TCFMap::const_iterator f_it = it->second.find(std::make_pair(t, c)); if (f_it != it->second.end()) { if (f_it->second < min_f) { min_f = f_it->second; filename = it->first; } } else { std::cerr << "cannot find F-value for (" << t << ", " << c << ")." << std::endl; } } return filename; } void PrintTCErrorMap(const TCFilenameMap &filename_map, const TCErrorMap &error_map, std::ostream &os) { for (TCFilenameMap::const_iterator it = filename_map.begin(); it != filename_map.end(); ++it) { os << it->first.first << "\t" << it->first.second << "\t" << it->second; TCErrorMap::const_iterator eit = error_map.find(it->first); if (eit != error_map.end()) { os << "\t" << eit->second.first << "\t" << eit->second.second; } os << std::endl; } } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Fabian Schuiki */ #pragma once #include <cassert> namespace gladus { template <typename T> struct binding { typedef T type; T& object; binding(T& object): object(object) { is_bound = false; bind(); } ~binding() { if (is_bound) unbind(); } void bind() { assert(!is_bound); object.bind(); is_bound = true; } void unbind() { assert(is_bound); object.unbind(); is_bound = false; } private: bool is_bound; }; } // namespace gladus <commit_msg>added GLADUS_HAS_BINDING<commit_after>/* Copyright (c) 2013 Fabian Schuiki */ #pragma once #include <cassert> #define GLADUS_HAS_BINDING namespace gladus { template <typename T> struct binding { typedef T type; T& object; binding(T& object): object(object) { is_bound = false; bind(); } ~binding() { if (is_bound) unbind(); } void bind() { assert(!is_bound); object.bind(); is_bound = true; } void unbind() { assert(is_bound); object.unbind(); is_bound = false; } private: bool is_bound; }; } // namespace gladus <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/init/Init.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/portability/GFlags.h> #include <folly/ssl/Init.h> #include <wangle/acceptor/Acceptor.h> #include <wangle/bootstrap/ServerBootstrap.h> #include <wangle/channel/AsyncSocketHandler.h> #include <wangle/codec/LineBasedFrameDecoder.h> #include <wangle/codec/StringCodec.h> #include <wangle/ssl/TLSCredProcessor.h> DEFINE_string(cert_path, "", "Path to cert pem"); DEFINE_string(key_path, "", "Path to cert key"); DEFINE_string(ca_path, "", "Path to trusted CA file"); DEFINE_int32(port, 8080, "Listen port"); DEFINE_string(tickets_path, "", "Path for ticket seeds"); DEFINE_uint32(num_workers, 2, "Number of worker threads"); DEFINE_bool( enable_share_ssl_ctx, true, "Enable sharing SSL context configs between worker threads"); /** * This is meant to be a simple server that accepts plaintext and SSL on a * single port. To test: * plaintext: nc localhost 8080 * ssl: openssl s_client -connect localhost:8080 * * Test cert and key are available in wangle/ssl/test/certs */ using namespace wangle; using namespace folly; typedef Pipeline<IOBufQueue&, std::string> EchoPipeline; namespace { // the main logic of our echo server; receives a string and writes it straight // back class EchoHandler : public HandlerAdapter<std::string> { public: void read(Context* ctx, std::string msg) override { std::cout << "handling " << msg << std::endl; write(ctx, msg + "\r\n"); } }; // where we define the chain of handlers for each messeage received class EchoPipelineFactory : public PipelineFactory<EchoPipeline> { public: EchoPipeline::Ptr newPipeline(std::shared_ptr<AsyncTransport> sock) override { auto pipeline = EchoPipeline::create(); pipeline->addBack(AsyncSocketHandler(sock)); pipeline->addBack(LineBasedFrameDecoder(8192)); pipeline->addBack(StringCodec()); pipeline->addBack(EchoHandler()); pipeline->finalize(); return pipeline; } }; // Init the processor callbacks. It's fine to do this // even if nothing is being watched void initCredProcessorCallbacks( ServerBootstrap<EchoPipeline>& sb, TLSCredProcessor& processor) { // set up ticket seed callback processor.addTicketCallback([&](TLSTicketKeySeeds seeds) { if (FLAGS_enable_share_ssl_ctx) { sb.getSharedSSLContextManager()->updateTLSTicketKeys(seeds); } else { // update sb.forEachWorker([&](Acceptor* acceptor) { if (!acceptor) { // this condition can happen if the processor triggers before the // server is ready / listening return; } auto evb = acceptor->getEventBase(); if (!evb) { return; } evb->runInEventBaseThread([acceptor, seeds] { acceptor->setTLSTicketSecrets( seeds.oldSeeds, seeds.currentSeeds, seeds.newSeeds); }); }); } }); // Reconfigure SSL when we detect cert or CA changes. processor.addCertCallback([&] { if (FLAGS_enable_share_ssl_ctx) { sb.getSharedSSLContextManager()->reloadSSLContextConfigs(); } else { sb.forEachWorker([&](Acceptor* acceptor) { if (!acceptor) { return; } auto evb = acceptor->getEventBase(); if (!evb) { return; } evb->runInEventBaseThread( [acceptor] { acceptor->resetSSLContextConfigs(); }); }); } }); } } // namespace int main(int argc, char** argv) { folly::Init init(&argc, &argv); folly::ssl::init(); ServerSocketConfig cfg; folly::Optional<TLSTicketKeySeeds> seeds; ServerBootstrap<EchoPipeline> sb; TLSCredProcessor processor; if (!FLAGS_tickets_path.empty()) { seeds = TLSCredProcessor::processTLSTickets(FLAGS_tickets_path); if (seeds) { cfg.initialTicketSeeds = *seeds; // watch for changes processor.setTicketPathToWatch(FLAGS_tickets_path); } } if (!FLAGS_cert_path.empty() && !FLAGS_key_path.empty()) { VLOG(0) << "Configuring SSL"; SSLContextConfig sslCfg; sslCfg.addCertificate(FLAGS_cert_path, FLAGS_key_path, ""); sslCfg.clientCAFile = FLAGS_ca_path; sslCfg.isDefault = true; cfg.sslContextConfigs.push_back(sslCfg); // IMPORTANT: when allowing both plaintext and ssl on the same port, // the acceptor requires 9 bytes of data to determine what kind of // connection is coming in. If the client does not send 9 bytes the // connection will idle out before the EchoCallback receives data. cfg.allowInsecureConnectionsOnSecureServer = true; // reload ssl contexts when certs change std::set<std::string> pathsToWatch{FLAGS_cert_path, FLAGS_key_path}; if (!FLAGS_ca_path.empty()) { pathsToWatch.insert(FLAGS_ca_path); } processor.setCertPathsToWatch(std::move(pathsToWatch)); } initCredProcessorCallbacks(sb, processor); // workers auto workers = std::make_shared<folly::IOThreadPoolExecutor>(FLAGS_num_workers); // create a server sb.acceptorConfig(cfg); sb.childPipeline(std::make_shared<EchoPipelineFactory>()); sb.setUseSharedSSLContextManager(FLAGS_enable_share_ssl_ctx); sb.group(workers); sb.bind(FLAGS_port); sb.waitForStop(); return 0; } <commit_msg>Set clientCAFiles instead of clientCAFile<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/init/Init.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/portability/GFlags.h> #include <folly/ssl/Init.h> #include <wangle/acceptor/Acceptor.h> #include <wangle/bootstrap/ServerBootstrap.h> #include <wangle/channel/AsyncSocketHandler.h> #include <wangle/codec/LineBasedFrameDecoder.h> #include <wangle/codec/StringCodec.h> #include <wangle/ssl/TLSCredProcessor.h> DEFINE_string(cert_path, "", "Path to cert pem"); DEFINE_string(key_path, "", "Path to cert key"); DEFINE_string(ca_path, "", "Path to trusted CA file"); DEFINE_int32(port, 8080, "Listen port"); DEFINE_string(tickets_path, "", "Path for ticket seeds"); DEFINE_uint32(num_workers, 2, "Number of worker threads"); DEFINE_bool( enable_share_ssl_ctx, true, "Enable sharing SSL context configs between worker threads"); /** * This is meant to be a simple server that accepts plaintext and SSL on a * single port. To test: * plaintext: nc localhost 8080 * ssl: openssl s_client -connect localhost:8080 * * Test cert and key are available in wangle/ssl/test/certs */ using namespace wangle; using namespace folly; typedef Pipeline<IOBufQueue&, std::string> EchoPipeline; namespace { // the main logic of our echo server; receives a string and writes it straight // back class EchoHandler : public HandlerAdapter<std::string> { public: void read(Context* ctx, std::string msg) override { std::cout << "handling " << msg << std::endl; write(ctx, msg + "\r\n"); } }; // where we define the chain of handlers for each messeage received class EchoPipelineFactory : public PipelineFactory<EchoPipeline> { public: EchoPipeline::Ptr newPipeline(std::shared_ptr<AsyncTransport> sock) override { auto pipeline = EchoPipeline::create(); pipeline->addBack(AsyncSocketHandler(sock)); pipeline->addBack(LineBasedFrameDecoder(8192)); pipeline->addBack(StringCodec()); pipeline->addBack(EchoHandler()); pipeline->finalize(); return pipeline; } }; // Init the processor callbacks. It's fine to do this // even if nothing is being watched void initCredProcessorCallbacks( ServerBootstrap<EchoPipeline>& sb, TLSCredProcessor& processor) { // set up ticket seed callback processor.addTicketCallback([&](TLSTicketKeySeeds seeds) { if (FLAGS_enable_share_ssl_ctx) { sb.getSharedSSLContextManager()->updateTLSTicketKeys(seeds); } else { // update sb.forEachWorker([&](Acceptor* acceptor) { if (!acceptor) { // this condition can happen if the processor triggers before the // server is ready / listening return; } auto evb = acceptor->getEventBase(); if (!evb) { return; } evb->runInEventBaseThread([acceptor, seeds] { acceptor->setTLSTicketSecrets( seeds.oldSeeds, seeds.currentSeeds, seeds.newSeeds); }); }); } }); // Reconfigure SSL when we detect cert or CA changes. processor.addCertCallback([&] { if (FLAGS_enable_share_ssl_ctx) { sb.getSharedSSLContextManager()->reloadSSLContextConfigs(); } else { sb.forEachWorker([&](Acceptor* acceptor) { if (!acceptor) { return; } auto evb = acceptor->getEventBase(); if (!evb) { return; } evb->runInEventBaseThread( [acceptor] { acceptor->resetSSLContextConfigs(); }); }); } }); } } // namespace int main(int argc, char** argv) { folly::Init init(&argc, &argv); folly::ssl::init(); ServerSocketConfig cfg; folly::Optional<TLSTicketKeySeeds> seeds; ServerBootstrap<EchoPipeline> sb; TLSCredProcessor processor; if (!FLAGS_tickets_path.empty()) { seeds = TLSCredProcessor::processTLSTickets(FLAGS_tickets_path); if (seeds) { cfg.initialTicketSeeds = *seeds; // watch for changes processor.setTicketPathToWatch(FLAGS_tickets_path); } } if (!FLAGS_cert_path.empty() && !FLAGS_key_path.empty()) { VLOG(0) << "Configuring SSL"; SSLContextConfig sslCfg; sslCfg.addCertificate(FLAGS_cert_path, FLAGS_key_path, ""); sslCfg.clientCAFiles = std::vector<std::string>{FLAGS_ca_path}; sslCfg.isDefault = true; cfg.sslContextConfigs.push_back(sslCfg); // IMPORTANT: when allowing both plaintext and ssl on the same port, // the acceptor requires 9 bytes of data to determine what kind of // connection is coming in. If the client does not send 9 bytes the // connection will idle out before the EchoCallback receives data. cfg.allowInsecureConnectionsOnSecureServer = true; // reload ssl contexts when certs change std::set<std::string> pathsToWatch{FLAGS_cert_path, FLAGS_key_path}; if (!FLAGS_ca_path.empty()) { pathsToWatch.insert(FLAGS_ca_path); } processor.setCertPathsToWatch(std::move(pathsToWatch)); } initCredProcessorCallbacks(sb, processor); // workers auto workers = std::make_shared<folly::IOThreadPoolExecutor>(FLAGS_num_workers); // create a server sb.acceptorConfig(cfg); sb.childPipeline(std::make_shared<EchoPipelineFactory>()); sb.setUseSharedSSLContextManager(FLAGS_enable_share_ssl_ctx); sb.group(workers); sb.bind(FLAGS_port); sb.waitForStop(); return 0; } <|endoftext|>
<commit_before>// Copyright 2020 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdlib> #include <bsoncxx/exception/error_code.hpp> #include <bsoncxx/exception/exception.hpp> #include <bsoncxx/private/libbson.hh> #include <bsoncxx/private/suppress_deprecation_warnings.hh> #include <bsoncxx/types/bson_value/view.hpp> #include <bsoncxx/types/private/convert.hh> #include <bsoncxx/config/private/prelude.hh> #define BSONCXX_CITER \ bson_iter_t iter; \ bson_iter_init_from_data_at_offset(&iter, raw, length, offset, keylen); #define BSONCXX_TYPE_CHECK(name) \ do { \ if (type() != bsoncxx::type::k_##name) { \ throw bsoncxx::exception{error_code::k_need_element_type_k_##name}; \ } \ } while (0) namespace bsoncxx { BSONCXX_INLINE_NAMESPACE_BEGIN namespace types { namespace bson_value { view::view() noexcept : view(nullptr) {} // Boost doesn't mark the copy constructor and copy-assignment operator of string_ref as noexcept // so we can't rely on automatic noexcept propagation. It really is though, so it is OK. #if !defined(BSONCXX_POLY_USE_BOOST) #define BSONCXX_ENUM(name, val) \ view::view(b_##name value) noexcept \ : _type(static_cast<bsoncxx::type>(val)), _b_##name(std::move(value)) { \ static_assert(std::is_nothrow_copy_constructible<b_##name>::value, "Copy may throw"); \ static_assert(std::is_nothrow_copy_assignable<b_##name>::value, "Copy may throw"); \ static_assert(std::is_nothrow_destructible<b_##name>::value, "Destruction may throw"); \ } #else #define BSONCXX_ENUM(name, val) \ view::view(b_##name value) noexcept \ : _type(static_cast<bsoncxx::type>(val)), _b_##name(std::move(value)) { \ static_assert(std::is_nothrow_destructible<b_##name>::value, "Destruction may throw"); \ } #endif #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM view::view(const view& rhs) noexcept { switch (static_cast<int>(rhs._type)) { #define BSONCXX_ENUM(type, val) \ case val: \ new (&_b_##type) b_##type(rhs.get_##type()); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } _type = rhs._type; } view& view::operator=(const view& rhs) noexcept { if (this == &rhs) { return *this; } destroy(); switch (static_cast<int>(rhs._type)) { #define BSONCXX_ENUM(type, val) \ case val: \ new (&_b_##type) b_##type(rhs.get_##type()); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } _type = rhs._type; return *this; } view::~view() { destroy(); } bsoncxx::type view::type() const { return _type; } #define BSONCXX_ENUM(type, val) \ const types::b_##type& view::get_##type() const { \ BSONCXX_TYPE_CHECK(type); \ return _b_##type; \ } #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM const types::b_string& view::get_utf8() const { BSONCXX_TYPE_CHECK(string); return _b_string; } view::view(const std::uint8_t* raw, std::uint32_t length, std::uint32_t offset, std::uint32_t keylen) { BSONCXX_CITER; auto value = bson_iter_value(&iter); _init((void*)value); } view::view(void* internal_value) noexcept { _init(internal_value); } void view::_init(void* internal_value) noexcept { if (!internal_value) { _type = bsoncxx::type::k_null; _b_null = bsoncxx::types::b_null{}; return; } bson_value_t* v = (bson_value_t*)(internal_value); _type = static_cast<bsoncxx::type>(v->value_type); switch (_type) { #define BSONCXX_ENUM(name, val) \ case bsoncxx::type::k_##name: { \ convert_from_libbson(v, &_b_##name); \ break; \ } #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM default: BSONCXX_UNREACHABLE; } } bool operator==(const view& lhs, const view& rhs) { if (lhs.type() != rhs.type()) { return false; } switch (static_cast<int>(lhs.type())) { #define BSONCXX_ENUM(type, val) \ case val: \ return lhs.get_##type() == rhs.get_##type(); #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } // Silence compiler warnings about failing to return a value. BSONCXX_UNREACHABLE; } bool operator!=(const view& lhs, const view& rhs) { return !(lhs == rhs); } void view::destroy() noexcept { switch (static_cast<int>(_type)) { #define BSONCXX_ENUM(type, val) \ case val: \ _b_##type.~b_##type(); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } } } // namespace bson_value } // namespace types BSONCXX_INLINE_NAMESPACE_END } // namespace bsoncxx <commit_msg>default added (#820)<commit_after>// Copyright 2020 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdlib> #include <bsoncxx/exception/error_code.hpp> #include <bsoncxx/exception/exception.hpp> #include <bsoncxx/private/libbson.hh> #include <bsoncxx/private/suppress_deprecation_warnings.hh> #include <bsoncxx/types/bson_value/view.hpp> #include <bsoncxx/types/private/convert.hh> #include <bsoncxx/config/private/prelude.hh> #define BSONCXX_CITER \ bson_iter_t iter; \ bson_iter_init_from_data_at_offset(&iter, raw, length, offset, keylen); #define BSONCXX_TYPE_CHECK(name) \ do { \ if (type() != bsoncxx::type::k_##name) { \ throw bsoncxx::exception{error_code::k_need_element_type_k_##name}; \ } \ } while (0) namespace bsoncxx { BSONCXX_INLINE_NAMESPACE_BEGIN namespace types { namespace bson_value { view::view() noexcept : view(nullptr) {} // Boost doesn't mark the copy constructor and copy-assignment operator of string_ref as noexcept // so we can't rely on automatic noexcept propagation. It really is though, so it is OK. #if !defined(BSONCXX_POLY_USE_BOOST) #define BSONCXX_ENUM(name, val) \ view::view(b_##name value) noexcept \ : _type(static_cast<bsoncxx::type>(val)), _b_##name(std::move(value)) { \ static_assert(std::is_nothrow_copy_constructible<b_##name>::value, "Copy may throw"); \ static_assert(std::is_nothrow_copy_assignable<b_##name>::value, "Copy may throw"); \ static_assert(std::is_nothrow_destructible<b_##name>::value, "Destruction may throw"); \ } #else #define BSONCXX_ENUM(name, val) \ view::view(b_##name value) noexcept \ : _type(static_cast<bsoncxx::type>(val)), _b_##name(std::move(value)) { \ static_assert(std::is_nothrow_destructible<b_##name>::value, "Destruction may throw"); \ } #endif #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM view::view(const view& rhs) noexcept { switch (static_cast<int>(rhs._type)) { #define BSONCXX_ENUM(type, val) \ case val: \ new (&_b_##type) b_##type(rhs.get_##type()); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } _type = rhs._type; } view& view::operator=(const view& rhs) noexcept { if (this == &rhs) { return *this; } destroy(); switch (static_cast<int>(rhs._type)) { #define BSONCXX_ENUM(type, val) \ case val: \ new (&_b_##type) b_##type(rhs.get_##type()); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM default : break; } _type = rhs._type; return *this; } view::~view() { destroy(); } bsoncxx::type view::type() const { return _type; } #define BSONCXX_ENUM(type, val) \ const types::b_##type& view::get_##type() const { \ BSONCXX_TYPE_CHECK(type); \ return _b_##type; \ } #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM const types::b_string& view::get_utf8() const { BSONCXX_TYPE_CHECK(string); return _b_string; } view::view(const std::uint8_t* raw, std::uint32_t length, std::uint32_t offset, std::uint32_t keylen) { BSONCXX_CITER; auto value = bson_iter_value(&iter); _init((void*)value); } view::view(void* internal_value) noexcept { _init(internal_value); } void view::_init(void* internal_value) noexcept { if (!internal_value) { _type = bsoncxx::type::k_null; _b_null = bsoncxx::types::b_null{}; return; } bson_value_t* v = (bson_value_t*)(internal_value); _type = static_cast<bsoncxx::type>(v->value_type); switch (_type) { #define BSONCXX_ENUM(name, val) \ case bsoncxx::type::k_##name: { \ convert_from_libbson(v, &_b_##name); \ break; \ } #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM default: BSONCXX_UNREACHABLE; } } bool operator==(const view& lhs, const view& rhs) { if (lhs.type() != rhs.type()) { return false; } switch (static_cast<int>(lhs.type())) { #define BSONCXX_ENUM(type, val) \ case val: \ return lhs.get_##type() == rhs.get_##type(); #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } // Silence compiler warnings about failing to return a value. BSONCXX_UNREACHABLE; } bool operator!=(const view& lhs, const view& rhs) { return !(lhs == rhs); } void view::destroy() noexcept { switch (static_cast<int>(_type)) { #define BSONCXX_ENUM(type, val) \ case val: \ _b_##type.~b_##type(); \ break; #include <bsoncxx/enums/type.hpp> #undef BSONCXX_ENUM } } } // namespace bson_value } // namespace types BSONCXX_INLINE_NAMESPACE_END } // namespace bsoncxx <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2013/07/15 // Author: Mike Ovsiannikov // // Copyright 2013 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Ssl socket layer unit test. // //---------------------------------------------------------------------------- #include "kfsio/SslFilter.h" #include "kfsio/Globals.h" #include "kfsio/NetConnection.h" #include "kfsio/Acceptor.h" #include "kfsio/NetManager.h" #include "qcdio/qcdebug.h" #include "common/MsgLogger.h" #include "common/Properties.h" #include <iostream> #include <string> #include <sstream> namespace KFS { using std::cerr; using std::cout; using std::string; using std::istringstream; class SslFilterTest : private IAcceptorOwner, private SslFilter::ServerPsk { public: static int Run( int inArgsCount, char** inArgsPtr) { libkfsio::InitGlobals(); SslFilter::Error theErr = SslFilter::Initialize(); int theRet; if (theErr) { cerr << "SslFilter init error: " << SslFilter::GetErrorMsg(theErr) << "\n"; theRet = 1; } else { SslFilterTest theTest; theRet = theTest.Run(inArgsCount, inArgsPtr); } theErr = SslFilter::Cleanup(); if (theErr) { cerr << "SslFilter cleanup error: " << SslFilter::GetErrorMsg(theErr) << "\n"; if (theRet == 0) { theRet = 1; } } libkfsio::DestroyGlobals(); return theRet; } private: Properties mProperties; NetManager mNetManager; Acceptor* mAcceptorPtr; SslFilter::Ctx* mSslCtxPtr; string mPskIdentity; string mPskKey; int mMaxReadAhead; int mMaxWriteBehind; class Responder : public KfsCallbackObj { public: Responder( SslFilter::Ctx& inCtx, SslFilter::ServerPsk& inServerPsk, NetConnectionPtr& inConnectionPtr, int inMaxReadAhead, int inMaxWriteBehind) : mConnectionPtr(inConnectionPtr), mSslFilter( inCtx, 0, // inPskDataPtr 0, // inPskDataLen 0, // inPskCliIdendityPtr &inServerPsk, false // inDeleteOnCloseFlag ), mRecursionCount(0), mCloseConnectionFlag(false), mMaxReadAhead(inMaxReadAhead), mMaxWriteBehind(inMaxWriteBehind) { QCASSERT(inConnectionPtr); SET_HANDLER(this, &Responder::EventHandler); mConnectionPtr->SetFilter(&mSslFilter); mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } int EventHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_READ: { IOBuffer& theIoBuf = mConnectionPtr->GetInBuffer(); QCASSERT(&theIoBuf == inEventDataPtr); // Simple echo. mConnectionPtr->Write(&theIoBuf); break; } case EVENT_NET_WROTE: if (mCloseConnectionFlag && ! mConnectionPtr->IsWriteReady()) { mConnectionPtr->Close(); } break; case EVENT_INACTIVITY_TIMEOUT: case EVENT_NET_ERROR: if (mConnectionPtr->IsGood() && mConnectionPtr->IsWriteReady()) { mCloseConnectionFlag = mCloseConnectionFlag || ! mConnectionPtr->HasPendingRead(); break; } mConnectionPtr->Close(); mConnectionPtr->GetInBuffer().Clear(); break; default: QCASSERT(!"Unexpected event code"); break; } QCASSERT(mRecursionCount >= 1); if (mRecursionCount <= 1) { mConnectionPtr->StartFlush(); if (mConnectionPtr->IsGood()) { const int kIoTimeout = 60; const int kIdleTimeout = 600; mConnectionPtr->SetInactivityTimeout( mConnectionPtr->IsWriteReady() ? kIoTimeout : kIdleTimeout); if (mConnectionPtr->IsReadReady()) { if (IsOverWriteBehindLimit()) { // Shut down read until client unloads the data. mConnectionPtr->SetMaxReadAhead(0); } } else { if (! mCloseConnectionFlag && ! IsOverWriteBehindLimit()) { // Set read back again. mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } } } else { delete this; return 0; } } mRecursionCount--; return 0; } private: NetConnectionPtr const mConnectionPtr; SslFilter mSslFilter; int mRecursionCount; bool mCloseConnectionFlag; const int mMaxReadAhead; const int mMaxWriteBehind; bool IsOverWriteBehindLimit() const { return (mConnectionPtr->GetNumBytesToWrite() > mMaxWriteBehind); } private: Responder( const Responder& inResponder); Responder& operator=( const Responder& inResponder); }; SslFilterTest() : IAcceptorOwner(), ServerPsk(), mProperties(), mNetManager(), mAcceptorPtr(0), mSslCtxPtr(0), mPskIdentity(), mPskKey(), mMaxReadAhead((8 << 10) - 1), mMaxWriteBehind((8 << 10) - 1) {} virtual ~SslFilterTest() { delete mAcceptorPtr; } int RunSelf( int inArgsCount, char** inArgsPtr) { delete mAcceptorPtr; mAcceptorPtr = 0; string thePropsStr; const char kDelim = '='; const bool kVerboseFlag = true; for (int i = 1; i < inArgsCount; ) { if (strcmp(inArgsPtr[i], "-c") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } if (mProperties.loadProperties( inArgsPtr[i], kDelim, kVerboseFlag)) { cerr << "error reading properties file: " << inArgsPtr[i] << "\n"; return 1; } } else if (strcmp(inArgsPtr[i], "-D") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } thePropsStr += inArgsPtr[i]; thePropsStr += "\n"; } else { Usage(inArgsPtr[0]); return 1; } } if (! thePropsStr.empty()) { istringstream theInStream(thePropsStr); if (mProperties.loadProperties( theInStream, kDelim, kVerboseFlag)) { cerr << "error parsing arguments\n"; return 1; } } MsgLogger::Init(mProperties, "SslFilterTest."); if (! MsgLogger::GetLogger()) { cerr << "messsage logger initialization failure\n"; return 1; } MsgLogger::Stop(); return 0; } void Usage( const char* inNamePtr) { cerr << "Usage " << (inNamePtr ? inNamePtr : "") << ":\n" " -c <config file name>\n" " -D config-key=config-value\n" ; } virtual KfsCallbackObj* CreateKfsCallbackObj( NetConnectionPtr& inConnPtr) { return (mSslCtxPtr ? 0 : new Responder( *mSslCtxPtr, *this, inConnPtr, mMaxReadAhead, mMaxWriteBehind )); } virtual unsigned long GetPsk( const char* inIdentityPtr, unsigned char* inPskBufferPtr, unsigned int inPskBufferLen) { KFS_LOG_STREAM_DEBUG << "GetPsk:" " identity: " << (inIdentityPtr ? inIdentityPtr : "null") << " buffer: " << (const void*)inPskBufferPtr << " buflen: " << inPskBufferLen << KFS_LOG_EOM; if (inPskBufferLen <= mPskKey.size()) { return 0; } if (mPskIdentity != (inIdentityPtr ? inIdentityPtr : "")) { return 0; } memcpy(inPskBufferPtr, mPskKey.data(), mPskKey.size()); return mPskKey.size(); } private: SslFilterTest( const SslFilterTest& inTest); SslFilterTest& operator=( const SslFilterTest& inTest); }; } int main( int inArgsCount, char** inArgsPtr) { return KFS::SslFilterTest::Run(inArgsCount, inArgsPtr); } <commit_msg>Ssl filter test: fix receive / read EOF handling by setting read ahead to 0.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2013/07/15 // Author: Mike Ovsiannikov // // Copyright 2013 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Ssl socket layer unit test. // //---------------------------------------------------------------------------- #include "kfsio/SslFilter.h" #include "kfsio/Globals.h" #include "kfsio/NetConnection.h" #include "kfsio/Acceptor.h" #include "kfsio/NetManager.h" #include "qcdio/qcdebug.h" #include "common/MsgLogger.h" #include "common/Properties.h" #include <iostream> #include <string> #include <sstream> namespace KFS { using std::cerr; using std::cout; using std::string; using std::istringstream; class SslFilterTest : private IAcceptorOwner, private SslFilter::ServerPsk { public: static int Run( int inArgsCount, char** inArgsPtr) { libkfsio::InitGlobals(); SslFilter::Error theErr = SslFilter::Initialize(); int theRet; if (theErr) { cerr << "SslFilter init error: " << SslFilter::GetErrorMsg(theErr) << "\n"; theRet = 1; } else { SslFilterTest theTest; theRet = theTest.Run(inArgsCount, inArgsPtr); } theErr = SslFilter::Cleanup(); if (theErr) { cerr << "SslFilter cleanup error: " << SslFilter::GetErrorMsg(theErr) << "\n"; if (theRet == 0) { theRet = 1; } } libkfsio::DestroyGlobals(); return theRet; } private: Properties mProperties; NetManager mNetManager; Acceptor* mAcceptorPtr; SslFilter::Ctx* mSslCtxPtr; string mPskIdentity; string mPskKey; int mMaxReadAhead; int mMaxWriteBehind; class Responder : public KfsCallbackObj { public: Responder( SslFilter::Ctx& inCtx, SslFilter::ServerPsk& inServerPsk, NetConnectionPtr& inConnectionPtr, int inMaxReadAhead, int inMaxWriteBehind) : mConnectionPtr(inConnectionPtr), mSslFilter( inCtx, 0, // inPskDataPtr 0, // inPskDataLen 0, // inPskCliIdendityPtr &inServerPsk, false // inDeleteOnCloseFlag ), mRecursionCount(0), mCloseConnectionFlag(false), mMaxReadAhead(inMaxReadAhead), mMaxWriteBehind(inMaxWriteBehind) { QCASSERT(inConnectionPtr); SET_HANDLER(this, &Responder::EventHandler); mConnectionPtr->SetFilter(&mSslFilter); mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } int EventHandler( int inEventCode, void* inEventDataPtr) { mRecursionCount++; QCASSERT(mRecursionCount >= 1); switch (inEventCode) { case EVENT_NET_READ: { IOBuffer& theIoBuf = mConnectionPtr->GetInBuffer(); QCASSERT(&theIoBuf == inEventDataPtr); // Simple echo. mConnectionPtr->Write(&theIoBuf); break; } case EVENT_NET_WROTE: if (mCloseConnectionFlag && ! mConnectionPtr->IsWriteReady()) { mConnectionPtr->Close(); } break; case EVENT_NET_ERROR: mConnectionPtr->SetMaxReadAhead(0); if (mConnectionPtr->IsGood() && mConnectionPtr->IsWriteReady()) { mCloseConnectionFlag = mCloseConnectionFlag || ! mConnectionPtr->HasPendingRead(); break; } // Fall through case EVENT_INACTIVITY_TIMEOUT: mConnectionPtr->Close(); mConnectionPtr->GetInBuffer().Clear(); break; default: QCASSERT(!"Unexpected event code"); break; } QCASSERT(mRecursionCount >= 1); if (mRecursionCount <= 1) { mConnectionPtr->StartFlush(); if (mConnectionPtr->IsGood()) { const int kIoTimeout = 60; const int kIdleTimeout = 600; mConnectionPtr->SetInactivityTimeout( mConnectionPtr->IsWriteReady() ? kIoTimeout : kIdleTimeout); if (mConnectionPtr->IsReadReady()) { if (IsOverWriteBehindLimit()) { // Shut down read until client unloads the data. mConnectionPtr->SetMaxReadAhead(0); } } else { if (! mCloseConnectionFlag && ! IsOverWriteBehindLimit()) { // Set read back again. mConnectionPtr->SetMaxReadAhead(mMaxReadAhead); } } } else { delete this; return 0; } } mRecursionCount--; return 0; } private: NetConnectionPtr const mConnectionPtr; SslFilter mSslFilter; int mRecursionCount; bool mCloseConnectionFlag; const int mMaxReadAhead; const int mMaxWriteBehind; bool IsOverWriteBehindLimit() const { return (mConnectionPtr->GetNumBytesToWrite() > mMaxWriteBehind); } private: Responder( const Responder& inResponder); Responder& operator=( const Responder& inResponder); }; SslFilterTest() : IAcceptorOwner(), ServerPsk(), mProperties(), mNetManager(), mAcceptorPtr(0), mSslCtxPtr(0), mPskIdentity(), mPskKey(), mMaxReadAhead((8 << 10) - 1), mMaxWriteBehind((8 << 10) - 1) {} virtual ~SslFilterTest() { delete mAcceptorPtr; } int RunSelf( int inArgsCount, char** inArgsPtr) { delete mAcceptorPtr; mAcceptorPtr = 0; string thePropsStr; const char kDelim = '='; const bool kVerboseFlag = true; for (int i = 1; i < inArgsCount; ) { if (strcmp(inArgsPtr[i], "-c") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } if (mProperties.loadProperties( inArgsPtr[i], kDelim, kVerboseFlag)) { cerr << "error reading properties file: " << inArgsPtr[i] << "\n"; return 1; } } else if (strcmp(inArgsPtr[i], "-D") == 0) { if (inArgsCount <= ++i) { Usage(inArgsPtr[0]); return 1; } thePropsStr += inArgsPtr[i]; thePropsStr += "\n"; } else { Usage(inArgsPtr[0]); return 1; } } if (! thePropsStr.empty()) { istringstream theInStream(thePropsStr); if (mProperties.loadProperties( theInStream, kDelim, kVerboseFlag)) { cerr << "error parsing arguments\n"; return 1; } } MsgLogger::Init(mProperties, "SslFilterTest."); if (! MsgLogger::GetLogger()) { cerr << "messsage logger initialization failure\n"; return 1; } MsgLogger::Stop(); return 0; } void Usage( const char* inNamePtr) { cerr << "Usage " << (inNamePtr ? inNamePtr : "") << ":\n" " -c <config file name>\n" " -D config-key=config-value\n" ; } virtual KfsCallbackObj* CreateKfsCallbackObj( NetConnectionPtr& inConnPtr) { return (mSslCtxPtr ? 0 : new Responder( *mSslCtxPtr, *this, inConnPtr, mMaxReadAhead, mMaxWriteBehind )); } virtual unsigned long GetPsk( const char* inIdentityPtr, unsigned char* inPskBufferPtr, unsigned int inPskBufferLen) { KFS_LOG_STREAM_DEBUG << "GetPsk:" " identity: " << (inIdentityPtr ? inIdentityPtr : "null") << " buffer: " << (const void*)inPskBufferPtr << " buflen: " << inPskBufferLen << KFS_LOG_EOM; if (inPskBufferLen <= mPskKey.size()) { return 0; } if (mPskIdentity != (inIdentityPtr ? inIdentityPtr : "")) { return 0; } memcpy(inPskBufferPtr, mPskKey.data(), mPskKey.size()); return mPskKey.size(); } private: SslFilterTest( const SslFilterTest& inTest); SslFilterTest& operator=( const SslFilterTest& inTest); }; } int main( int inArgsCount, char** inArgsPtr) { return KFS::SslFilterTest::Run(inArgsCount, inArgsPtr); } <|endoftext|>
<commit_before>/* * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit * COPYRIGHT (C) 2012-2015, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE SIMPLIFIED BSD LICENSE: * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md */ #include "chronotext/sound/SoundManager.h" #include "chronotext/Context.h" #include "fmod_errors.h" using namespace std; using namespace ci; namespace chr { atomic<bool> SoundManager::LOG_VERBOSE (false); atomic<bool> SoundManager::PROBE_MEMORY (false); SoundManager::~SoundManager() { uninit(); } bool SoundManager::isValid() { return initialized; } bool SoundManager::init(int maxChannels, FMOD_INITFLAGS flags) { if (!initialized) { FMOD::System_Create(&system); FMOD_RESULT result = system->init(maxChannels, flags, nullptr); if (result) { system->release(); system = nullptr; } else { system->getMasterChannelGroup(&masterGroup); initialized = true; } } return initialized; } void SoundManager::uninit() { if (initialized) { discardEffects(); assert(playingEffects.empty()); effects.clear(); listeners.clear(); system->close(); system->release(); system = nullptr; // --- initialized = false; } } void SoundManager::pause() { if (initialized) { masterGroup->setPaused(true); system->update(); // NECESSARY ON ANDROID, OTHERWISE PAUSE-REQUEST WILL NOT BE EFFECTIVE } } void SoundManager::resume() { if (initialized) { masterGroup->setPaused(false); system->update(); // PROBABLY NOT PURELY NECESSARY... } } void SoundManager::update() { if (initialized) { system->update(); // --- vector<Event> completedEvents; for (auto &element : playingEffects) { auto playingId = element.first; auto channelId = element.second.first; auto uniqueId = element.second.second; FMOD::Channel *channel; system->getChannel(channelId, &channel); bool playing; channel->isPlaying(&playing); if (!playing) { completedEvents.emplace_back(Event(EVENT_COMPLETED, findByUniqueId(uniqueId), channelId, playingId)); } } for (auto &event : completedEvents) { playingEffects.erase(event.playingId); dispatchEvent(event); } } } void SoundManager::addListener(Listener *listener) { listeners.insert(listener); } void SoundManager::removeListener(Listener *listener) { listeners.erase(listener); } Effect::Ref SoundManager::getEffect(const Effect::Request &request) { if (initialized) { auto it = effects.find(request); if (it != effects.end()) { return it->second; } auto sound = loadSound(system, request); // CAN THROW auto effect = Effect::Ref(new Effect(request, sound, ++effectCounter)); // make_shared CAN'T BE USED WITH PROTECTED CONSTRUCTORS effects[request] = effect; return effect; } return nullptr; } Effect::Ref SoundManager::findEffect(const Effect::Request &request) const { auto it = effects.find(request); if (it != effects.end()) { return it->second; } return nullptr; } void SoundManager::discardEffect(Effect::Ref effect) { if (initialized && effect) { stopEffect(effect); effect->resetSound(); } } bool SoundManager::reloadEffect(Effect::Ref effect) { if (initialized && effect) { if (!effect->sound) { effect->setSound(loadSound(system, effect->request)); } return effect->sound; } return false; } void SoundManager::discardEffects(int tag) { for (auto &element : effects) { if ((tag < 0) || (tag == element.second->request.tag)) { discardEffect(element.second); } } } void SoundManager::reloadEffects(int tag) { for (auto &element : effects) { if ((tag < 0) || (tag == element.second->request.tag)) { reloadEffect(element.second); } } } void SoundManager::stopEffect(Effect::Ref effect) { if (effect) { vector<int> playingIdsToStop; for (auto &element : playingEffects) { if (element.second.second == effect->uniqueId) { playingIdsToStop.push_back(element.first); } } for (auto playingId : playingIdsToStop) { stopEffect(playingId); } } } void SoundManager::stopEffects(int tag) { vector<int> playingIdsToStop; for (auto &element : playingEffects) { playingIdsToStop.push_back(element.first); } for (auto &playingId : playingIdsToStop) { stopEffect(playingId, tag); } } bool SoundManager::pauseEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->setPaused(true); return true; } } return false; } bool SoundManager::resumeEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->setPaused(false); return true; } } return false; } bool SoundManager::stopEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->stop(); playingEffects.erase(it); dispatchEvent(Event(EVENT_STOPPED, effect, channelId, playingId)); return true; } } return false; } void SoundManager::setMute(bool mute) { if (initialized) { masterGroup->setMute(mute); } } bool SoundManager::isMute() { bool mute = false; if (initialized) { masterGroup->getMute(&mute); } return mute; } float SoundManager::getVolume() { float volume = 0; if (initialized) { masterGroup->getVolume(&volume); } return volume; } void SoundManager::setVolume(float volume) { if (initialized) { masterGroup->setVolume(volume); } } int SoundManager::playEffect(Effect::Ref effect, int loopCount, float volume) { if (reloadEffect(effect)) { auto channel = playSound(effect->sound, loopCount, (volume == 1) ? effect->request.volume : volume); int channelId; channel->getIndex(&channelId); interruptChannel(channelId); int playingId = ++playCounter; playingEffects[playingId] = make_pair(channelId, effect->uniqueId); dispatchEvent(Event(EVENT_STARTED, effect, channelId, playingId)); return playingId; } return 0; } FMOD::Channel* SoundManager::playSound(FMOD::Sound *sound, int loopCount, float volume) { if (initialized) { FMOD::Channel *channel; FMOD_RESULT result = system->playSound(sound, masterGroup, true, &channel); if (result) { throw EXCEPTION(SoundManager, "UNABLE TO PLAY SOUND | REASON: " + writeError(result)); } if (loopCount) { channel->setLoopCount(loopCount); channel->setMode(FMOD_LOOP_NORMAL); } else { channel->setMode(FMOD_LOOP_OFF); } channel->setVolume(volume); channel->setPaused(false); return channel; } return nullptr; } bool SoundManager::interruptChannel(int channelId) { for (auto &element : playingEffects) { if (channelId == element.second.first) { auto playingId = element.first; auto effect = findByUniqueId(element.second.second); playingEffects.erase(playingId); dispatchEvent(Event(EVENT_INTERRUPTED, effect, channelId, playingId)); return true; } } return false; } Effect::Ref SoundManager::findByUniqueId(int uniqueId) { for (auto &element : effects) { if (uniqueId == element.second->uniqueId) { return element.second; } } assert(false); // UNREACHABLE (AS LONG AS THE FUNCTION IS NOT PUBLIC: uniqueId IS SAFE) } void SoundManager::dispatchEvent(const Event &event) { for (auto &listener : listeners) { listener->handleEvent(event); } } // --- MemoryInfo SoundManager::memoryInfo[1]; map<FMOD::Sound*, SoundManager::Record> SoundManager::records; FMOD::Sound* SoundManager::loadSound(FMOD::System *system, const Effect::Request &request) { FMOD::Sound *sound = nullptr; int currentalloced1; int maxalloced1; FMOD_RESULT result = FMOD::Memory_GetStats(&currentalloced1, &maxalloced1); if (!result) { if (SoundManager::PROBE_MEMORY) { memoryInfo[0] = getMemoryInfo(); } if (request.forceMemoryLoad || !request.inputSource->hasFileName()) { auto buffer = request.inputSource->loadDataSource()->getBuffer(); FMOD_CREATESOUNDEXINFO exinfo; memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO)); exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO); exinfo.length = (unsigned int)buffer.getDataSize(); result = system->createSound(static_cast<const char*>(buffer.getData()), FMOD_DEFAULT | FMOD_OPENMEMORY, &exinfo, &sound); } else { result = system->createSound(request.inputSource->getFilePath().c_str(), FMOD_DEFAULT, nullptr, &sound); } } if (result) { throw EXCEPTION(SoundManager, "UNABLE TO LOAD SOUND | REASON: " + writeError(result)); } if (sound) { int currentalloced2; int maxalloced2; FMOD::Memory_GetStats(&currentalloced2, &maxalloced2); auto memoryUsage = currentalloced2 - currentalloced1; records[sound] = Record({memoryUsage, memoryInfo[0]}); } return sound; } double SoundManager::getSoundDuration(FMOD::Sound *sound) { if (sound) { unsigned int length; sound->getLength(&length, FMOD_TIMEUNIT_MS); return length / 1000.0; } return 0; } string SoundManager::writeError(FMOD_RESULT result) { return string(FMOD_ErrorString(result)); } } <commit_msg>sound/SoundManager: FIXING REGRESSION (AFFECTING ANDROID ONLY)<commit_after>/* * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit * COPYRIGHT (C) 2012-2015, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE SIMPLIFIED BSD LICENSE: * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md */ #include "chronotext/sound/SoundManager.h" #include "chronotext/Context.h" #include "fmod_errors.h" using namespace std; using namespace ci; namespace chr { atomic<bool> SoundManager::LOG_VERBOSE (false); atomic<bool> SoundManager::PROBE_MEMORY (false); SoundManager::~SoundManager() { uninit(); } bool SoundManager::isValid() { return initialized; } bool SoundManager::init(int maxChannels, FMOD_INITFLAGS flags) { if (!initialized) { FMOD::System_Create(&system); FMOD_RESULT result = system->init(maxChannels, flags, nullptr); if (result) { system->release(); system = nullptr; } else { system->getMasterChannelGroup(&masterGroup); initialized = true; } } return initialized; } void SoundManager::uninit() { if (initialized) { discardEffects(); assert(playingEffects.empty()); effects.clear(); listeners.clear(); system->close(); system->release(); system = nullptr; // --- initialized = false; } } void SoundManager::pause() { if (initialized) { masterGroup->setPaused(true); system->update(); // NECESSARY ON ANDROID, OTHERWISE PAUSE-REQUEST WILL NOT BE EFFECTIVE } } void SoundManager::resume() { if (initialized) { masterGroup->setPaused(false); system->update(); // PROBABLY NOT PURELY NECESSARY... } } void SoundManager::update() { if (initialized) { system->update(); // --- vector<Event> completedEvents; for (auto &element : playingEffects) { auto playingId = element.first; auto channelId = element.second.first; auto uniqueId = element.second.second; FMOD::Channel *channel; system->getChannel(channelId, &channel); bool playing; channel->isPlaying(&playing); if (!playing) { completedEvents.emplace_back(Event(EVENT_COMPLETED, findByUniqueId(uniqueId), channelId, playingId)); } } for (auto &event : completedEvents) { playingEffects.erase(event.playingId); dispatchEvent(event); } } } void SoundManager::addListener(Listener *listener) { listeners.insert(listener); } void SoundManager::removeListener(Listener *listener) { listeners.erase(listener); } Effect::Ref SoundManager::getEffect(const Effect::Request &request) { if (initialized) { auto it = effects.find(request); if (it != effects.end()) { return it->second; } auto sound = loadSound(system, request); // CAN THROW auto effect = Effect::Ref(new Effect(request, sound, ++effectCounter)); // make_shared CAN'T BE USED WITH PROTECTED CONSTRUCTORS effects[request] = effect; return effect; } return nullptr; } Effect::Ref SoundManager::findEffect(const Effect::Request &request) const { auto it = effects.find(request); if (it != effects.end()) { return it->second; } return nullptr; } void SoundManager::discardEffect(Effect::Ref effect) { if (initialized && effect) { stopEffect(effect); effect->resetSound(); } } bool SoundManager::reloadEffect(Effect::Ref effect) { if (initialized && effect) { if (!effect->sound) { effect->setSound(loadSound(system, effect->request)); } return effect->sound; } return false; } void SoundManager::discardEffects(int tag) { for (auto &element : effects) { if ((tag < 0) || (tag == element.second->request.tag)) { discardEffect(element.second); } } } void SoundManager::reloadEffects(int tag) { for (auto &element : effects) { if ((tag < 0) || (tag == element.second->request.tag)) { reloadEffect(element.second); } } } void SoundManager::stopEffect(Effect::Ref effect) { if (effect) { vector<int> playingIdsToStop; for (auto &element : playingEffects) { if (element.second.second == effect->uniqueId) { playingIdsToStop.push_back(element.first); } } for (auto playingId : playingIdsToStop) { stopEffect(playingId); } } } void SoundManager::stopEffects(int tag) { vector<int> playingIdsToStop; for (auto &element : playingEffects) { playingIdsToStop.push_back(element.first); } for (auto &playingId : playingIdsToStop) { stopEffect(playingId, tag); } } bool SoundManager::pauseEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->setPaused(true); return true; } } return false; } bool SoundManager::resumeEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->setPaused(false); return true; } } return false; } bool SoundManager::stopEffect(int playingId, int tag) { auto it = playingEffects.find(playingId); if (it != playingEffects.end()) { auto channelId = it->second.first; auto effect = findByUniqueId(it->second.second); if ((tag < 0) || (effect->request.tag == tag)) { FMOD::Channel *channel; system->getChannel(channelId, &channel); channel->stop(); playingEffects.erase(it); dispatchEvent(Event(EVENT_STOPPED, effect, channelId, playingId)); return true; } } return false; } void SoundManager::setMute(bool mute) { if (initialized) { masterGroup->setMute(mute); } } bool SoundManager::isMute() { bool mute = false; if (initialized) { masterGroup->getMute(&mute); } return mute; } float SoundManager::getVolume() { float volume = 0; if (initialized) { masterGroup->getVolume(&volume); } return volume; } void SoundManager::setVolume(float volume) { if (initialized) { masterGroup->setVolume(volume); } } int SoundManager::playEffect(Effect::Ref effect, int loopCount, float volume) { if (reloadEffect(effect)) { auto channel = playSound(effect->sound, loopCount, (volume == 1) ? effect->request.volume : volume); int channelId; channel->getIndex(&channelId); interruptChannel(channelId); int playingId = ++playCounter; playingEffects[playingId] = make_pair(channelId, effect->uniqueId); dispatchEvent(Event(EVENT_STARTED, effect, channelId, playingId)); return playingId; } return 0; } FMOD::Channel* SoundManager::playSound(FMOD::Sound *sound, int loopCount, float volume) { if (initialized) { FMOD::Channel *channel; FMOD_RESULT result = system->playSound(sound, masterGroup, true, &channel); if (result) { throw EXCEPTION(SoundManager, "UNABLE TO PLAY SOUND | REASON: " + writeError(result)); } if (loopCount) { channel->setLoopCount(loopCount); channel->setMode(FMOD_LOOP_NORMAL); } else { channel->setMode(FMOD_LOOP_OFF); } channel->setVolume(volume); channel->setPaused(false); return channel; } return nullptr; } bool SoundManager::interruptChannel(int channelId) { for (auto &element : playingEffects) { if (channelId == element.second.first) { auto playingId = element.first; auto effect = findByUniqueId(element.second.second); playingEffects.erase(playingId); dispatchEvent(Event(EVENT_INTERRUPTED, effect, channelId, playingId)); return true; } } return false; } Effect::Ref SoundManager::findByUniqueId(int uniqueId) { for (auto &element : effects) { if (uniqueId == element.second->uniqueId) { return element.second; } } assert(false); // UNREACHABLE (AS LONG AS THE FUNCTION IS NOT PUBLIC: uniqueId IS SAFE) } void SoundManager::dispatchEvent(const Event &event) { for (auto &listener : listeners) { listener->handleEvent(event); } } // --- MemoryInfo SoundManager::memoryInfo[1]; map<FMOD::Sound*, SoundManager::Record> SoundManager::records; FMOD::Sound* SoundManager::loadSound(FMOD::System *system, const Effect::Request &request) { FMOD::Sound *sound = nullptr; int currentalloced1; int maxalloced1; FMOD_RESULT result = FMOD::Memory_GetStats(&currentalloced1, &maxalloced1); if (!result) { if (SoundManager::PROBE_MEMORY) { memoryInfo[0] = getMemoryInfo(); } if (request.forceMemoryLoad || !request.inputSource->isFile()) { auto buffer = request.inputSource->loadDataSource()->getBuffer(); FMOD_CREATESOUNDEXINFO exinfo; memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO)); exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO); exinfo.length = (unsigned int)buffer.getDataSize(); result = system->createSound(static_cast<const char*>(buffer.getData()), FMOD_DEFAULT | FMOD_OPENMEMORY, &exinfo, &sound); } else { result = system->createSound(request.inputSource->getFilePath().c_str(), FMOD_DEFAULT, nullptr, &sound); } } if (result) { throw EXCEPTION(SoundManager, "UNABLE TO LOAD SOUND | REASON: " + writeError(result)); } if (sound) { int currentalloced2; int maxalloced2; FMOD::Memory_GetStats(&currentalloced2, &maxalloced2); auto memoryUsage = currentalloced2 - currentalloced1; records[sound] = Record({memoryUsage, memoryInfo[0]}); } return sound; } double SoundManager::getSoundDuration(FMOD::Sound *sound) { if (sound) { unsigned int length; sound->getLength(&length, FMOD_TIMEUNIT_MS); return length / 1000.0; } return 0; } string SoundManager::writeError(FMOD_RESULT result) { return string(FMOD_ErrorString(result)); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdundo.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:12:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SD_SDUNDO_HXX #define _SD_SDUNDO_HXX #ifndef _UNDO_HXX //autogen #include <svtools/undo.hxx> #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif class SdDrawDocument; class SD_DLLPUBLIC SdUndoAction : public SfxUndoAction { String aComment; protected: SdDrawDocument* pDoc; public: TYPEINFO(); SdUndoAction(SdDrawDocument* pSdDrawDocument) : pDoc(pSdDrawDocument) {} virtual ~SdUndoAction() {} virtual BOOL CanRepeat(SfxRepeatTarget& rView) const; virtual void Repeat(SfxRepeatTarget& rView); void SetComment(String& rStr) { aComment = rStr; } virtual String GetComment() const { return aComment; } virtual SdUndoAction* Clone() const { return NULL; } }; #endif // _SD_SDUNDO_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.4.374); FILE MERGED 2005/09/05 13:20:02 rt 1.4.374.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdundo.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:02:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_SDUNDO_HXX #define _SD_SDUNDO_HXX #ifndef _UNDO_HXX //autogen #include <svtools/undo.hxx> #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif class SdDrawDocument; class SD_DLLPUBLIC SdUndoAction : public SfxUndoAction { String aComment; protected: SdDrawDocument* pDoc; public: TYPEINFO(); SdUndoAction(SdDrawDocument* pSdDrawDocument) : pDoc(pSdDrawDocument) {} virtual ~SdUndoAction() {} virtual BOOL CanRepeat(SfxRepeatTarget& rView) const; virtual void Repeat(SfxRepeatTarget& rView); void SetComment(String& rStr) { aComment = rStr; } virtual String GetComment() const { return aComment; } virtual SdUndoAction* Clone() const { return NULL; } }; #endif // _SD_SDUNDO_HXX <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org>" // Copyright 2007 Inge Wallin <ingwa@kde.org>" // #include "TextureTile.h" #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtGui/QFont> #include <QtGui/QPainter> #include <QtGui/QPen> #include <cmath> #include "MarbleDirs.h" #include "TileLoader.h" static uint **jumpTableFromQImage32( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine() / 4; uint *data = (QRgb*)(img.scanLine(0)); uint **jumpTable = new uint*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } static uchar **jumpTableFromQImage8( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine(); uchar *data = img.bits(); uchar **jumpTable = new uchar*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } TextureTile::TextureTile( int id ) : QObject(), jumpTable8(0), jumpTable32(0), m_id(id), m_rawtile( QImage() ), m_depth(0), m_used(false)/*, m_sun_shading(false)*/ { } TextureTile::~TextureTile() { switch ( m_depth ) { case 32: delete [] jumpTable32; break; case 8: delete [] jumpTable8; break; default: qDebug("Color m_depth of a tile could not be retrieved. Exiting."); exit(-1); } // qDebug() << "Tile deleted: " << m_id; // delete m_rawtile; } void TextureTile::loadTile( int x, int y, int level, const QString& theme, bool requestTileUpdate, bool sun_shading ) { // qDebug() << "Entered loadTile( int, int, int) of Tile" << m_id; m_used = true; // Needed to avoid frequent deletion of tiles QString absfilename; // qDebug() << "Requested tile level" << level; // If the tile level offers the requested tile then load it. // Otherwise cycle from the requested tilelevel down to one where // the requested area is covered. Then scale the area to create a // replacement for the tile that has been requested. for ( int i = level; i > -1; --i ) { double origx1 = (double)(x) / (double)( TileLoader::levelToRow( level ) ); double origy1 = (double)(y) / (double)( TileLoader::levelToColumn( level ) ); double testx1 = origx1 * (double)( TileLoader::levelToRow( i ) ) ; double testy1 = origy1 * (double)( TileLoader::levelToColumn( i ) ); QString relfilename = QString("%1/%2/%3/%3_%4.jpg") .arg(theme).arg(i) .arg( (int)(testy1), tileDigits, 10, QChar('0') ) .arg( (int)(testx1), tileDigits, 10, QChar('0') ); absfilename = MarbleDirs::path( relfilename ); if ( QFile::exists( absfilename ) ) { // qDebug() << "The image filename does exist: " << absfilename ; QImage temptile( absfilename ); if ( !temptile.isNull() ) { // qDebug() << "Image has been successfully loaded."; if ( level != i ) { // qDebug() << "About to start cropping an existing image."; QSize tilesize = temptile.size(); double origx2 = (double)(x + 1) / (double)( TileLoader::levelToRow( level ) ); double origy2 = (double)(y + 1) / (double)( TileLoader::levelToColumn( level ) ); double testx2 = origx2 * (double)( TileLoader::levelToRow( i ) ); double testy2 = origy2 * (double)( TileLoader::levelToColumn( i ) ); QPoint topleft( (int)( ( testx1 - (int)(testx1) ) * temptile.width() ), (int)( ( testy1 - (int)(testy1) ) * temptile.height() ) ); QPoint bottomright( (int)( ( testx2 - (int)(testx1) ) * temptile.width() ) - 1, (int)( ( testy2 - (int)(testy1) ) * temptile.height() ) - 1 ); // This should not create any memory leaks as // 'copy' and 'scaled' return a value (on the // stack) which gets deep copied always into the // same place for m_rawtile on the heap: temptile = temptile.copy( QRect( topleft, bottomright ) ); temptile = temptile.scaled( tilesize ); // TODO: use correct size // qDebug() << "Finished scaling up the Temporary Tile."; } m_rawtile = temptile; break; } // !tempfile.isNull() // else { // qDebug() << "Image load failed for: " + // absfilename.toLocal8Bit(); // } } else { // qDebug() << "emit downloadTile(" << relfilename << ");"; emit downloadTile( relfilename, QString::number( m_id ) ); } } if ( m_rawtile.isNull() ) { qDebug() << "An essential tile is missing. Please rerun the application."; exit(-1); } m_worktile = m_rawtile; m_depth = m_worktile.depth(); // FIXME: This should get accessible from MarbleWidget, so we can pass over // a testing command line option bool tileIdVisible = false; if( tileIdVisible ) { showTileId( m_worktile, theme, level, x, y ); } if(sun_shading && m_depth == 32) { // TODO add support for 8-bit maps? // add sun shading m_sun.updatePosition(); double global_width = m_worktile.width() * TileLoader::levelToColumn(level); double global_height = m_worktile.height() * TileLoader::levelToRow(level); double lon_scale = 2*M_PI / global_width; double lat_scale = -M_PI / global_height; for(int cur_y = 0; cur_y < m_worktile.height(); cur_y++) { double lat = lat_scale * (y * m_worktile.height() + cur_y) - 0.5*M_PI; QRgb* scanline = (QRgb*)m_worktile.scanLine(cur_y); for(int cur_x = 0; cur_x < m_worktile.width(); cur_x++) { double lon = lon_scale * (x * m_worktile.width() + cur_x); m_sun.shadePixel(*scanline, m_sun.shading(lat, lon)); scanline++; } } } switch ( m_depth ) { case 32: if ( jumpTable32 ) delete [] jumpTable32; jumpTable32 = jumpTableFromQImage32( m_worktile ); break; case 8: if ( jumpTable8 ) delete [] jumpTable8; jumpTable8 = jumpTableFromQImage8( m_worktile ); break; default: qDebug() << QString("Color m_depth %1 of tile %2 could not be retrieved. Exiting.").arg(m_depth).arg(absfilename); exit( -1 ); } if ( requestTileUpdate ) { // qDebug() << "TileUpdate available"; emit tileUpdateDone(); } } void TextureTile::reloadTile( int x, int y, int level, const QString& theme, bool sun_shading ) { // qDebug() << "slotLoadTile variables: |" << theme << "|" // << level << "|" << x << "|" << y; loadTile( x, y, level, theme, true, sun_shading ); } void TextureTile::showTileId( QImage& worktile, QString theme, int level, int x, int y ) { QString filename = QString("%1_%2.jpg") .arg( x, tileDigits, 10, QChar('0') ) .arg( y, tileDigits, 10, QChar('0') ); QPainter painter(&m_worktile); QColor foreground; QColor background; if ( ( (double)(x)/2 == x/2 && (double)(y)/2 == y/2 ) || ( (double)(x)/2 != x/2 && (double)(y)/2 != y/2 ) ) { foreground.setNamedColor("#FFFFFF"); background.setNamedColor("#000000"); } else { foreground.setNamedColor("#000000"); background.setNamedColor("#FFFFFF"); } int strokeWidth = 10; QPen testPen( foreground ); testPen.setWidth( strokeWidth ); testPen.setJoinStyle(Qt::MiterJoin); painter.setPen( testPen ); painter.drawRect( strokeWidth / 2, strokeWidth / 2, worktile.width() - strokeWidth, worktile.height() - strokeWidth ); QFont testFont("Sans", 30, QFont::Bold); QFontMetrics testFm(testFont); painter.setFont(testFont); QPen outlinepen( foreground ); outlinepen.setWidthF( 6 ); painter.setPen( outlinepen ); painter.setBrush( background ); QPainterPath outlinepath; QPointF baseline1( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.25) ); outlinepath.addText( baseline1, testFont, QString( "level: %1" ).arg(level) ); QPointF baseline2( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.50) ); outlinepath.addText( baseline2, testFont, filename ); QPointF baseline3( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.75) ); outlinepath.addText( baseline3, testFont, theme ); painter.drawPath( outlinepath ); painter.setPen( Qt::NoPen ); painter.drawPath( outlinepath ); } #include "TextureTile.moc" <commit_msg>- optimization patch by David Roberts. <commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org>" // Copyright 2007 Inge Wallin <ingwa@kde.org>" // #include "TextureTile.h" #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtGui/QFont> #include <QtGui/QPainter> #include <QtGui/QPen> #include <cmath> #include "MarbleDirs.h" #include "TileLoader.h" static uint **jumpTableFromQImage32( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine() / 4; uint *data = (QRgb*)(img.scanLine(0)); uint **jumpTable = new uint*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } static uchar **jumpTableFromQImage8( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine(); uchar *data = img.bits(); uchar **jumpTable = new uchar*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } TextureTile::TextureTile( int id ) : QObject(), jumpTable8(0), jumpTable32(0), m_id(id), m_rawtile( QImage() ), m_depth(0), m_used(false)/*, m_sun_shading(false)*/ { } TextureTile::~TextureTile() { switch ( m_depth ) { case 32: delete [] jumpTable32; break; case 8: delete [] jumpTable8; break; default: qDebug("Color m_depth of a tile could not be retrieved. Exiting."); exit(-1); } // qDebug() << "Tile deleted: " << m_id; // delete m_rawtile; } void TextureTile::loadTile( int x, int y, int level, const QString& theme, bool requestTileUpdate, bool sun_shading ) { // qDebug() << "Entered loadTile( int, int, int) of Tile" << m_id; m_used = true; // Needed to avoid frequent deletion of tiles QString absfilename; // qDebug() << "Requested tile level" << level; // If the tile level offers the requested tile then load it. // Otherwise cycle from the requested tilelevel down to one where // the requested area is covered. Then scale the area to create a // replacement for the tile that has been requested. for ( int i = level; i > -1; --i ) { double origx1 = (double)(x) / (double)( TileLoader::levelToRow( level ) ); double origy1 = (double)(y) / (double)( TileLoader::levelToColumn( level ) ); double testx1 = origx1 * (double)( TileLoader::levelToRow( i ) ) ; double testy1 = origy1 * (double)( TileLoader::levelToColumn( i ) ); QString relfilename = QString("%1/%2/%3/%3_%4.jpg") .arg(theme).arg(i) .arg( (int)(testy1), tileDigits, 10, QChar('0') ) .arg( (int)(testx1), tileDigits, 10, QChar('0') ); absfilename = MarbleDirs::path( relfilename ); if ( QFile::exists( absfilename ) ) { // qDebug() << "The image filename does exist: " << absfilename ; QImage temptile( absfilename ); if ( !temptile.isNull() ) { // qDebug() << "Image has been successfully loaded."; if ( level != i ) { // qDebug() << "About to start cropping an existing image."; QSize tilesize = temptile.size(); double origx2 = (double)(x + 1) / (double)( TileLoader::levelToRow( level ) ); double origy2 = (double)(y + 1) / (double)( TileLoader::levelToColumn( level ) ); double testx2 = origx2 * (double)( TileLoader::levelToRow( i ) ); double testy2 = origy2 * (double)( TileLoader::levelToColumn( i ) ); QPoint topleft( (int)( ( testx1 - (int)(testx1) ) * temptile.width() ), (int)( ( testy1 - (int)(testy1) ) * temptile.height() ) ); QPoint bottomright( (int)( ( testx2 - (int)(testx1) ) * temptile.width() ) - 1, (int)( ( testy2 - (int)(testy1) ) * temptile.height() ) - 1 ); // This should not create any memory leaks as // 'copy' and 'scaled' return a value (on the // stack) which gets deep copied always into the // same place for m_rawtile on the heap: temptile = temptile.copy( QRect( topleft, bottomright ) ); temptile = temptile.scaled( tilesize ); // TODO: use correct size // qDebug() << "Finished scaling up the Temporary Tile."; } m_rawtile = temptile; break; } // !tempfile.isNull() // else { // qDebug() << "Image load failed for: " + // absfilename.toLocal8Bit(); // } } else { // qDebug() << "emit downloadTile(" << relfilename << ");"; emit downloadTile( relfilename, QString::number( m_id ) ); } } if ( m_rawtile.isNull() ) { qDebug() << "An essential tile is missing. Please rerun the application."; exit(-1); } m_worktile = m_rawtile; m_depth = m_worktile.depth(); // FIXME: This should get accessible from MarbleWidget, so we can pass over // a testing command line option bool tileIdVisible = false; if( tileIdVisible ) { showTileId( m_worktile, theme, level, x, y ); } if(sun_shading && m_depth == 32) { // TODO add support for 8-bit maps? // add sun shading m_sun.updatePosition(); const double global_width = m_worktile.width() * TileLoader::levelToColumn(level); const double global_height = m_worktile.height() * TileLoader::levelToRow(level); const double lon_scale = 2*M_PI / global_width; const double lat_scale = -M_PI / global_height; const int tileHeight = m_worktile.height(); const int tileWidth = m_worktile.width(); for(int cur_y = 0; cur_y < tileHeight; cur_y++) { double lat = lat_scale * (y * tileHeight + cur_y) - 0.5*M_PI; QRgb* scanline = (QRgb*)m_worktile.scanLine(cur_y); for(int cur_x = 0; cur_x < tileWidth; cur_x++) { double lon = lon_scale * (x * tileWidth + cur_x); m_sun.shadePixel(*scanline, m_sun.shading(lat, lon)); scanline++; } } } switch ( m_depth ) { case 32: if ( jumpTable32 ) delete [] jumpTable32; jumpTable32 = jumpTableFromQImage32( m_worktile ); break; case 8: if ( jumpTable8 ) delete [] jumpTable8; jumpTable8 = jumpTableFromQImage8( m_worktile ); break; default: qDebug() << QString("Color m_depth %1 of tile %2 could not be retrieved. Exiting.").arg(m_depth).arg(absfilename); exit( -1 ); } if ( requestTileUpdate ) { // qDebug() << "TileUpdate available"; emit tileUpdateDone(); } } void TextureTile::reloadTile( int x, int y, int level, const QString& theme, bool sun_shading ) { // qDebug() << "slotLoadTile variables: |" << theme << "|" // << level << "|" << x << "|" << y; loadTile( x, y, level, theme, true, sun_shading ); } void TextureTile::showTileId( QImage& worktile, QString theme, int level, int x, int y ) { QString filename = QString("%1_%2.jpg") .arg( x, tileDigits, 10, QChar('0') ) .arg( y, tileDigits, 10, QChar('0') ); QPainter painter(&m_worktile); QColor foreground; QColor background; if ( ( (double)(x)/2 == x/2 && (double)(y)/2 == y/2 ) || ( (double)(x)/2 != x/2 && (double)(y)/2 != y/2 ) ) { foreground.setNamedColor("#FFFFFF"); background.setNamedColor("#000000"); } else { foreground.setNamedColor("#000000"); background.setNamedColor("#FFFFFF"); } int strokeWidth = 10; QPen testPen( foreground ); testPen.setWidth( strokeWidth ); testPen.setJoinStyle(Qt::MiterJoin); painter.setPen( testPen ); painter.drawRect( strokeWidth / 2, strokeWidth / 2, worktile.width() - strokeWidth, worktile.height() - strokeWidth ); QFont testFont("Sans", 30, QFont::Bold); QFontMetrics testFm(testFont); painter.setFont(testFont); QPen outlinepen( foreground ); outlinepen.setWidthF( 6 ); painter.setPen( outlinepen ); painter.setBrush( background ); QPainterPath outlinepath; QPointF baseline1( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.25) ); outlinepath.addText( baseline1, testFont, QString( "level: %1" ).arg(level) ); QPointF baseline2( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.50) ); outlinepath.addText( baseline2, testFont, filename ); QPointF baseline3( ( worktile.width() - testFm.boundingRect(filename).width() ) / 2, (worktile.height() * 0.75) ); outlinepath.addText( baseline3, testFont, theme ); painter.drawPath( outlinepath ); painter.setPen( Qt::NoPen ); painter.drawPath( outlinepath ); } #include "TextureTile.moc" <|endoftext|>
<commit_before>#ifndef URMEM_H_ #define URMEM_H_ #ifdef _WIN32 #include <windows.h> #else #include <dlfcn.h> #include <sys/stat.h> #include <sys/mman.h> #include <unistd.h> #endif #include <vector> #include <iterator> #include <algorithm> #include <memory> #include <mutex> class urmem { public: using address_t = unsigned long; using byte_t = unsigned char; using bytearray_t = std::vector<byte_t>; enum class calling_convention { cdeclcall, stdcall, thiscall }; template<calling_convention CConv, typename Ret = void, typename ... Args> static Ret call_function(address_t address, Args ... args) { #ifdef _WIN32 return invoker<CConv>::call<Ret, Args...>(address, args...); #else return (reinterpret_cast<Ret(*)(Args...)>(address))(args...); #endif } template<typename T> static address_t get_func_addr(T func) { union { T func; address_t addr; } u{func}; return u.addr; }; static void unprotect_memory(address_t addr, size_t length) { #ifdef _WIN32 unsigned long original_protect; VirtualProtect(reinterpret_cast<void *>(addr), length, PAGE_EXECUTE_READWRITE, &original_protect); #else auto pagesize = sysconf(_SC_PAGE_SIZE); addr = addr & ~(pagesize - 1); mprotect(reinterpret_cast<void *>(addr), length, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } template<typename T> class bit_manager { public: bit_manager(void) = delete; bit_manager(T &src) :_data(src) {} class bit { public: bit(void) = delete; bit(T &src, size_t index) : _data(src), _mask(1 << index), _index(index) {} bit &operator=(bool value) { if (value) { _data |= _mask; } else { _data &= ~_mask; } return *this; } operator bool() const { return (_data & _mask) != 0; } private: T &_data; const T _mask; const size_t _index; }; bit operator [](size_t index) const { return bit(_data, index); }; private: T &_data; }; class pointer { public: pointer(void) = delete; template<typename T> pointer(T *address) : pointer{reinterpret_cast<address_t>(address)} {} pointer(address_t address) : _pointer(address) {} template<typename T> T &field(size_t offset) { return *reinterpret_cast<T *>(_pointer + offset); } pointer ptr_field(size_t offset) { return pointer(field<address_t>(offset)); } template<typename T> operator T *() const { return reinterpret_cast<T *>(_pointer); } private: const address_t _pointer; }; class unprotect_scope { public: unprotect_scope(void) = delete; unprotect_scope(address_t addr, size_t length) :_addr(addr), _lenght(length) { #ifdef _WIN32 VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, PAGE_EXECUTE_READWRITE, &_original_protect); #else auto pagesize = sysconf(_SC_PAGE_SIZE); _addr = _addr & ~(pagesize - 1); mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } ~unprotect_scope(void) { #ifdef _WIN32 VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, _original_protect, nullptr); #else mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_EXEC); #endif } private: #ifdef _WIN32 unsigned long _original_protect; #endif address_t _addr; const size_t _lenght; }; class sig_scanner { public: bool init(void *addr_in_module) { return init(reinterpret_cast<address_t>(addr_in_module)); } bool init(address_t addr_in_module) { #ifdef _WIN32 MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast<void *>(addr_in_module), &info, sizeof(info))) { return false; } auto dos = reinterpret_cast<IMAGE_DOS_HEADER *>(info.AllocationBase); auto pe = reinterpret_cast<IMAGE_NT_HEADERS *>(reinterpret_cast<address_t>(dos) + dos->e_lfanew); if (pe->Signature != IMAGE_NT_SIGNATURE) { return false; } _base = reinterpret_cast<address_t>(info.AllocationBase); _size = pe->OptionalHeader.SizeOfImage; #else Dl_info info{}; struct stat buf {}; if (!dladdr(reinterpret_cast<void *>(addr_in_module), &info)) { return false; } if (stat(info.dli_fname, &buf) != 0) { return false; } _base = reinterpret_cast<address_t>(info.dli_fbase); _size = buf.st_size; #endif return true; } bool find(const char *pattern, const char *mask, address_t &addr) const { auto current_byte = reinterpret_cast<byte_t *>(_base); auto last_byte = current_byte + _size; size_t i{}; while (current_byte < last_byte) { for (i = 0; mask[i]; ++i) { if (&current_byte[i] >= last_byte || ((mask[i] != '?') && (static_cast<byte_t>(pattern[i]) != current_byte[i]))) { break; } } if (!mask[i]) { addr = reinterpret_cast<address_t>(current_byte); return true; } ++current_byte; } return false; } private: address_t _base{}; size_t _size{}; }; class patch { public: patch(void) = delete; patch(void *addr, const bytearray_t &new_data) : patch{reinterpret_cast<address_t>(addr), new_data} {} patch(address_t addr, const bytearray_t &new_data) : _patch_addr(addr), _new_data(new_data), _enabled(false) { unprotect_memory(_patch_addr, _new_data.size()); enable(); } ~patch(void) { disable(); } void enable(void) { if (_enabled) { return; } _original_data.clear(); std::copy_n( reinterpret_cast<bytearray_t::value_type*>(_patch_addr), _new_data.size(), std::back_inserter<bytearray_t>(_original_data) ); std::copy_n( _new_data.data(), _new_data.size(), reinterpret_cast<bytearray_t::value_type*>(_patch_addr) ); _enabled = true; } void disable(void) { if (!_enabled) { return; } std::copy_n( _original_data.data(), _original_data.size(), reinterpret_cast<bytearray_t::value_type*>(_patch_addr) ); _enabled = false; } bool is_enabled(void) const { return _enabled; } private: address_t _patch_addr; bytearray_t _original_data; bytearray_t _new_data; bool _enabled; }; class hook { public: enum class type { jmp, call }; class raii { public: raii(void) = delete; raii(hook &h) : _hook(h) { _hook.disable(); } ~raii(void) { _hook.enable(); } private: hook &_hook; }; hook(void) = delete; hook(void *inject_addr, void *handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) : hook{reinterpret_cast<address_t>(inject_addr), reinterpret_cast<address_t>(handle_addr), h_type, length} {}; hook(address_t inject_addr, address_t handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) { bytearray_t new_bytes(length, 0x90); switch (h_type) { case type::jmp: { new_bytes[0] = 0xE9; _original_addr = inject_addr; break; } case type::call: { new_bytes[0] = 0xE8; _original_addr = pointer(inject_addr).field<address_t>(1) + (inject_addr + 5); break; } } *reinterpret_cast<address_t *>(new_bytes.data() + 1) = handle_addr - (inject_addr + 5); _patch = std::make_shared<patch>(inject_addr, new_bytes); } void enable(void) { _patch->enable(); } void disable(void) { _patch->disable(); } bool is_enabled(void) const { return _patch->is_enabled(); } address_t get_original_addr(void) const { return _original_addr; } private: address_t _original_addr{}; std::shared_ptr<patch> _patch; }; template<size_t, calling_convention, typename Sig> class smart_hook; template<size_t Id, calling_convention CConv, typename Ret, typename ... Args> class smart_hook<Id, CConv, Ret(Args...)> { public: using func = std::function<Ret(Args...)>; smart_hook(void *inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) : smart_hook{reinterpret_cast<address_t>(inject_addr), h_type, length} {}; smart_hook(address_t inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) { get_data() = this; _hook = std::make_shared<hook>(inject_addr, reinterpret_cast<address_t>(_interlayer.func), h_type, length); } void attach(const func &f) { _cb = f; } void detach(void) { _cb = nullptr; } Ret call(Args ... args) { return call_function<CConv, Ret>(_hook->get_original_addr(), args...); } private: static smart_hook<Id, CConv, Ret(Args...)> *&get_data(void) { static smart_hook<Id, CConv, Ret(Args...)> *d{}; return d; } #ifdef _WIN32 template<calling_convention> struct interlayer; template<> struct interlayer<calling_convention::cdeclcall> { static Ret __cdecl func(Args ... args) { return get_data()->call_cb(args...); } }; template<> struct interlayer<calling_convention::stdcall> { static Ret __stdcall func(Args ... args) { return get_data()->call_cb(args...); } }; template<> struct interlayer<calling_convention::thiscall> { static Ret __thiscall func(Args ... args) { return get_data()->call_cb(args...); } }; #else struct interlayer { static Ret func(Args ... args) { return get_data()->call_cb(args...); } }; #endif inline Ret call_cb(Args ... args) { std::lock_guard<std::mutex> guard(_mutex); hook::raii scope(*_hook); return _cb ? _cb(args...) : call(args...); } std::shared_ptr<hook> _hook; std::mutex _mutex; #ifdef _WIN32 interlayer<CConv> _interlayer; #else interlayer _interlayer; #endif func _cb; }; private: #ifdef _WIN32 template<calling_convention> struct invoker; template<> struct invoker<calling_convention::cdeclcall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__cdecl *)(Args...)>(address))(args...); } }; template<> struct invoker<calling_convention::stdcall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__stdcall *)(Args...)>(address))(args...); } }; template<> struct invoker<calling_convention::thiscall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__thiscall *)(Args...)>(address))(args...); } }; #endif }; #endif // URMEM_H_ <commit_msg>Discard reallocation<commit_after>#ifndef URMEM_H_ #define URMEM_H_ #ifdef _WIN32 #include <windows.h> #else #include <dlfcn.h> #include <sys/stat.h> #include <sys/mman.h> #include <unistd.h> #endif #include <vector> #include <iterator> #include <algorithm> #include <memory> #include <mutex> class urmem { public: using address_t = unsigned long; using byte_t = unsigned char; using bytearray_t = std::vector<byte_t>; enum class calling_convention { cdeclcall, stdcall, thiscall }; template<calling_convention CConv, typename Ret = void, typename ... Args> static Ret call_function(address_t address, Args ... args) { #ifdef _WIN32 return invoker<CConv>::call<Ret, Args...>(address, args...); #else return (reinterpret_cast<Ret(*)(Args...)>(address))(args...); #endif } template<typename T> static address_t get_func_addr(T func) { union { T func; address_t addr; } u{func}; return u.addr; }; static void unprotect_memory(address_t addr, size_t length) { #ifdef _WIN32 unsigned long original_protect; VirtualProtect(reinterpret_cast<void *>(addr), length, PAGE_EXECUTE_READWRITE, &original_protect); #else auto pagesize = sysconf(_SC_PAGE_SIZE); addr = addr & ~(pagesize - 1); mprotect(reinterpret_cast<void *>(addr), length, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } template<typename T> class bit_manager { public: bit_manager(void) = delete; bit_manager(T &src) :_data(src) {} class bit { public: bit(void) = delete; bit(T &src, size_t index) : _data(src), _mask(1 << index), _index(index) {} bit &operator=(bool value) { if (value) { _data |= _mask; } else { _data &= ~_mask; } return *this; } operator bool() const { return (_data & _mask) != 0; } private: T &_data; const T _mask; const size_t _index; }; bit operator [](size_t index) const { return bit(_data, index); }; private: T &_data; }; class pointer { public: pointer(void) = delete; template<typename T> pointer(T *address) : pointer{reinterpret_cast<address_t>(address)} {} pointer(address_t address) : _pointer(address) {} template<typename T> T &field(size_t offset) { return *reinterpret_cast<T *>(_pointer + offset); } pointer ptr_field(size_t offset) { return pointer(field<address_t>(offset)); } template<typename T> operator T *() const { return reinterpret_cast<T *>(_pointer); } private: const address_t _pointer; }; class unprotect_scope { public: unprotect_scope(void) = delete; unprotect_scope(address_t addr, size_t length) :_addr(addr), _lenght(length) { #ifdef _WIN32 VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, PAGE_EXECUTE_READWRITE, &_original_protect); #else auto pagesize = sysconf(_SC_PAGE_SIZE); _addr = _addr & ~(pagesize - 1); mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } ~unprotect_scope(void) { #ifdef _WIN32 VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, _original_protect, nullptr); #else mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_EXEC); #endif } private: #ifdef _WIN32 unsigned long _original_protect; #endif address_t _addr; const size_t _lenght; }; class sig_scanner { public: bool init(void *addr_in_module) { return init(reinterpret_cast<address_t>(addr_in_module)); } bool init(address_t addr_in_module) { #ifdef _WIN32 MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast<void *>(addr_in_module), &info, sizeof(info))) { return false; } auto dos = reinterpret_cast<IMAGE_DOS_HEADER *>(info.AllocationBase); auto pe = reinterpret_cast<IMAGE_NT_HEADERS *>(reinterpret_cast<address_t>(dos) + dos->e_lfanew); if (pe->Signature != IMAGE_NT_SIGNATURE) { return false; } _base = reinterpret_cast<address_t>(info.AllocationBase); _size = pe->OptionalHeader.SizeOfImage; #else Dl_info info{}; struct stat buf {}; if (!dladdr(reinterpret_cast<void *>(addr_in_module), &info)) { return false; } if (stat(info.dli_fname, &buf) != 0) { return false; } _base = reinterpret_cast<address_t>(info.dli_fbase); _size = buf.st_size; #endif return true; } bool find(const char *pattern, const char *mask, address_t &addr) const { auto current_byte = reinterpret_cast<byte_t *>(_base); auto last_byte = current_byte + _size; size_t i{}; while (current_byte < last_byte) { for (i = 0; mask[i]; ++i) { if (&current_byte[i] >= last_byte || ((mask[i] != '?') && (static_cast<byte_t>(pattern[i]) != current_byte[i]))) { break; } } if (!mask[i]) { addr = reinterpret_cast<address_t>(current_byte); return true; } ++current_byte; } return false; } private: address_t _base{}; size_t _size{}; }; class patch { public: patch(void) = delete; patch(void *addr, const bytearray_t &new_data) : patch{reinterpret_cast<address_t>(addr), new_data} {} patch(address_t addr, const bytearray_t &new_data) : _patch_addr(addr), _new_data(new_data), _original_data(new_data.size(), 0x90), _enabled(false) { unprotect_memory(_patch_addr, _new_data.size()); enable(); } ~patch(void) { disable(); } void enable(void) { if (_enabled) { return; } std::copy_n( reinterpret_cast<bytearray_t::value_type *>(_patch_addr), _new_data.size(), _original_data.data() ); std::copy_n( _new_data.data(), _new_data.size(), reinterpret_cast<bytearray_t::value_type*>(_patch_addr) ); _enabled = true; } void disable(void) { if (!_enabled) { return; } std::copy_n( _original_data.data(), _original_data.size(), reinterpret_cast<bytearray_t::value_type*>(_patch_addr) ); _enabled = false; } bool is_enabled(void) const { return _enabled; } private: address_t _patch_addr; bytearray_t _original_data; bytearray_t _new_data; bool _enabled; }; class hook { public: enum class type { jmp, call }; class raii { public: raii(void) = delete; raii(hook &h) : _hook(h) { _hook.disable(); } ~raii(void) { _hook.enable(); } private: hook &_hook; }; hook(void) = delete; hook(void *inject_addr, void *handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) : hook{reinterpret_cast<address_t>(inject_addr), reinterpret_cast<address_t>(handle_addr), h_type, length} {}; hook(address_t inject_addr, address_t handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) { bytearray_t new_bytes(length, 0x90); switch (h_type) { case type::jmp: { new_bytes[0] = 0xE9; _original_addr = inject_addr; break; } case type::call: { new_bytes[0] = 0xE8; _original_addr = pointer(inject_addr).field<address_t>(1) + (inject_addr + 5); break; } } *reinterpret_cast<address_t *>(new_bytes.data() + 1) = handle_addr - (inject_addr + 5); _patch = std::make_shared<patch>(inject_addr, new_bytes); } void enable(void) { _patch->enable(); } void disable(void) { _patch->disable(); } bool is_enabled(void) const { return _patch->is_enabled(); } address_t get_original_addr(void) const { return _original_addr; } private: address_t _original_addr{}; std::shared_ptr<patch> _patch; }; template<size_t, calling_convention, typename Sig> class smart_hook; template<size_t Id, calling_convention CConv, typename Ret, typename ... Args> class smart_hook<Id, CConv, Ret(Args...)> { public: using func = std::function<Ret(Args...)>; smart_hook(void *inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) : smart_hook{reinterpret_cast<address_t>(inject_addr), h_type, length} {}; smart_hook(address_t inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) { get_data() = this; _hook = std::make_shared<hook>(inject_addr, reinterpret_cast<address_t>(_interlayer.func), h_type, length); } void attach(const func &f) { _cb = f; } void detach(void) { _cb = nullptr; } Ret call(Args ... args) { return call_function<CConv, Ret>(_hook->get_original_addr(), args...); } private: static smart_hook<Id, CConv, Ret(Args...)> *&get_data(void) { static smart_hook<Id, CConv, Ret(Args...)> *d{}; return d; } #ifdef _WIN32 template<calling_convention> struct interlayer; template<> struct interlayer<calling_convention::cdeclcall> { static Ret __cdecl func(Args ... args) { return get_data()->call_cb(args...); } }; template<> struct interlayer<calling_convention::stdcall> { static Ret __stdcall func(Args ... args) { return get_data()->call_cb(args...); } }; template<> struct interlayer<calling_convention::thiscall> { static Ret __thiscall func(Args ... args) { return get_data()->call_cb(args...); } }; #else struct interlayer { static Ret func(Args ... args) { return get_data()->call_cb(args...); } }; #endif inline Ret call_cb(Args ... args) { std::lock_guard<std::mutex> guard(_mutex); hook::raii scope(*_hook); return _cb ? _cb(args...) : call(args...); } std::shared_ptr<hook> _hook; std::mutex _mutex; #ifdef _WIN32 interlayer<CConv> _interlayer; #else interlayer _interlayer; #endif func _cb; }; private: #ifdef _WIN32 template<calling_convention> struct invoker; template<> struct invoker<calling_convention::cdeclcall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__cdecl *)(Args...)>(address))(args...); } }; template<> struct invoker<calling_convention::stdcall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__stdcall *)(Args...)>(address))(args...); } }; template<> struct invoker<calling_convention::thiscall> { template<typename Ret, typename ... Args> static inline Ret call(address_t address, Args... args) { return (reinterpret_cast<Ret(__thiscall *)(Args...)>(address))(args...); } }; #endif }; #endif // URMEM_H_ <|endoftext|>
<commit_before>/* * Copyright 2009-2021 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/xtp/rpa.h" #include "votca/xtp/aomatrix.h" #include "votca/xtp/openmp_cuda.h" #include "votca/xtp/threecenter.h" #include "votca/xtp/vc2index.h" namespace votca { namespace xtp { void RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies, const Eigen::VectorXd& gwaenergies, Index qpmin) { Index rpatotal = _rpamax - _rpamin + 1; _energies = dftenergies.segment(_rpamin, rpatotal); Index gwsize = Index(gwaenergies.size()); _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies; ShiftUncorrectedEnergies(dftenergies, qpmin, gwsize); } // Shifts energies of levels that are not QP corrected but // used in the RPA: // between rpamin and qpmin: by maximum abs of explicit QP corrections // from qpmin to HOMO // between qpmax and rpamax: by maximum abs of explicit QP corrections // from LUMO to qpmax void RPA::ShiftUncorrectedEnergies(const Eigen::VectorXd& dftenergies, Index qpmin, Index gwsize) { Index lumo = _homo + 1; Index qpmax = qpmin + gwsize - 1; // get max abs QP corrections for occupied/virtual levels double max_correction_occ = getMaxCorrection(dftenergies, qpmin, _homo); double max_correction_virt = getMaxCorrection(dftenergies, lumo, qpmax); // shift energies _energies.head(qpmin).array() -= max_correction_occ; _energies.tail(_rpamax - qpmax).array()+= max_correction_virt; } double RPA::getMaxCorrection(const Eigen::VectorXd& dftenergies, Index min, Index max) { Index range = max - min +1; Eigen::VectorXd corrections = _energies.segment(min, range) - dftenergies.segment(min - _rpamin, range); return (corrections.cwiseAbs()).maxCoeff(); } template <bool imag> Eigen::MatrixXd RPA::calculate_epsilon(double frequency) const { const Index size = _Mmn.auxsize(); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const double freq2 = frequency * frequency; const double eta2 = _eta * _eta; OpenMP_CUDA transform; transform.createTemporaries(n_unocc, size); #pragma omp parallel for schedule(dynamic) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::VectorXd denom; if (imag) { denom = 4 * deltaE / (deltaE.square() + freq2); } else { Eigen::ArrayXd deltEf = deltaE - frequency; Eigen::ArrayXd sum = deltEf / (deltEf.square() + eta2); deltEf = deltaE + frequency; sum += deltEf / (deltEf.square() + eta2); denom = 2 * sum; } transform.A_TDA(Mmn_RPA, denom); } Eigen::MatrixXd result = transform.A_TDA_result(); result.diagonal().array() += 1.0; return result; } template Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const; template Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const; Eigen::MatrixXd RPA::calculate_epsilon_r(std::complex<double> frequency) const { const Index size = _Mmn.auxsize(); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; OpenMP_CUDA transform; transform.createTemporaries(n_unocc, size); #pragma omp parallel for schedule(dynamic) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::ArrayXd deltaEm = frequency.real() - deltaE; Eigen::ArrayXd deltaEp = frequency.real() + deltaE; double sigma_1 = std::pow(frequency.imag() + _eta, 2); double sigma_2 = std::pow(frequency.imag() - _eta, 2); Eigen::VectorXd chi = deltaEm * (deltaEm.cwiseAbs2() + sigma_1).cwiseInverse() - deltaEp * (deltaEp.cwiseAbs2() + sigma_2).cwiseInverse(); transform.A_TDA(Mmn_RPA, chi); } Eigen::MatrixXd result = -2 * transform.A_TDA_result(); result.diagonal().array() += 1.0; return result; } RPA::rpa_eigensolution RPA::Diagonalize_H2p() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; Eigen::VectorXd AmB = Calculate_H2p_AmB(); Eigen::MatrixXd ApB = Calculate_H2p_ApB(); RPA::rpa_eigensolution sol; sol.ERPA_correlation = -0.25 * (ApB.trace() + AmB.sum()); // C = AmB^1/2 * ApB * AmB^1/2 Eigen::MatrixXd& C = ApB; C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal()); C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal()); Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C); // Do not remove this line! It has to be there for MKL to not crash sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size()); sol.omega = es.eigenvalues().cwiseSqrt(); sol.ERPA_correlation += 0.5 * sol.omega.sum(); XTP_LOG(Log::info, _log) << TimeStamp() << " Lowest neutral excitation energy (eV): " << tools::conv::hrt2ev * sol.omega.minCoeff() << std::flush; // RPA correlation energy calculated from Eq.9 of J. Chem. Phys. 132, 234114 // (2010) XTP_LOG(Log::error, _log) << TimeStamp() << " RPA correlation energy (Hartree): " << sol.ERPA_correlation << std::flush; sol.XpY = Eigen::MatrixXd(rpasize, rpasize); Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt(); Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse(); for (int s = 0; s < rpasize; s++) { sol.XpY.col(s) = Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s)); } return sol; } Eigen::VectorXd RPA::Calculate_H2p_AmB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; vc2index vc = vc2index(0, 0, n_unocc); Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize); for (Index v = 0; v < n_occ; v++) { Index i = vc.I(v, 0); AmB.segment(i, n_unocc) = _energies.segment(n_occ, n_unocc).array() - _energies(v); } return AmB; } Eigen::MatrixXd RPA::Calculate_H2p_ApB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; const Index auxsize = _Mmn.auxsize(); vc2index vc = vc2index(0, 0, n_unocc); Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize); #pragma omp parallel for schedule(guided) for (Index v2 = 0; v2 < n_occ; v2++) { Index i2 = vc.I(v2, 0); const Eigen::MatrixXd Mmn_v2T = _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose(); for (Index v1 = v2; v1 < n_occ; v1++) { Index i1 = vc.I(v1, 0); // Multiply with factor 2 to sum over both (identical) spin states ApB.block(i1, i2, n_unocc, n_unocc) = 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T; } } ApB.diagonal() += Calculate_H2p_AmB(); return ApB; } Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C( const Eigen::MatrixXd& C) const { XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalizing two-particle Hamiltonian " << std::flush; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); // Uses lower triangle XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalization done " << std::flush; double minCoeff = es.eigenvalues().minCoeff(); if (minCoeff <= 0.0) { XTP_LOG(Log::error, _log) << TimeStamp() << " Detected non-positive eigenvalue: " << minCoeff << std::flush; throw std::runtime_error("Detected non-positive eigenvalue."); } return es; } } // namespace xtp } // namespace votca <commit_msg>Update src/libxtp/gwbse/rpa.cc<commit_after>/* * Copyright 2009-2021 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/xtp/rpa.h" #include "votca/xtp/aomatrix.h" #include "votca/xtp/openmp_cuda.h" #include "votca/xtp/threecenter.h" #include "votca/xtp/vc2index.h" namespace votca { namespace xtp { void RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies, const Eigen::VectorXd& gwaenergies, Index qpmin) { Index rpatotal = _rpamax - _rpamin + 1; _energies = dftenergies.segment(_rpamin, rpatotal); Index gwsize = Index(gwaenergies.size()); _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies; ShiftUncorrectedEnergies(dftenergies, qpmin, gwsize); } // Shifts energies of levels that are not QP corrected but // used in the RPA: // between rpamin and qpmin: by maximum abs of explicit QP corrections // from qpmin to HOMO // between qpmax and rpamax: by maximum abs of explicit QP corrections // from LUMO to qpmax void RPA::ShiftUncorrectedEnergies(const Eigen::VectorXd& dftenergies, Index qpmin, Index gwsize) { Index lumo = _homo + 1; Index qpmax = qpmin + gwsize - 1; // get max abs QP corrections for occupied/virtual levels double max_correction_occ = getMaxCorrection(dftenergies, qpmin, _homo); double max_correction_virt = getMaxCorrection(dftenergies, lumo, qpmax); // shift energies _energies.head(qpmin).array() -= max_correction_occ; _energies.tail(_rpamax - qpmax).array()+= max_correction_virt; } double RPA::getMaxCorrection(const Eigen::VectorXd& dftenergies, Index min, Index max) const{ Index range = max - min +1; Eigen::VectorXd corrections = _energies.segment(min, range) - dftenergies.segment(min - _rpamin, range); return (corrections.cwiseAbs()).maxCoeff(); } template <bool imag> Eigen::MatrixXd RPA::calculate_epsilon(double frequency) const { const Index size = _Mmn.auxsize(); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const double freq2 = frequency * frequency; const double eta2 = _eta * _eta; OpenMP_CUDA transform; transform.createTemporaries(n_unocc, size); #pragma omp parallel for schedule(dynamic) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::VectorXd denom; if (imag) { denom = 4 * deltaE / (deltaE.square() + freq2); } else { Eigen::ArrayXd deltEf = deltaE - frequency; Eigen::ArrayXd sum = deltEf / (deltEf.square() + eta2); deltEf = deltaE + frequency; sum += deltEf / (deltEf.square() + eta2); denom = 2 * sum; } transform.A_TDA(Mmn_RPA, denom); } Eigen::MatrixXd result = transform.A_TDA_result(); result.diagonal().array() += 1.0; return result; } template Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const; template Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const; Eigen::MatrixXd RPA::calculate_epsilon_r(std::complex<double> frequency) const { const Index size = _Mmn.auxsize(); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; OpenMP_CUDA transform; transform.createTemporaries(n_unocc, size); #pragma omp parallel for schedule(dynamic) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::ArrayXd deltaEm = frequency.real() - deltaE; Eigen::ArrayXd deltaEp = frequency.real() + deltaE; double sigma_1 = std::pow(frequency.imag() + _eta, 2); double sigma_2 = std::pow(frequency.imag() - _eta, 2); Eigen::VectorXd chi = deltaEm * (deltaEm.cwiseAbs2() + sigma_1).cwiseInverse() - deltaEp * (deltaEp.cwiseAbs2() + sigma_2).cwiseInverse(); transform.A_TDA(Mmn_RPA, chi); } Eigen::MatrixXd result = -2 * transform.A_TDA_result(); result.diagonal().array() += 1.0; return result; } RPA::rpa_eigensolution RPA::Diagonalize_H2p() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; Eigen::VectorXd AmB = Calculate_H2p_AmB(); Eigen::MatrixXd ApB = Calculate_H2p_ApB(); RPA::rpa_eigensolution sol; sol.ERPA_correlation = -0.25 * (ApB.trace() + AmB.sum()); // C = AmB^1/2 * ApB * AmB^1/2 Eigen::MatrixXd& C = ApB; C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal()); C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal()); Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C); // Do not remove this line! It has to be there for MKL to not crash sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size()); sol.omega = es.eigenvalues().cwiseSqrt(); sol.ERPA_correlation += 0.5 * sol.omega.sum(); XTP_LOG(Log::info, _log) << TimeStamp() << " Lowest neutral excitation energy (eV): " << tools::conv::hrt2ev * sol.omega.minCoeff() << std::flush; // RPA correlation energy calculated from Eq.9 of J. Chem. Phys. 132, 234114 // (2010) XTP_LOG(Log::error, _log) << TimeStamp() << " RPA correlation energy (Hartree): " << sol.ERPA_correlation << std::flush; sol.XpY = Eigen::MatrixXd(rpasize, rpasize); Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt(); Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse(); for (int s = 0; s < rpasize; s++) { sol.XpY.col(s) = Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s)); } return sol; } Eigen::VectorXd RPA::Calculate_H2p_AmB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; vc2index vc = vc2index(0, 0, n_unocc); Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize); for (Index v = 0; v < n_occ; v++) { Index i = vc.I(v, 0); AmB.segment(i, n_unocc) = _energies.segment(n_occ, n_unocc).array() - _energies(v); } return AmB; } Eigen::MatrixXd RPA::Calculate_H2p_ApB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; const Index auxsize = _Mmn.auxsize(); vc2index vc = vc2index(0, 0, n_unocc); Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize); #pragma omp parallel for schedule(guided) for (Index v2 = 0; v2 < n_occ; v2++) { Index i2 = vc.I(v2, 0); const Eigen::MatrixXd Mmn_v2T = _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose(); for (Index v1 = v2; v1 < n_occ; v1++) { Index i1 = vc.I(v1, 0); // Multiply with factor 2 to sum over both (identical) spin states ApB.block(i1, i2, n_unocc, n_unocc) = 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T; } } ApB.diagonal() += Calculate_H2p_AmB(); return ApB; } Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C( const Eigen::MatrixXd& C) const { XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalizing two-particle Hamiltonian " << std::flush; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); // Uses lower triangle XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalization done " << std::flush; double minCoeff = es.eigenvalues().minCoeff(); if (minCoeff <= 0.0) { XTP_LOG(Log::error, _log) << TimeStamp() << " Detected non-positive eigenvalue: " << minCoeff << std::flush; throw std::runtime_error("Detected non-positive eigenvalue."); } return es; } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/stat.h> #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #include "lz4mt_io_cstdio.h" #include "lz4mt.h" namespace { FILE* fopen_(const char* filename, const char* mode) { #if defined(_MSC_VER) FILE* fp = nullptr; ::fopen_s(&fp, filename, mode); return fp; #else return ::fopen(filename, mode); #endif } void fclose_(FILE* fp) { if(fp) { if(fp != stdin && fp != stdout) { ::fclose(fp); } } } FILE* getStdin() { #ifdef _WIN32 (void) _setmode(_fileno(stdin), _O_BINARY); #endif return stdin; } FILE* getStdout() { #ifdef _WIN32 (void) _setmode(_fileno(stdout), _O_BINARY); #endif return stdout; } } namespace Lz4Mt { namespace Cstdio { bool fileExist(const std::string& filename) { if("stdin" == filename || "stdout" == filename) { return false; } else { FILE* fp = fopen_(filename.c_str(), "rb"); fclose_(fp); return nullptr != fp; } } FILE* readCtx(const Lz4MtContext* ctx) { return reinterpret_cast<FILE*>(ctx->readCtx); } FILE* writeCtx(const Lz4MtContext* ctx) { return reinterpret_cast<FILE*>(ctx->writeCtx); } bool openIstream(Lz4MtContext* ctx, const std::string& filename) { FILE* fp = nullptr; if("stdin" == filename) { fp = getStdin(); } else { fp = fopen_(filename.c_str(), "rb"); } ctx->readCtx = reinterpret_cast<void*>(fp); return nullptr != fp; } bool openOstream(Lz4MtContext* ctx, const std::string& filename) { FILE* fp = nullptr; if("stdout" == filename) { fp = getStdout(); } else { fp = fopen_(filename.c_str(), "wb"); } ctx->writeCtx = reinterpret_cast<void*>(fp); return nullptr != fp; } void closeIstream(Lz4MtContext* ctx) { fclose_(readCtx(ctx)); ctx->readCtx = nullptr; } void closeOstream(Lz4MtContext* ctx) { fclose_(writeCtx(ctx)); ctx->writeCtx = nullptr; } int read(Lz4MtContext* ctx, void* dst, int dstSize) { if(auto* fp = readCtx(ctx)) { return static_cast<int>(::fread(dst, 1, dstSize, fp)); } else { return 0; } } int readSkippable(const Lz4MtContext* ctx , uint32_t //magicNumber , size_t size) { if(auto* fp = readCtx(ctx)) { return ::fseek(fp, static_cast<long>(size), SEEK_CUR); } else { return -1; } } int readSeek(const Lz4MtContext* ctx, int offset) { if(auto* fp = readCtx(ctx)) { return ::fseek(fp, offset, SEEK_CUR); } else { return -1; } } int readEof(const Lz4MtContext* ctx) { if(auto* fp = readCtx(ctx)) { return ::feof(fp); } else { return 1; } } int write(const Lz4MtContext* ctx, const void* source, int sourceSize) { if(auto* fp = writeCtx(ctx)) { return static_cast<int>(::fwrite(source, 1, sourceSize, fp)); } else { return 0; } } uint64_t getFilesize(const std::string& fileanme) { int r = 0; #if defined(_MSC_VER) struct _stat64 s = { 0 }; r = _stat64(fileanme.c_str(), &s); auto S_ISREG = [](decltype(s.st_mode) x) { return (x & S_IFMT) == S_IFREG; }; #else struct stat s; r = stat(fileanme.c_str(), &s); #endif if(r || !S_ISREG(s.st_mode)) { return 0; } else { return static_cast<uint64_t>(s.st_size); } } }} // namespace Cstdio, Lz4Mt <commit_msg>Remove unnecessary cast.<commit_after>#include <sys/types.h> #include <sys/stat.h> #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #include "lz4mt_io_cstdio.h" #include "lz4mt.h" namespace { FILE* fopen_(const char* filename, const char* mode) { #if defined(_MSC_VER) FILE* fp = nullptr; ::fopen_s(&fp, filename, mode); return fp; #else return ::fopen(filename, mode); #endif } void fclose_(FILE* fp) { if(fp) { if(fp != stdin && fp != stdout) { ::fclose(fp); } } } FILE* getStdin() { #ifdef _WIN32 (void) _setmode(_fileno(stdin), _O_BINARY); #endif return stdin; } FILE* getStdout() { #ifdef _WIN32 (void) _setmode(_fileno(stdout), _O_BINARY); #endif return stdout; } } namespace Lz4Mt { namespace Cstdio { bool fileExist(const std::string& filename) { if("stdin" == filename || "stdout" == filename) { return false; } else { FILE* fp = fopen_(filename.c_str(), "rb"); fclose_(fp); return nullptr != fp; } } FILE* readCtx(const Lz4MtContext* ctx) { return reinterpret_cast<FILE*>(ctx->readCtx); } FILE* writeCtx(const Lz4MtContext* ctx) { return reinterpret_cast<FILE*>(ctx->writeCtx); } bool openIstream(Lz4MtContext* ctx, const std::string& filename) { FILE* fp = nullptr; if("stdin" == filename) { fp = getStdin(); } else { fp = fopen_(filename.c_str(), "rb"); } ctx->readCtx = fp; return nullptr != fp; } bool openOstream(Lz4MtContext* ctx, const std::string& filename) { FILE* fp = nullptr; if("stdout" == filename) { fp = getStdout(); } else { fp = fopen_(filename.c_str(), "wb"); } ctx->writeCtx = fp; return nullptr != fp; } void closeIstream(Lz4MtContext* ctx) { fclose_(readCtx(ctx)); ctx->readCtx = nullptr; } void closeOstream(Lz4MtContext* ctx) { fclose_(writeCtx(ctx)); ctx->writeCtx = nullptr; } int read(Lz4MtContext* ctx, void* dst, int dstSize) { if(auto* fp = readCtx(ctx)) { return static_cast<int>(::fread(dst, 1, dstSize, fp)); } else { return 0; } } int readSkippable(const Lz4MtContext* ctx , uint32_t //magicNumber , size_t size) { if(auto* fp = readCtx(ctx)) { return ::fseek(fp, static_cast<long>(size), SEEK_CUR); } else { return -1; } } int readSeek(const Lz4MtContext* ctx, int offset) { if(auto* fp = readCtx(ctx)) { return ::fseek(fp, offset, SEEK_CUR); } else { return -1; } } int readEof(const Lz4MtContext* ctx) { if(auto* fp = readCtx(ctx)) { return ::feof(fp); } else { return 1; } } int write(const Lz4MtContext* ctx, const void* source, int sourceSize) { if(auto* fp = writeCtx(ctx)) { return static_cast<int>(::fwrite(source, 1, sourceSize, fp)); } else { return 0; } } uint64_t getFilesize(const std::string& fileanme) { int r = 0; #if defined(_MSC_VER) struct _stat64 s = { 0 }; r = _stat64(fileanme.c_str(), &s); auto S_ISREG = [](decltype(s.st_mode) x) { return (x & S_IFMT) == S_IFREG; }; #else struct stat s; r = stat(fileanme.c_str(), &s); #endif if(r || !S_ISREG(s.st_mode)) { return 0; } else { return static_cast<uint64_t>(s.st_size); } } }} // namespace Cstdio, Lz4Mt <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/PingPacket.h" namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); atexit_ptr(shutdownGNE); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 1; return ret; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setUserVersion(guint32 version) { assert(initialized); userVersion = version; } void checkVersions(const GNEProtocolVersionNumber& otherGNE, guint32 otherUser) throw (Error) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version && otherGNE.subVersion != us.subVersion && otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw new Error(Error::GNETheirVersionHigh); else throw new Error(Error::GNETheirVersionLow); } //Check the user version numbers if (userVersion != otherUser) { throw new Error(Error::UserVersionMismatch); } } } <commit_msg>Uses new endian selection feature in HawkNL 1.5.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/PingPacket.h" namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); atexit_ptr(shutdownGNE); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); //GNE sends its data in little endian format. nlEnable(NL_LITTLE_ENDIAN_DATA); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 1; return ret; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setUserVersion(guint32 version) { assert(initialized); userVersion = version; } void checkVersions(const GNEProtocolVersionNumber& otherGNE, guint32 otherUser) throw (Error) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version && otherGNE.subVersion != us.subVersion && otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw new Error(Error::GNETheirVersionHigh); else throw new Error(Error::GNETheirVersionLow); } //Check the user version numbers if (userVersion != otherUser) { throw new Error(Error::UserVersionMismatch); } } } <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/PingPacket.h" namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } char gameNameBuf[32] = {0}; guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); atexit_ptr(shutdownGNE); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); //GNE sends its data in little endian format. nlEnable(NL_LITTLE_ENDIAN_DATA); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 4; return ret; } const char* getGameName() { return gameNameBuf; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setGameInformation(std::string gameName, guint32 version) { assert(initialized); assert(gameName.length() <= GNE::MAX_GAME_NAME_LEN); //We do this assert since this function should only be called once. assert(gameNameBuf[0] = 0); userVersion = version; strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN); } void checkVersions(const GNEProtocolVersionNumber& otherGNE, std::string otherName, guint32 otherUser) throw (Error) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version || otherGNE.subVersion != us.subVersion || otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw Error(Error::GNETheirVersionHigh); else throw Error(Error::GNETheirVersionLow); } //Check the game name if (otherName != gameNameBuf) throw Error(Error::WrongGame); //Check the user version numbers if (userVersion != otherUser) throw Error(Error::UserVersionMismatch); } } <commit_msg>Small = to == fix.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/PingPacket.h" namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } char gameNameBuf[32] = {0}; guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); atexit_ptr(shutdownGNE); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); //GNE sends its data in little endian format. nlEnable(NL_LITTLE_ENDIAN_DATA); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 4; return ret; } const char* getGameName() { return gameNameBuf; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setGameInformation(std::string gameName, guint32 version) { assert(initialized); assert(gameName.length() <= GNE::MAX_GAME_NAME_LEN); //We do this assert since this function should only be called once. assert(gameNameBuf[0] == 0); userVersion = version; strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN); } void checkVersions(const GNEProtocolVersionNumber& otherGNE, std::string otherName, guint32 otherUser) throw (Error) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version || otherGNE.subVersion != us.subVersion || otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw Error(Error::GNETheirVersionHigh); else throw Error(Error::GNETheirVersionLow); } //Check the game name if (otherName != gameNameBuf) throw Error(Error::WrongGame); //Check the user version numbers if (userVersion != otherUser) throw Error(Error::UserVersionMismatch); } } <|endoftext|>
<commit_before><commit_msg>todo refactoring<commit_after><|endoftext|>
<commit_before>// @(#)root/graf:$Name: $:$Id: TCutG.cxx,v 1.11 2002/03/15 22:11:47 brun Exp $ // Author: Rene Brun 16/05/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCutG // // // // A Graphical cut. // // A TCutG object defines a closed polygon in a x,y plot. // // It can be created via the graphics editor option "CutG" // // or directly by invoking its constructor. // // To create a TCutG via the graphics editor, use the left button // // to select the points building the contour of the cut. Click on // // the right button to close the TCutG. // // When it is created via the graphics editor, the TCutG object // // is named "CUTG". It is recommended to immediatly change the name // // by using the context menu item "SetName". // // // When the graphics editor is used, the names of the variables X,Y // // are automatically taken from the current pad title. // // Example: // // Assume a TTree object T and: // // Root > T.Draw("abs(fMomemtum)%fEtot") // // the TCutG members fVarX, fVary will be set to: // // fVarx = fEtot // // fVary = abs(fMomemtum) // // // // A graphical cut can be used in a TTree selection expression: // // Root > T.Draw("fEtot","cutg1") // // where "cutg1" is the name of an existing graphical cut. // // // // Note that, as shown in the example above, a graphical cut may be // // used in a selection expression when drawing TTrees expressions // // of 1-d, 2-d or 3-dimensions. // // The expressions used in TTree::Draw can reference the variables // // in the fVarX, fVarY of the graphical cut plus other variables. // // // // When the TCutG object is created, it is added to the list of special// // objects in the main TROOT object pointed by gROOT. To retrieve a // // pointer to this object from the code or command line, do: // // TCutG *mycutg; // // mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") // // mycutg->SetName("mycutg"); // // // // Example of use of a TCutG in TTree::Draw: // // tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1") // // // // A Graphical cut may be drawn via TGraph::Draw. // // It can be edited like a normal TGraph. // // // // A Graphical cut may be saved to a file via TCutG::Write. // // // // ////////////////////////////////////////////////////////////////////////// #include <string.h> #include "Riostream.h" #include "TROOT.h" #include "TCutG.h" #include "TVirtualPad.h" #include "TPaveText.h" ClassImp(TCutG) //______________________________________________________________________________ TCutG::TCutG() : TGraph() { fObjectX = 0; fObjectY = 0; gROOT->GetListOfSpecials()->Add(this); } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n) :TGraph(n) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::~TCutG() { delete fObjectX; delete fObjectY; gROOT->GetListOfSpecials()->Remove(this); } //______________________________________________________________________________ Int_t TCutG::IsInside(Double_t x, Double_t y) const { //*. Function which returns 1 if point x,y lies inside the //*. polygon defined by the graph points //*. 0 otherwise //*. //*. The loop is executed with the end-point coordinates of a //*. line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a //*. horizontal line. //*. The counter inter is incremented if the line (X1,Y1)-(X2,Y2) //*. intersects the horizontal line. //*. In this case XINT is set to the X-coordinate of the //*. intersection point. //*. If inter is an odd number, then the point x,y is within //*. the polygon. //*. //*. This routine is based on an original algorithm //*. developed by R.Nierhaus. //*. Double_t xint; Int_t i; Int_t inter = 0; for (i=0;i<fNpoints-1;i++) { if (fY[i] == fY[i+1]) continue; if (y <= fY[i] && y <= fY[i+1]) continue; if (fY[i] < y && fY[i+1] < y) continue; xint = fX[i] + (y-fY[i])*(fX[i+1]-fX[i])/(fY[i+1]-fY[i]); if (x < xint) inter++; } if (inter%2) return 1; return 0; } //______________________________________________________________________________ void TCutG::SavePrimitive(ofstream &out, Option_t *option) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TCutG::Class())) { out<<" "; } else { out<<" TCutG *"; } out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl; out<<" cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl; out<<" cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl; out<<" cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl; SaveFillAttributes(out,"cutg",0,1001); SaveLineAttributes(out,"cutg",1,1,1); SaveMarkerAttributes(out,"cutg",1,1,1); for (Int_t i=0;i<fNpoints;i++) { out<<" cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl; } out<<" cutg->Draw(" <<quote<<option<<quote<<");"<<endl; } //______________________________________________________________________________ void TCutG::SetVarX(const char *varx) { fVarX = varx; delete fObjectX; fObjectX = 0; } //______________________________________________________________________________ void TCutG::SetVarY(const char *vary) { fVarY = vary; delete fObjectY; fObjectY = 0; } //______________________________________________________________________________ void TCutG::Streamer(TBuffer &R__b) { // Stream an object of class TCutG. if (R__b.IsReading()) { TCutG::Class()->ReadBuffer(R__b, this); gROOT->GetListOfSpecials()->Add(this); } else { TCutG::Class()->WriteBuffer(R__b, this); } } <commit_msg>In TCutG default constructor, do not add the cut to the list of specials. When reading from a file, the cut is added in Streamer.<commit_after>// @(#)root/graf:$Name: $:$Id: TCutG.cxx,v 1.12 2002/03/26 07:05:57 brun Exp $ // Author: Rene Brun 16/05/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TCutG // // // // A Graphical cut. // // A TCutG object defines a closed polygon in a x,y plot. // // It can be created via the graphics editor option "CutG" // // or directly by invoking its constructor. // // To create a TCutG via the graphics editor, use the left button // // to select the points building the contour of the cut. Click on // // the right button to close the TCutG. // // When it is created via the graphics editor, the TCutG object // // is named "CUTG". It is recommended to immediatly change the name // // by using the context menu item "SetName". // // // When the graphics editor is used, the names of the variables X,Y // // are automatically taken from the current pad title. // // Example: // // Assume a TTree object T and: // // Root > T.Draw("abs(fMomemtum)%fEtot") // // the TCutG members fVarX, fVary will be set to: // // fVarx = fEtot // // fVary = abs(fMomemtum) // // // // A graphical cut can be used in a TTree selection expression: // // Root > T.Draw("fEtot","cutg1") // // where "cutg1" is the name of an existing graphical cut. // // // // Note that, as shown in the example above, a graphical cut may be // // used in a selection expression when drawing TTrees expressions // // of 1-d, 2-d or 3-dimensions. // // The expressions used in TTree::Draw can reference the variables // // in the fVarX, fVarY of the graphical cut plus other variables. // // // // When the TCutG object is created, it is added to the list of special// // objects in the main TROOT object pointed by gROOT. To retrieve a // // pointer to this object from the code or command line, do: // // TCutG *mycutg; // // mycutg = (TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG") // // mycutg->SetName("mycutg"); // // // // Example of use of a TCutG in TTree::Draw: // // tree.Draw("x:y","mycutg && z>0 %% sqrt(x)>1") // // // // A Graphical cut may be drawn via TGraph::Draw. // // It can be edited like a normal TGraph. // // // // A Graphical cut may be saved to a file via TCutG::Write. // // // // ////////////////////////////////////////////////////////////////////////// #include <string.h> #include "Riostream.h" #include "TROOT.h" #include "TCutG.h" #include "TVirtualPad.h" #include "TPaveText.h" ClassImp(TCutG) //______________________________________________________________________________ TCutG::TCutG() : TGraph() { fObjectX = 0; fObjectY = 0; } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n) :TGraph(n) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Float_t *x, const Float_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::TCutG(const char *name, Int_t n, const Double_t *x, const Double_t *y) :TGraph(n,x,y) { fObjectX = 0; fObjectY = 0; SetName(name); delete gROOT->GetListOfSpecials()->FindObject(name); gROOT->GetListOfSpecials()->Add(this); // Take name of cut variables from pad title if title contains ":" if (gPad) { TPaveText *ptitle = (TPaveText*)gPad->FindObject("title"); if (!ptitle) return; TText *ttitle = ptitle->GetLineWith(":"); if (!ttitle) ttitle = ptitle->GetLineWith("{"); if (!ttitle) ttitle = ptitle->GetLine(0); if (!ttitle) return; const char *title = ttitle->GetTitle(); Int_t nch = strlen(title); char *vars = new char[nch+1]; strcpy(vars,title); char *col = strstr(vars,":"); if (col) { *col = 0; col++; char *brak = strstr(col," {"); if (brak) *brak = 0; fVarY = vars; fVarX = col; } else { char *brak = strstr(vars," {"); if (brak) *brak = 0; fVarX = vars; } delete [] vars; } } //______________________________________________________________________________ TCutG::~TCutG() { delete fObjectX; delete fObjectY; gROOT->GetListOfSpecials()->Remove(this); } //______________________________________________________________________________ Int_t TCutG::IsInside(Double_t x, Double_t y) const { //*. Function which returns 1 if point x,y lies inside the //*. polygon defined by the graph points //*. 0 otherwise //*. //*. The loop is executed with the end-point coordinates of a //*. line segment (X1,Y1)-(X2,Y2) and the Y-coordinate of a //*. horizontal line. //*. The counter inter is incremented if the line (X1,Y1)-(X2,Y2) //*. intersects the horizontal line. //*. In this case XINT is set to the X-coordinate of the //*. intersection point. //*. If inter is an odd number, then the point x,y is within //*. the polygon. //*. //*. This routine is based on an original algorithm //*. developed by R.Nierhaus. //*. Double_t xint; Int_t i; Int_t inter = 0; for (i=0;i<fNpoints-1;i++) { if (fY[i] == fY[i+1]) continue; if (y <= fY[i] && y <= fY[i+1]) continue; if (fY[i] < y && fY[i+1] < y) continue; xint = fX[i] + (y-fY[i])*(fX[i+1]-fX[i])/(fY[i+1]-fY[i]); if (x < xint) inter++; } if (inter%2) return 1; return 0; } //______________________________________________________________________________ void TCutG::SavePrimitive(ofstream &out, Option_t *option) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TCutG::Class())) { out<<" "; } else { out<<" TCutG *"; } out<<"cutg = new TCutG("<<quote<<GetName()<<quote<<","<<fNpoints<<");"<<endl; out<<" cutg->SetVarX("<<quote<<GetVarX()<<quote<<");"<<endl; out<<" cutg->SetVarY("<<quote<<GetVarY()<<quote<<");"<<endl; out<<" cutg->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl; SaveFillAttributes(out,"cutg",0,1001); SaveLineAttributes(out,"cutg",1,1,1); SaveMarkerAttributes(out,"cutg",1,1,1); for (Int_t i=0;i<fNpoints;i++) { out<<" cutg->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl; } out<<" cutg->Draw(" <<quote<<option<<quote<<");"<<endl; } //______________________________________________________________________________ void TCutG::SetVarX(const char *varx) { fVarX = varx; delete fObjectX; fObjectX = 0; } //______________________________________________________________________________ void TCutG::SetVarY(const char *vary) { fVarY = vary; delete fObjectY; fObjectY = 0; } //______________________________________________________________________________ void TCutG::Streamer(TBuffer &R__b) { // Stream an object of class TCutG. if (R__b.IsReading()) { TCutG::Class()->ReadBuffer(R__b, this); gROOT->GetListOfSpecials()->Add(this); } else { TCutG::Class()->WriteBuffer(R__b, this); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: BColumns.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: oj $ $Date: 2001-10-12 11:39:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_COLUMNS_HXX_ #include "adabas/BColumns.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_ #include "adabas/BTable.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_TABLES_HXX_ #include "adabas/BTables.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_ #include "adabas/BCatalog.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif using namespace ::comphelper; using namespace connectivity::adabas; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; Reference< XNamed > OColumns::createObject(const ::rtl::OUString& _rName) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns(Any(), m_pTable->getSchema(),m_pTable->getTableName(),_rName); Reference< XNamed > xRet = NULL; if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while(xResult->next()) { if(xRow->getString(4) == _rName) { sal_Int32 nType = xRow->getInt(5); ::rtl::OUString sTypeName = xRow->getString(6); sal_Int32 nPrec = xRow->getInt(7); OAdabasCatalog::correctColumnProperties(nPrec,nType,sTypeName); OColumn* pRet = new OColumn(_rName, sTypeName, xRow->getString(13), xRow->getInt(11), nPrec, xRow->getInt(9), nType, sal_False,sal_False,sal_False,sal_True); xRet = pRet; break; } } ::comphelper::disposeComponent(xResult); } return xRet; } // ------------------------------------------------------------------------- void OColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OColumns::createEmptyObject() { return new OColumn(sal_True); } // ----------------------------------------------------------------------------- Reference< XNamed > OColumns::cloneObject(const Reference< XPropertySet >& _xDescriptor) { OColumn* pColumn = new OColumn(sal_True); Reference<XPropertySet> xProp = pColumn; ::comphelper::copyProperties(_xDescriptor,xProp); Reference< XNamed > xName(xProp,UNO_QUERY); OSL_ENSURE(xName.is(),"Must be a XName interface here !"); return xName; } // ------------------------------------------------------------------------- // XAppend void OColumns::appendObject( const Reference< XPropertySet >& descriptor ) { ::osl::MutexGuard aGuard(m_rMutex); OSL_ENSURE(m_pTable,"OColumns::appendByDescriptor: Table is null!"); OSL_ENSURE(descriptor.is(),"OColumns::appendByDescriptor: descriptor is null!"); if(descriptor.is() && !m_pTable->isNew()) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE "); ::rtl::OUString sQuote = m_pTable->getConnection()->getMetaData()->getIdentifierQuoteString( ); const ::rtl::OUString& sDot = OAdabasCatalog::getDot(); m_pTable->beginTransAction(); try { ::rtl::OUString sColumnName; descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sColumnName; aSql += ::dbtools::quoteName(sQuote,m_pTable->getSchema()) + sDot + ::dbtools::quoteName(sQuote,m_pTable->getTableName()); aSql += ::rtl::OUString::createFromAscii(" ADD ("); aSql += ::dbtools::quoteName(sQuote,sColumnName); aSql += ::rtl::OUString::createFromAscii(" "); aSql += OTables::getColumnSqlType(descriptor); aSql += ::rtl::OUString::createFromAscii(" )"); Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement(); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); m_pTable->alterNotNullValue(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE))),sColumnName); } catch(const Exception&) { m_pTable->rollbackTransAction(); throw; } m_pTable->endTransAction(); } } // ------------------------------------------------------------------------- // XDrop void OColumns::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { OSL_ENSURE(m_pTable,"OColumns::dropByName: Table is null!"); if(!m_pTable->isNew()) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE "); ::rtl::OUString sQuote = m_pTable->getConnection()->getMetaData()->getIdentifierQuoteString( ); const ::rtl::OUString& sDot = OAdabasCatalog::getDot(); aSql += ::dbtools::quoteName(sQuote,m_pTable->getSchema()) + sDot + ::dbtools::quoteName(sQuote,m_pTable->getTableName()); aSql += ::rtl::OUString::createFromAscii(" DROP "); aSql += ::dbtools::quoteName(sQuote,_sElementName); Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba24 (1.15.262); FILE MERGED 2005/02/09 08:07:36 oj 1.15.262.1: #i26950# remove the need for XNamed<commit_after>/************************************************************************* * * $RCSfile: BColumns.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2005-03-10 15:19:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_COLUMNS_HXX_ #include "adabas/BColumns.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_ #include "adabas/BTable.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_TABLES_HXX_ #include "adabas/BTables.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_ #include "adabas/BCatalog.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif using namespace ::comphelper; using namespace connectivity::adabas; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; sdbcx::ObjectType OColumns::createObject(const ::rtl::OUString& _rName) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns(Any(), m_pTable->getSchema(),m_pTable->getTableName(),_rName); sdbcx::ObjectType xRet = NULL; if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while(xResult->next()) { if(xRow->getString(4) == _rName) { sal_Int32 nType = xRow->getInt(5); ::rtl::OUString sTypeName = xRow->getString(6); sal_Int32 nPrec = xRow->getInt(7); OAdabasCatalog::correctColumnProperties(nPrec,nType,sTypeName); xRet = new OColumn(_rName, sTypeName, xRow->getString(13), xRow->getInt(11), nPrec, xRow->getInt(9), nType, sal_False,sal_False,sal_False,sal_True); break; } } ::comphelper::disposeComponent(xResult); } return xRet; } // ------------------------------------------------------------------------- void OColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OColumns::createEmptyObject() { return new OColumn(sal_True); } // ----------------------------------------------------------------------------- sdbcx::ObjectType OColumns::cloneObject(const Reference< XPropertySet >& _xDescriptor) { sdbcx::ObjectType xProp = new OColumn(sal_True); ::comphelper::copyProperties(_xDescriptor,xProp); return xProp; } // ------------------------------------------------------------------------- // XAppend void OColumns::appendObject( const Reference< XPropertySet >& descriptor ) { ::osl::MutexGuard aGuard(m_rMutex); OSL_ENSURE(m_pTable,"OColumns::appendByDescriptor: Table is null!"); OSL_ENSURE(descriptor.is(),"OColumns::appendByDescriptor: descriptor is null!"); if(descriptor.is() && !m_pTable->isNew()) { ::rtl::OUString aSql(RTL_CONSTASCII_USTRINGPARAM("ALTER TABLE ")); ::rtl::OUString sQuote = m_pTable->getConnection()->getMetaData()->getIdentifierQuoteString( ); const ::rtl::OUString& sDot = OAdabasCatalog::getDot(); m_pTable->beginTransAction(); try { ::rtl::OUString sColumnName; descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sColumnName; aSql += ::dbtools::quoteName(sQuote,m_pTable->getSchema()) + sDot + ::dbtools::quoteName(sQuote,m_pTable->getTableName()); aSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ADD (")); aSql += ::dbtools::quoteName(sQuote,sColumnName); aSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); aSql += OTables::getColumnSqlType(descriptor); aSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" )")); Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement(); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); m_pTable->alterNotNullValue(getINT32(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE))),sColumnName); } catch(const Exception&) { m_pTable->rollbackTransAction(); throw; } m_pTable->endTransAction(); } } // ------------------------------------------------------------------------- // XDrop void OColumns::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { OSL_ENSURE(m_pTable,"OColumns::dropByName: Table is null!"); if(!m_pTable->isNew()) { ::rtl::OUString aSql(RTL_CONSTASCII_USTRINGPARAM("ALTER TABLE ")); ::rtl::OUString sQuote = m_pTable->getConnection()->getMetaData()->getIdentifierQuoteString( ); const ::rtl::OUString& sDot = OAdabasCatalog::getDot(); aSql += ::dbtools::quoteName(sQuote,m_pTable->getSchema()) + sDot + ::dbtools::quoteName(sQuote,m_pTable->getTableName()); aSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" DROP ")); aSql += ::dbtools::quoteName(sQuote,_sElementName); Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gpu/gpu_process_host_ui_shim.h" #include <algorithm> #include "base/bind.h" #include "base/command_line.h" #include "base/id_map.h" #include "base/lazy_instance.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/debug/trace_event.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/browser/gpu/gpu_surface_tracker.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/common/gpu/gpu_messages.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/browser_thread.h" #include "ui/gfx/gl/gl_switches.h" #if defined(TOOLKIT_GTK) // These two #includes need to come after gpu_messages.h. #include "ui/base/x/x11_util.h" #include "ui/gfx/size.h" #include <gdk/gdk.h> // NOLINT #include <gdk/gdkx.h> // NOLINT #endif using content::BrowserThread; using content::RenderWidgetHostImpl; using content::RenderWidgetHostViewPort; namespace { // One of the linux specific headers defines this as a macro. #ifdef DestroyAll #undef DestroyAll #endif base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id = LAZY_INSTANCE_INITIALIZER; void SendOnIOThreadTask(int host_id, IPC::Message* msg) { GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) host->Send(msg); else delete msg; } class ScopedSendOnIOThread { public: ScopedSendOnIOThread(int host_id, IPC::Message* msg) : host_id_(host_id), msg_(msg), cancelled_(false) { } ~ScopedSendOnIOThread() { if (!cancelled_) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SendOnIOThreadTask, host_id_, msg_.release())); } } void Cancel() { cancelled_ = true; } private: int host_id_; scoped_ptr<IPC::Message> msg_; bool cancelled_; }; RenderWidgetHostViewPort* GetRenderWidgetHostViewFromSurfaceID( int surface_id) { int render_process_id = 0; int render_widget_id = 0; if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface( surface_id, &render_process_id, &render_widget_id)) return NULL; content::RenderProcessHost* process = content::RenderProcessHost::FromID(render_process_id); if (!process) return NULL; content::RenderWidgetHost* host = process->GetRenderWidgetHostByID( render_widget_id); return host ? RenderWidgetHostViewPort::FromRWHV(host->GetView()) : NULL; } } // namespace void RouteToGpuProcessHostUIShimTask(int host_id, const IPC::Message& msg) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id); if (ui_shim) ui_shim->OnMessageReceived(msg); } GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id) : host_id_(host_id) { g_hosts_by_id.Pointer()->AddWithID(this, host_id_); } // static GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) { DCHECK(!FromID(host_id)); return new GpuProcessHostUIShim(host_id); } // static void GpuProcessHostUIShim::Destroy(int host_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); delete FromID(host_id); } // static void GpuProcessHostUIShim::DestroyAll() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); while (!g_hosts_by_id.Pointer()->IsEmpty()) { IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer()); delete it.GetCurrentValue(); } } // static GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_hosts_by_id.Pointer()->Lookup(host_id); } // static GpuProcessHostUIShim* GpuProcessHostUIShim::GetOneInstance() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (g_hosts_by_id.Pointer()->IsEmpty()) return NULL; IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer()); return it.GetCurrentValue(); } bool GpuProcessHostUIShim::Send(IPC::Message* msg) { DCHECK(CalledOnValidThread()); return BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SendOnIOThreadTask, host_id_, msg)); } bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) { DCHECK(CalledOnValidThread()); if (message.routing_id() != MSG_ROUTING_CONTROL) return false; return OnControlMessageReceived(message); } void GpuProcessHostUIShim::SimulateRemoveAllContext() { Send(new GpuMsg_Clean()); } void GpuProcessHostUIShim::SimulateCrash() { Send(new GpuMsg_Crash()); } void GpuProcessHostUIShim::SimulateHang() { Send(new GpuMsg_Hang()); } GpuProcessHostUIShim::~GpuProcessHostUIShim() { DCHECK(CalledOnValidThread()); g_hosts_by_id.Pointer()->Remove(host_id_); } bool GpuProcessHostUIShim::OnControlMessageReceived( const IPC::Message& message) { DCHECK(CalledOnValidThread()); IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message) IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage, OnLogMessage) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped, OnAcceleratedSurfaceBuffersSwapped) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfacePostSubBuffer, OnAcceleratedSurfacePostSubBuffer) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSuspend, OnAcceleratedSurfaceSuspend) IPC_MESSAGE_HANDLER(GpuHostMsg_GraphicsInfoCollected, OnGraphicsInfoCollected) #if defined(TOOLKIT_GTK) || defined(OS_WIN) IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView) #endif #if defined(USE_AURA) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceNew, OnAcceleratedSurfaceNew) #endif #if defined(USE_AURA) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease, OnAcceleratedSurfaceRelease) #endif IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } void GpuProcessHostUIShim::OnLogMessage( int level, const std::string& header, const std::string& message) { DictionaryValue* dict = new DictionaryValue(); dict->SetInteger("level", level); dict->SetString("header", header); dict->SetString("message", message); GpuDataManagerImpl::GetInstance()->AddLogMessage(dict); } void GpuProcessHostUIShim::OnGraphicsInfoCollected( const content::GPUInfo& gpu_info) { // OnGraphicsInfoCollected is sent back after the GPU process successfully // initializes GL. TRACE_EVENT0("test_gpu", "OnGraphicsInfoCollected"); GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info); } #if defined(TOOLKIT_GTK) || defined(OS_WIN) void GpuProcessHostUIShim::OnResizeView(int32 surface_id, int32 route_id, gfx::Size size) { // Always respond even if the window no longer exists. The GPU process cannot // make progress on the resizing command buffer until it receives the // response. ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_ResizeViewACK(route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(surface_id); if (!view) return; gfx::GLSurfaceHandle surface = view->GetCompositingSurface(); // Resize the window synchronously. The GPU process must not issue GL // calls on the command buffer until the window is the size it expects it // to be. #if defined(TOOLKIT_GTK) GdkWindow* window = reinterpret_cast<GdkWindow*>( gdk_xid_table_lookup(surface.handle)); if (window) { Display* display = GDK_WINDOW_XDISPLAY(window); gdk_window_resize(window, size.width(), size.height()); XSync(display, False); } #elif defined(OS_WIN) // Ensure window does not have zero area because D3D cannot create a zero // area swap chain. SetWindowPos(surface.handle, NULL, 0, 0, std::max(1, size.width()), std::max(1, size.height()), SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER | SWP_NOACTIVATE | SWP_DEFERERASE); #endif } #endif #if defined(USE_AURA) void GpuProcessHostUIShim::OnAcceleratedSurfaceNew( const GpuHostMsg_AcceleratedSurfaceNew_Params& params) { ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_NewACK( params.route_id, params.surface_handle, TransportDIB::DefaultHandleValue())); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; uint64 surface_handle = params.surface_handle; TransportDIB::Handle shm_handle = TransportDIB::DefaultHandleValue(); view->AcceleratedSurfaceNew( params.width, params.height, &surface_handle, &shm_handle); delayed_send.Cancel(); Send(new AcceleratedSurfaceMsg_NewACK( params.route_id, surface_handle, shm_handle)); } #endif static base::TimeDelta GetSwapDelay() { CommandLine* cmd_line = CommandLine::ForCurrentProcess(); int delay = 0; if (cmd_line->HasSwitch(switches::kGpuSwapDelay)) { base::StringToInt(cmd_line->GetSwitchValueNative( switches::kGpuSwapDelay).c_str(), &delay); } return base::TimeDelta::FromMilliseconds(delay); } void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); // View must send ACK message after next composite. view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_PostSubBufferACK(params.route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(params.surface_id); if (!view) return; delayed_send.Cancel(); // View must send ACK message after next composite. view->AcceleratedSurfacePostSubBuffer(params, host_id_); } void GpuProcessHostUIShim::OnAcceleratedSurfaceSuspend(int32 surface_id) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceSuspend"); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(surface_id); if (!view) return; view->AcceleratedSurfaceSuspend(); } #if defined(USE_AURA) void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease( const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; view->AcceleratedSurfaceRelease(params.identifier); } #endif <commit_msg>Add a message to about:gpu when the gpu process crashes.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gpu/gpu_process_host_ui_shim.h" #include <algorithm> #include "base/bind.h" #include "base/command_line.h" #include "base/id_map.h" #include "base/lazy_instance.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/debug/trace_event.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/browser/gpu/gpu_surface_tracker.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/common/gpu/gpu_messages.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/browser_thread.h" #include "ui/gfx/gl/gl_switches.h" #if defined(TOOLKIT_GTK) // These two #includes need to come after gpu_messages.h. #include "ui/base/x/x11_util.h" #include "ui/gfx/size.h" #include <gdk/gdk.h> // NOLINT #include <gdk/gdkx.h> // NOLINT #endif using content::BrowserThread; using content::RenderWidgetHostImpl; using content::RenderWidgetHostViewPort; namespace { // One of the linux specific headers defines this as a macro. #ifdef DestroyAll #undef DestroyAll #endif base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id = LAZY_INSTANCE_INITIALIZER; void SendOnIOThreadTask(int host_id, IPC::Message* msg) { GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) host->Send(msg); else delete msg; } class ScopedSendOnIOThread { public: ScopedSendOnIOThread(int host_id, IPC::Message* msg) : host_id_(host_id), msg_(msg), cancelled_(false) { } ~ScopedSendOnIOThread() { if (!cancelled_) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SendOnIOThreadTask, host_id_, msg_.release())); } } void Cancel() { cancelled_ = true; } private: int host_id_; scoped_ptr<IPC::Message> msg_; bool cancelled_; }; RenderWidgetHostViewPort* GetRenderWidgetHostViewFromSurfaceID( int surface_id) { int render_process_id = 0; int render_widget_id = 0; if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface( surface_id, &render_process_id, &render_widget_id)) return NULL; content::RenderProcessHost* process = content::RenderProcessHost::FromID(render_process_id); if (!process) return NULL; content::RenderWidgetHost* host = process->GetRenderWidgetHostByID( render_widget_id); return host ? RenderWidgetHostViewPort::FromRWHV(host->GetView()) : NULL; } } // namespace void RouteToGpuProcessHostUIShimTask(int host_id, const IPC::Message& msg) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id); if (ui_shim) ui_shim->OnMessageReceived(msg); } GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id) : host_id_(host_id) { g_hosts_by_id.Pointer()->AddWithID(this, host_id_); } // static GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) { DCHECK(!FromID(host_id)); return new GpuProcessHostUIShim(host_id); } // static void GpuProcessHostUIShim::Destroy(int host_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); delete FromID(host_id); } // static void GpuProcessHostUIShim::DestroyAll() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); while (!g_hosts_by_id.Pointer()->IsEmpty()) { IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer()); delete it.GetCurrentValue(); } } // static GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_hosts_by_id.Pointer()->Lookup(host_id); } // static GpuProcessHostUIShim* GpuProcessHostUIShim::GetOneInstance() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (g_hosts_by_id.Pointer()->IsEmpty()) return NULL; IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer()); return it.GetCurrentValue(); } bool GpuProcessHostUIShim::Send(IPC::Message* msg) { DCHECK(CalledOnValidThread()); return BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SendOnIOThreadTask, host_id_, msg)); } bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) { DCHECK(CalledOnValidThread()); if (message.routing_id() != MSG_ROUTING_CONTROL) return false; return OnControlMessageReceived(message); } void GpuProcessHostUIShim::SimulateRemoveAllContext() { Send(new GpuMsg_Clean()); } void GpuProcessHostUIShim::SimulateCrash() { Send(new GpuMsg_Crash()); } void GpuProcessHostUIShim::SimulateHang() { Send(new GpuMsg_Hang()); } GpuProcessHostUIShim::~GpuProcessHostUIShim() { DCHECK(CalledOnValidThread()); g_hosts_by_id.Pointer()->Remove(host_id_); DictionaryValue* dict = new DictionaryValue(); dict->SetInteger("level", logging::LOG_ERROR); dict->SetString("header", "GpuProcessHostUIShim"); dict->SetString("message", "GPU Process Crashed."); GpuDataManagerImpl::GetInstance()->AddLogMessage(dict); } bool GpuProcessHostUIShim::OnControlMessageReceived( const IPC::Message& message) { DCHECK(CalledOnValidThread()); IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message) IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage, OnLogMessage) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped, OnAcceleratedSurfaceBuffersSwapped) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfacePostSubBuffer, OnAcceleratedSurfacePostSubBuffer) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSuspend, OnAcceleratedSurfaceSuspend) IPC_MESSAGE_HANDLER(GpuHostMsg_GraphicsInfoCollected, OnGraphicsInfoCollected) #if defined(TOOLKIT_GTK) || defined(OS_WIN) IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView) #endif #if defined(USE_AURA) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceNew, OnAcceleratedSurfaceNew) #endif #if defined(USE_AURA) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease, OnAcceleratedSurfaceRelease) #endif IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } void GpuProcessHostUIShim::OnLogMessage( int level, const std::string& header, const std::string& message) { DictionaryValue* dict = new DictionaryValue(); dict->SetInteger("level", level); dict->SetString("header", header); dict->SetString("message", message); GpuDataManagerImpl::GetInstance()->AddLogMessage(dict); } void GpuProcessHostUIShim::OnGraphicsInfoCollected( const content::GPUInfo& gpu_info) { // OnGraphicsInfoCollected is sent back after the GPU process successfully // initializes GL. TRACE_EVENT0("test_gpu", "OnGraphicsInfoCollected"); GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info); } #if defined(TOOLKIT_GTK) || defined(OS_WIN) void GpuProcessHostUIShim::OnResizeView(int32 surface_id, int32 route_id, gfx::Size size) { // Always respond even if the window no longer exists. The GPU process cannot // make progress on the resizing command buffer until it receives the // response. ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_ResizeViewACK(route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(surface_id); if (!view) return; gfx::GLSurfaceHandle surface = view->GetCompositingSurface(); // Resize the window synchronously. The GPU process must not issue GL // calls on the command buffer until the window is the size it expects it // to be. #if defined(TOOLKIT_GTK) GdkWindow* window = reinterpret_cast<GdkWindow*>( gdk_xid_table_lookup(surface.handle)); if (window) { Display* display = GDK_WINDOW_XDISPLAY(window); gdk_window_resize(window, size.width(), size.height()); XSync(display, False); } #elif defined(OS_WIN) // Ensure window does not have zero area because D3D cannot create a zero // area swap chain. SetWindowPos(surface.handle, NULL, 0, 0, std::max(1, size.width()), std::max(1, size.height()), SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER | SWP_NOACTIVATE | SWP_DEFERERASE); #endif } #endif #if defined(USE_AURA) void GpuProcessHostUIShim::OnAcceleratedSurfaceNew( const GpuHostMsg_AcceleratedSurfaceNew_Params& params) { ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_NewACK( params.route_id, params.surface_handle, TransportDIB::DefaultHandleValue())); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; uint64 surface_handle = params.surface_handle; TransportDIB::Handle shm_handle = TransportDIB::DefaultHandleValue(); view->AcceleratedSurfaceNew( params.width, params.height, &surface_handle, &shm_handle); delayed_send.Cancel(); Send(new AcceleratedSurfaceMsg_NewACK( params.route_id, surface_handle, shm_handle)); } #endif static base::TimeDelta GetSwapDelay() { CommandLine* cmd_line = CommandLine::ForCurrentProcess(); int delay = 0; if (cmd_line->HasSwitch(switches::kGpuSwapDelay)) { base::StringToInt(cmd_line->GetSwitchValueNative( switches::kGpuSwapDelay).c_str(), &delay); } return base::TimeDelta::FromMilliseconds(delay); } void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); // View must send ACK message after next composite. view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_PostSubBufferACK(params.route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(params.surface_id); if (!view) return; delayed_send.Cancel(); // View must send ACK message after next composite. view->AcceleratedSurfacePostSubBuffer(params, host_id_); } void GpuProcessHostUIShim::OnAcceleratedSurfaceSuspend(int32 surface_id) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceSuspend"); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(surface_id); if (!view) return; view->AcceleratedSurfaceSuspend(); } #if defined(USE_AURA) void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease( const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) { RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; view->AcceleratedSurfaceRelease(params.identifier); } #endif <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreMaya/Parameter.h" #include "IECoreMaya/ToMayaObjectConverter.h" #include "IECoreMaya/FromMayaObjectConverter.h" #include "IECoreMaya/MeshParameterHandler.h" #include "IECore/TypedObjectParameter.h" #include "IECore/MeshPrimitive.h" #include "maya/MFnGenericAttribute.h" #include "maya/MFnMeshData.h" using namespace IECoreMaya; using namespace Imath; using namespace boost; static ParameterHandler::Description< MeshParameterHandler > registrar( IECore::MeshPrimitiveParameter::staticTypeId(), IECore::MeshPrimitive::staticTypeId() ); MStatus MeshParameterHandler::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MFnGenericAttribute fnGAttr( attribute ); if( !fnGAttr.hasObj( attribute ) ) { return MS::kFailure; } fnGAttr.addAccept( MFnData::kMesh ); return MS::kSuccess; } MObject MeshParameterHandler::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MObject::kNullObj; } /// Use a generic attribute, so we could eventually accept other ObjectParamter types, too. MFnGenericAttribute fnGAttr; MObject result = fnGAttr.create( attributeName, attributeName ); if ( !update( parameter, result ) ) { return MObject::kNullObj; } return result; } MStatus MeshParameterHandler::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MFnMeshData fnData; MObject data = fnData.create(); /// \todo Pull in userData from parameter to set up conversion parameters ToMayaObjectConverterPtr converter = ToMayaObjectConverter::create( p->getValue(), MFn::kMeshData ); assert(converter); bool conversionSuccess = converter->convert( data ); if ( !conversionSuccess ) { return MS::kFailure; } return plug.setValue( data ); } MStatus MeshParameterHandler::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const { intrusive_ptr<IECore::ObjectParameter> p = IECore::runTimeCast<IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MObject v; MStatus result = plug.getValue( v ); if( result ) { /// \todo Pull in userData from parameter to set up conversion parameters FromMayaObjectConverterPtr converter = FromMayaObjectConverter::create( v, IECore::MeshPrimitive::staticTypeId() ); assert(converter); p->setValue( converter->convert() ); } return result; } <commit_msg>Added temporary defence against Maya crash, and todos<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreMaya/Parameter.h" #include "IECoreMaya/ToMayaObjectConverter.h" #include "IECoreMaya/FromMayaObjectConverter.h" #include "IECoreMaya/MeshParameterHandler.h" #include "IECore/TypedObjectParameter.h" #include "IECore/MeshPrimitive.h" #include "maya/MFnGenericAttribute.h" #include "maya/MFnMeshData.h" using namespace IECoreMaya; using namespace Imath; using namespace boost; static ParameterHandler::Description< MeshParameterHandler > registrar( IECore::MeshPrimitiveParameter::staticTypeId(), IECore::MeshPrimitive::staticTypeId() ); MStatus MeshParameterHandler::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MFnGenericAttribute fnGAttr( attribute ); if( !fnGAttr.hasObj( attribute ) ) { return MS::kFailure; } fnGAttr.addAccept( MFnData::kMesh ); /// \todo It seems that Maya can crash under certain circumstances when saving as ASCII, usually when dealing with an empty mesh. Try and /// establish why. //fnGAttr.setStorable( false ); return MS::kSuccess; } MObject MeshParameterHandler::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MObject::kNullObj; } /// Use a generic attribute, so we could eventually accept other ObjectParamter types, too. MFnGenericAttribute fnGAttr; MObject result = fnGAttr.create( attributeName, attributeName ); if ( !update( parameter, result ) ) { return MObject::kNullObj; } return result; } MStatus MeshParameterHandler::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const { intrusive_ptr<const IECore::ObjectParameter> p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MFnMeshData fnData; MObject data = fnData.create(); /// \todo Pull in userData from parameter to set up conversion parameters ToMayaObjectConverterPtr converter = ToMayaObjectConverter::create( p->getValue(), MFn::kMeshData ); assert(converter); bool conversionSuccess = converter->convert( data ); if ( !conversionSuccess ) { return MS::kFailure; } /// \todo It seems like this can occassionally fail, usually with an empty mesh, but sometimes not. Try to establish exactly why. plug.setValue( data ); return MS::kSuccess; } MStatus MeshParameterHandler::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const { intrusive_ptr<IECore::ObjectParameter> p = IECore::runTimeCast<IECore::ObjectParameter>( parameter ); if( !p ) { return MS::kFailure; } MObject v; MStatus result = plug.getValue( v ); if( result ) { /// \todo Pull in userData from parameter to set up conversion parameters FromMayaObjectConverterPtr converter = FromMayaObjectConverter::create( v, IECore::MeshPrimitive::staticTypeId() ); assert(converter); p->setValue( converter->convert() ); } return result; } <|endoftext|>
<commit_before>#include "WPILib.h" #include "DeadSwipe.h" #include "UsefulMath.h" #include "F310.h" class Robot : public SampleRobot { // class wide declarations // drive train declarations - anything prefixed with db is a part of the drive train // motor declarations - motors are controlled by motor controllers. We use Talons Talon *dbFrontLeft; // pwm 6 Talon *dbRearLeft; // pwm 4 Talon *dbFrontRight; // pwm 7 Talon *dbRearRight; // pwm 9 RobotDrive *dbDrive; // easy tools ftw Talon *dbMiddleLeft; // pwm 5 Talon *dbMiddleRight; // pwm 8 // encoder declarations - encoders require 2 digital I/O pins and are used to measured how far a rotating object // has moved Encoder *dbLeftEncoder; // DIO 0 and 1 Encoder *dbRightEncoder; // DIO 2 and 3 Encoder *dbMidEncoder; // DIO 4 and 5 // gyro declaration - gyros allow us to measure how much an object has rotated along an axis // NOTE: gyros can(as of this writing) ONLY be used on AIN 0 and 1 Gyro *dbGyro; // AIN 0 // Elevator declarations Talon *eLeft; // pwm 0 Talon *eRight; // pwm 1 DoubleSolenoid *epLeft; // PCM ports 0 and 1 DoubleSolenoid *epRight; // PCM ports 2 and 3 DigitalInput *eLeftBottom; // DIO 6 DigitalInput *eLeftTop; // DIO 7 DigitalInput *eRightBottom; // DIO 8 DigitalInput *eRightTop; // DIO 9 // Encoder *eLeftEnc; // DIO 6 and 7 // Encoder *eRightEnc; // DIO 8 and 9 // intake declarations Talon *iLeft; // pwm 2 Talon *iRight; // pwm 3 DoubleSolenoid *ipLeft; // PCM ports 4 and 5 DoubleSolenoid *ipRight; // PCM ports 6 and 7 // operator interface declarations - prefixed by oi Joystick *oiLeft; Joystick *oiRight; F310 *oiGamepad; SendableChooser *autoChooser; // this is how we'll select different int mode1 = 0; int mode2 = 1; public: Robot() { oiLeft = new Joystick(0); oiRight = new Joystick(1); oiGamepad = new F310(2); autoChooser = new SendableChooser(); autoChooser->AddDefault("Do Nuffin", (int *) mode1); autoChooser->AddObject("Move you goddamm robot", (int *) mode2); dbFrontLeft = new Talon(6); dbRearLeft = new Talon(4); dbFrontRight = new Talon(7); dbRearRight = new Talon(9); dbDrive = new RobotDrive(dbFrontLeft, dbRearLeft, dbFrontRight, dbRearRight); dbDrive->SetSafetyEnabled(true); dbDrive->SetExpiration(0.1); dbDrive->SetSensitivity(0.5); dbDrive->SetMaxOutput(1.0); dbMiddleLeft = new Talon(5); dbMiddleRight = new Talon(8); dbLeftEncoder = new Encoder(0, 1, false, Encoder::k4X); dbLeftEncoder->SetDistancePerPulse(DRIVE_DISTANCE_PER_PULSE); dbRightEncoder = new Encoder(2, 3, false, Encoder::k4X); dbRightEncoder->SetDistancePerPulse(DRIVE_DISTANCE_PER_PULSE); dbMidEncoder = new Encoder(4, 5, false, Encoder::k4X); dbMidEncoder->SetDistancePerPulse(MIDDLE_DISTANCE_PER_PULSE); dbGyro = new Gyro(0); dbGyro->SetSensitivity(0.007); epLeft = new DoubleSolenoid(0, 0, 1); epRight = new DoubleSolenoid(0, 2, 3); eLeft = new Talon(2); eRight = new Talon(3); // eLeftEnc = new Encoder(6, 7, false, Encoder::k4X); // eLeftEnc->SetDistancePerPulse(OPTICAL_PPR); // // eRightEnc = new Encoder(8, 9, true, Encoder::k4X); // eRightEnc->SetDistancePerPulse(OPTICAL_PPR); eLeftBottom = new DigitalInput(6); eLeftTop = new DigitalInput(7); eRightBottom = new DigitalInput(8); eRightTop = new DigitalInput(9); ipLeft = new DoubleSolenoid(0, 4, 5); ipRight = new DoubleSolenoid(0, 6, 7); iLeft = new Talon(0); iRight= new Talon(1); } // end of constructor void Autonomous(void) { int aSelectedMode = (int) autoChooser->GetSelected(); while(IsEnabled() && IsAutonomous()) { this->Debug(); switch (aSelectedMode) { case 1: break; case 2: break; default: break; } this->Debug(); } // end of while loop } // end of auton void OperatorControl(void) { bool manualOverride = true; while(IsOperatorControl() && IsEnabled()) { this->Debug(); if(oiGamepad->GetButton(F310::kXButton) == true) { this->ePneumaticControl(B_CLOSE); } if(oiGamepad->GetButton(F310::kBButton) == true) { this->ePneumaticControl(B_OPEN); } if(oiGamepad->GetButton(F310::kXButton) && oiGamepad->GetButton(F310::kBButton)) { // do nothing. } if (oiGamepad->GetButton(F310::kStartButton)) { manualOverride = ~manualOverride; } if(oiGamepad->GetRawButton(F310::kAButton)) { eLeft->Set(0.0); eRight->Set(0.0); } if(oiGamepad->GetRawButton(F310::kRightBumper)) { eLeft->Set(1.0); eRight->Set(1.0); } if(oiGamepad->GetRawButton(F310::kRightTrigger)) { eLeft->Set(-1.0); eRight->Set(-1.0); } if(oiGamepad->GetRawButton(F310::kLeftBumper)) { iLeft->Set(1.0); iRight->Set(-1.0); } if(oiGamepad->GetRawButton(F310::kLeftTrigger)) { iLeft->Set(-1.0); iRight->Set(1.0); } iLeft->Set(0); iRight->Set(0); eLeft->Set(0); eRight->Set(0); HDrive(0.0); // float lyDrive = scaleyFunction(oiLeft->GetY(), 0, 3); // float ryDrive = scaleyFunction(oiRight->GetY(), 0, 3); // float xDrive = scaleyFunction(oiRight->GetX(), 0, 3); // dbDrive->TankDrive(lyDrive, ryDrive); // if (oiRight->GetRawButton(1) == true) // { // this->HDrive(xDrive); // } dbDrive->TankDrive(-oiLeft->GetY(), -oiRight->GetY()); if (oiRight->GetRawButton(1) == true) { this->HDrive(oiRight->GetX()); } if (manualOverride) { eLeft->Set(-oiGamepad->GetRawAxis(1)); eRight->Set(-oiGamepad->GetRawAxis(3)); } SmartDashboard::PutBoolean("ManualOverride:", manualOverride); } // end or while loop } // end of teleop void Disabled(void) { } void Test(void) { } // h drive function void HDrive(float speed) { dbMiddleLeft->Set(speed); dbMiddleRight->Set(speed); } // elevator pneumatic function void ePneumaticControl(int x) { switch(x) { case L_OPEN: this->epLeft->Set(DoubleSolenoid::kReverse); break; case L_CLOSE: this->epLeft->Set(DoubleSolenoid::kForward); break; case R_OPEN: this->epRight->Set(DoubleSolenoid::kReverse); break; case R_CLOSE: this->epRight->Set(DoubleSolenoid::kForward); break; case B_OPEN: this->epLeft->Set(DoubleSolenoid::kReverse); this->epRight->Set(DoubleSolenoid::kReverse); break; case B_CLOSE: this->epLeft->Set(DoubleSolenoid::kForward); this->epRight->Set(DoubleSolenoid::kForward); break; default: break; } } // intake pnematic function void iPneumaticControl(int x) { switch(x) { case L_OPEN: this->ipLeft->Set(DoubleSolenoid::kReverse); break; case L_CLOSE: this->ipLeft->Set(DoubleSolenoid::kForward); break; case R_OPEN: this->ipRight->Set(DoubleSolenoid::kReverse); break; case R_CLOSE: this->ipRight->Set(DoubleSolenoid::kForward); break; case B_OPEN: this->ipLeft->Set(DoubleSolenoid::kReverse); this->ipRight->Set(DoubleSolenoid::kReverse); break; case B_CLOSE: this->ipLeft->Set(DoubleSolenoid::kForward); this->ipRight->Set(DoubleSolenoid::kForward); break; default: break; } } // drive train debug function void dbDebug() { SmartDashboard::PutNumber("dbMiddle:", dbMidEncoder->GetDistance()); SmartDashboard::PutNumber("dbLeft:", dbLeftEncoder->GetDistance()); SmartDashboard::PutNumber("dbRight:", dbRightEncoder->GetDistance()); SmartDashboard::PutNumber("dbGyro:", dbGyro->GetAngle()); } // elevator debug function void eDebug() { // SmartDashboard::PutNumber("eLeft", eLeftEnc->GetDistance()); // SmartDashboard::PutNumber("eRight", eRightEnc->GetDistance()); // SmartDashboard::PutNumber("eLeft Pulses", eLeftEnc->Get()); // SmartDashboard::PutNumber("eLeft revs", eLeftEnc->Get() / OPTICAL_PPR); // float LRevs = eLeftEnc->Get() / OPTICAL_PPR; // SmartDashboard::PutNumber("eLeft Pulses per rev", EncoderMagic(LRevs)); // SmartDashboard::PutNumber("eRight pulses", eRightEnc->Get()); // SmartDashboard::PutNumber("eRight revs", eRightEnc->Get() / OPTICAL_PPR); // float RRevs = eRightEnc->Get() / OPTICAL_PPR; // SmartDashboard::PutNumber("eRight pulses per rev", EncoderMagic(RRevs)); } void Debug() { this->dbDebug(); this->eDebug(); } }; START_ROBOT_CLASS(Robot); <commit_msg>added "correct" solenoid pinouts<commit_after>#include "WPILib.h" #include "DeadSwipe.h" #include "UsefulMath.h" #include "F310.h" class Robot : public SampleRobot { // class wide declarations // drive train declarations - anything prefixed with db is a part of the drive train // motor declarations - motors are controlled by motor controllers. We use Talons Talon *dbFrontLeft; // pwm 6 Talon *dbRearLeft; // pwm 4 Talon *dbFrontRight; // pwm 7 Talon *dbRearRight; // pwm 9 RobotDrive *dbDrive; // easy tools ftw Talon *dbMiddleLeft; // pwm 5 Talon *dbMiddleRight; // pwm 8 // encoder declarations - encoders require 2 digital I/O pins and are used to measured how far a rotating object // has moved Encoder *dbLeftEncoder; // DIO 0 and 1 Encoder *dbRightEncoder; // DIO 2 and 3 Encoder *dbMidEncoder; // DIO 4 and 5 // gyro declaration - gyros allow us to measure how much an object has rotated along an axis // NOTE: gyros can(as of this writing) ONLY be used on AIN 0 and 1 Gyro *dbGyro; // AIN 0 // Elevator declarations Talon *eLeft; // pwm 0 Talon *eRight; // pwm 1 DoubleSolenoid *epLeft; // PCM ports 3 and 4 DoubleSolenoid *epRight; // PCM ports 2 and 5 DigitalInput *eLeftBottom; // DIO 6 DigitalInput *eLeftTop; // DIO 7 DigitalInput *eRightBottom; // DIO 8 DigitalInput *eRightTop; // DIO 9 // Encoder *eLeftEnc; // DIO 6 and 7 // Encoder *eRightEnc; // DIO 8 and 9 // intake declarations Talon *iLeft; // pwm 2 Talon *iRight; // pwm 3 DoubleSolenoid *ipLeft; // PCM ports 1 and 6 DoubleSolenoid *ipRight; // PCM ports 0 and 7 // operator interface declarations - prefixed by oi Joystick *oiLeft; Joystick *oiRight; F310 *oiGamepad; SendableChooser *autoChooser; // this is how we'll select different int mode1 = 0; int mode2 = 1; public: Robot() { oiLeft = new Joystick(0); oiRight = new Joystick(1); oiGamepad = new F310(2); autoChooser = new SendableChooser(); autoChooser->AddDefault("Do Nuffin", (int *) mode1); autoChooser->AddObject("Move you goddamm robot", (int *) mode2); dbFrontLeft = new Talon(6); dbRearLeft = new Talon(4); dbFrontRight = new Talon(7); dbRearRight = new Talon(9); dbDrive = new RobotDrive(dbFrontLeft, dbRearLeft, dbFrontRight, dbRearRight); dbDrive->SetSafetyEnabled(true); dbDrive->SetExpiration(0.1); dbDrive->SetSensitivity(0.5); dbDrive->SetMaxOutput(1.0); dbMiddleLeft = new Talon(5); dbMiddleRight = new Talon(8); dbLeftEncoder = new Encoder(0, 1, false, Encoder::k4X); dbLeftEncoder->SetDistancePerPulse(DRIVE_DISTANCE_PER_PULSE); dbRightEncoder = new Encoder(2, 3, false, Encoder::k4X); dbRightEncoder->SetDistancePerPulse(DRIVE_DISTANCE_PER_PULSE); dbMidEncoder = new Encoder(4, 5, false, Encoder::k4X); dbMidEncoder->SetDistancePerPulse(MIDDLE_DISTANCE_PER_PULSE); dbGyro = new Gyro(0); dbGyro->SetSensitivity(0.007); epLeft = new DoubleSolenoid(0, 3, 4); epRight = new DoubleSolenoid(0, 2, 5); eLeft = new Talon(2); eRight = new Talon(3); // eLeftEnc = new Encoder(6, 7, false, Encoder::k4X); // eLeftEnc->SetDistancePerPulse(OPTICAL_PPR); // // eRightEnc = new Encoder(8, 9, true, Encoder::k4X); // eRightEnc->SetDistancePerPulse(OPTICAL_PPR); eLeftBottom = new DigitalInput(6); eLeftTop = new DigitalInput(7); eRightBottom = new DigitalInput(8); eRightTop = new DigitalInput(9); ipLeft = new DoubleSolenoid(0, 1, 6); ipRight = new DoubleSolenoid(0, 0, 7); iLeft = new Talon(0); iRight= new Talon(1); } // end of constructor void Autonomous(void) { int aSelectedMode = (int) autoChooser->GetSelected(); while(IsEnabled() && IsAutonomous()) { this->Debug(); switch (aSelectedMode) { case 1: break; case 2: break; default: break; } this->Debug(); } // end of while loop } // end of auton void OperatorControl(void) { bool manualOverride = true; while(IsOperatorControl() && IsEnabled()) { this->Debug(); if(oiGamepad->GetButton(F310::kXButton) == true) { this->ePneumaticControl(B_CLOSE); } if(oiGamepad->GetButton(F310::kBButton) == true) { this->ePneumaticControl(B_OPEN); } if(oiGamepad->GetButton(F310::kXButton) && oiGamepad->GetButton(F310::kBButton)) { // do nothing. } if (oiGamepad->GetButton(F310::kStartButton)) { manualOverride = ~manualOverride; } if(oiGamepad->GetRawButton(F310::kAButton)) { eLeft->Set(0.0); eRight->Set(0.0); } if(oiGamepad->GetRawButton(F310::kRightBumper)) { eLeft->Set(1.0); eRight->Set(1.0); } if(oiGamepad->GetRawButton(F310::kRightTrigger)) { eLeft->Set(-1.0); eRight->Set(-1.0); } // if(oiGamepad->GetButton(F310::kRightTrigger) == true) // { // if((eLeftTop->Get() == 0) && (eRightTop->Get() == 0)) // { // eLeft->Set(1.0); // eRight->Set(1.0); } else // { // eLeft->Set(0.0); // eRight->Set(0.0); // } // } // // if(oiGamepad->GetButton(F310::kLeftTrigger) == true) // { // if((eLeftBottom->Get() == 0) && (eRightBottom->Get() == 0)) // { // eLeft->Set(-1.0); // eRight->Set(-1.0); // } // else // { // eLeft->Set(0.0); // eRight->Set(0.0); // } // } if(oiGamepad->GetRawButton(F310::kLeftBumper)) { iLeft->Set(1.0); iRight->Set(-1.0); } if(oiGamepad->GetRawButton(F310::kLeftTrigger)) { iLeft->Set(-1.0); iRight->Set(1.0); } iLeft->Set(0); iRight->Set(0); eLeft->Set(0); eRight->Set(0); HDrive(0.0); // float lyDrive = scaleyFunction(oiLeft->GetY(), 0, 3); // float ryDrive = scaleyFunction(oiRight->GetY(), 0, 3); // float xDrive = scaleyFunction(oiRight->GetX(), 0, 3); // dbDrive->TankDrive(lyDrive, ryDrive); // if (oiRight->GetRawButton(1) == true) // { // this->HDrive(xDrive); // } dbDrive->TankDrive(-oiLeft->GetY(), -oiRight->GetY()); if (oiRight->GetRawButton(1) == true) { this->HDrive(oiRight->GetX()); } if (manualOverride) { eLeft->Set(-oiGamepad->GetRawAxis(1)); eRight->Set(-oiGamepad->GetRawAxis(3)); } SmartDashboard::PutBoolean("ManualOverride:", manualOverride); } // end or while loop } // end of teleop void Disabled(void) { } void Test(void) { } // h drive function void HDrive(float speed) { dbMiddleLeft->Set(speed); dbMiddleRight->Set(speed); } // elevator pneumatic function void ePneumaticControl(int x) { switch(x) { case L_OPEN: this->epLeft->Set(DoubleSolenoid::kReverse); break; case L_CLOSE: this->epLeft->Set(DoubleSolenoid::kForward); break; case R_OPEN: this->epRight->Set(DoubleSolenoid::kReverse); break; case R_CLOSE: this->epRight->Set(DoubleSolenoid::kForward); break; case B_OPEN: this->epLeft->Set(DoubleSolenoid::kReverse); this->epRight->Set(DoubleSolenoid::kReverse); break; case B_CLOSE: this->epLeft->Set(DoubleSolenoid::kForward); this->epRight->Set(DoubleSolenoid::kForward); break; default: break; } } // intake pnematic function void iPneumaticControl(int x) { switch(x) { case L_OPEN: this->ipLeft->Set(DoubleSolenoid::kReverse); break; case L_CLOSE: this->ipLeft->Set(DoubleSolenoid::kForward); break; case R_OPEN: this->ipRight->Set(DoubleSolenoid::kReverse); break; case R_CLOSE: this->ipRight->Set(DoubleSolenoid::kForward); break; case B_OPEN: this->ipLeft->Set(DoubleSolenoid::kReverse); this->ipRight->Set(DoubleSolenoid::kReverse); break; case B_CLOSE: this->ipLeft->Set(DoubleSolenoid::kForward); this->ipRight->Set(DoubleSolenoid::kForward); break; default: break; } } // drive train debug function void dbDebug() { SmartDashboard::PutNumber("dbMiddle:", dbMidEncoder->GetDistance()); SmartDashboard::PutNumber("dbLeft:", dbLeftEncoder->GetDistance()); SmartDashboard::PutNumber("dbRight:", dbRightEncoder->GetDistance()); SmartDashboard::PutNumber("dbGyro:", dbGyro->GetAngle()); } // elevator debug function void eDebug() { // SmartDashboard::PutNumber("eLeft", eLeftEnc->GetDistance()); // SmartDashboard::PutNumber("eRight", eRightEnc->GetDistance()); // SmartDashboard::PutNumber("eLeft Pulses", eLeftEnc->Get()); // SmartDashboard::PutNumber("eLeft revs", eLeftEnc->Get() / OPTICAL_PPR); // float LRevs = eLeftEnc->Get() / OPTICAL_PPR; // SmartDashboard::PutNumber("eLeft Pulses per rev", EncoderMagic(LRevs)); // SmartDashboard::PutNumber("eRight pulses", eRightEnc->Get()); // SmartDashboard::PutNumber("eRight revs", eRightEnc->Get() / OPTICAL_PPR); // float RRevs = eRightEnc->Get() / OPTICAL_PPR; // SmartDashboard::PutNumber("eRight pulses per rev", EncoderMagic(RRevs)); } void Debug() { this->dbDebug(); this->eDebug(); } }; START_ROBOT_CLASS(Robot); <|endoftext|>
<commit_before>#include "Shell.hpp" #include <iostream> #include <sstream> #include "FileSystem.hpp" using namespace std; const int MAXCOMMANDS = 8; const int NUMAVAILABLECOMMANDS = 15; string availableCommands[NUMAVAILABLECOMMANDS] = { "quit", "format", "ls", "create", "cat", "save", "load", "rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help" }; Shell::Shell(const string &user) { this->user = user; currentDir = "/"; } bool Shell::getCommand() { string userCommand, commandArr[MAXCOMMANDS]; cout << user << ":" << currentDir << "$ "; getline(cin, userCommand); int nrOfCommands = parseCommandString(userCommand, commandArr); if (nrOfCommands > 0) { int cIndex = findCommand(commandArr[0]); switch (cIndex) { case 0: // quit cout << "Exiting" << endl; return false; break; case 1: // format fileSystem.format(); break; case 2: // ls cout << "Listing directory" << endl; if (nrOfCommands < 2) fileSystem.ls(absolutePath(currentDir)); else fileSystem.ls(absolutePath(commandArr[1])); break; case 3: // create /// @todo create break; case 4: // cat /// @todo cat break; case 5: // save fileSystem.save(absolutePath(commandArr[1])); break; case 6: // load fileSystem.load(absolutePath(commandArr[1])); break; case 7: // rm /// @todo rm break; case 8: // copy /// @todo copy break; case 9: // append /// @todo append break; case 10: // rename /// @todo rename break; case 11: // mkdir fileSystem.mkdir(absolutePath(commandArr[1])); break; case 12: // cd if (fileSystem.directoryExists(absolutePath(commandArr[1]))) { currentDir = "/" + absolutePath(commandArr[1]); if (currentDir[currentDir.length() - 1] != '/') currentDir += "/"; } break; case 13: // pwd cout << currentDir << endl; break; case 14: // help cout << help() << endl; break; default: cout << "Unknown command: " << commandArr[0] << endl; } } return true; } int Shell::parseCommandString(const string &userCommand, string strArr[]) { stringstream ssin(userCommand); int counter = 0; while (ssin.good() && counter < MAXCOMMANDS) { ssin >> strArr[counter]; counter++; } if (strArr[0] == "") { counter = 0; } return counter; } int Shell::findCommand(string &command) { int index = -1; for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) { if (command == availableCommands[i]) { index = i; } } return index; } std::string Shell::absolutePath(const std::string &path) { /// Fix relative path string temp = path; if (path.length() == 0 || temp[0] != '/') temp = currentDir + temp; temp = temp.substr(1); /// @todo Replace ./ /// @todo Replace ../ return temp; } string Shell::help() { string helpStr; helpStr += "OSD Disk Tool .oO Help Screen Oo.\n"; helpStr += "-----------------------------------------------------------------------------------\n"; helpStr += "* quit: Quit OSD Disk Tool\n"; helpStr += "* format; Formats disk\n"; helpStr += "* ls <path>: Lists contents of <path>.\n"; helpStr += "* create <path>: Creates a file and stores contents in <path>\n"; helpStr += "* cat <path>: Dumps contents of <file>.\n"; helpStr += "* save <real-file>: Saves disk to <real-file>\n"; helpStr += "* read <real-file>: Reads <real-file> onto disk\n"; helpStr += "* rm <file>: Removes <file>\n"; helpStr += "* copy <source> <destination>: Copy <source> to <destination>\n"; helpStr += "* append <source> <destination>: Appends contents of <source> to <destination>\n"; helpStr += "* rename <old-file> <new-file>: Renames <old-file> to <new-file>\n"; helpStr += "* mkdir <directory>: Creates a new directory called <directory>\n"; helpStr += "* cd <directory>: Changes current working directory to <directory>\n"; helpStr += "* pwd: Get current working directory\n"; helpStr += "* help: Prints this help screen\n"; return helpStr; } <commit_msg>cd now complains if directory does not exist<commit_after>#include "Shell.hpp" #include <iostream> #include <sstream> #include "FileSystem.hpp" using namespace std; const int MAXCOMMANDS = 8; const int NUMAVAILABLECOMMANDS = 15; string availableCommands[NUMAVAILABLECOMMANDS] = { "quit", "format", "ls", "create", "cat", "save", "load", "rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help" }; Shell::Shell(const string &user) { this->user = user; currentDir = "/"; } bool Shell::getCommand() { string userCommand, commandArr[MAXCOMMANDS]; cout << user << ":" << currentDir << "$ "; getline(cin, userCommand); int nrOfCommands = parseCommandString(userCommand, commandArr); if (nrOfCommands > 0) { int cIndex = findCommand(commandArr[0]); switch (cIndex) { case 0: // quit cout << "Exiting" << endl; return false; break; case 1: // format fileSystem.format(); break; case 2: // ls cout << "Listing directory" << endl; if (nrOfCommands < 2) fileSystem.ls(absolutePath(currentDir)); else fileSystem.ls(absolutePath(commandArr[1])); break; case 3: // create /// @todo create break; case 4: // cat /// @todo cat break; case 5: // save fileSystem.save(absolutePath(commandArr[1])); break; case 6: // load fileSystem.load(absolutePath(commandArr[1])); break; case 7: // rm /// @todo rm break; case 8: // copy /// @todo copy break; case 9: // append /// @todo append break; case 10: // rename /// @todo rename break; case 11: // mkdir fileSystem.mkdir(absolutePath(commandArr[1])); break; case 12: // cd if (fileSystem.directoryExists(absolutePath(commandArr[1]))) { currentDir = "/" + absolutePath(commandArr[1]); if (currentDir[currentDir.length() - 1] != '/') currentDir += "/"; } else { cout << "Directory does not exist." << endl; } break; case 13: // pwd cout << currentDir << endl; break; case 14: // help cout << help() << endl; break; default: cout << "Unknown command: " << commandArr[0] << endl; } } return true; } int Shell::parseCommandString(const string &userCommand, string strArr[]) { stringstream ssin(userCommand); int counter = 0; while (ssin.good() && counter < MAXCOMMANDS) { ssin >> strArr[counter]; counter++; } if (strArr[0] == "") { counter = 0; } return counter; } int Shell::findCommand(string &command) { int index = -1; for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) { if (command == availableCommands[i]) { index = i; } } return index; } std::string Shell::absolutePath(const std::string &path) { /// Fix relative path string temp = path; if (path.length() == 0 || temp[0] != '/') temp = currentDir + temp; temp = temp.substr(1); /// @todo Replace ./ /// @todo Replace ../ return temp; } string Shell::help() { string helpStr; helpStr += "OSD Disk Tool .oO Help Screen Oo.\n"; helpStr += "-----------------------------------------------------------------------------------\n"; helpStr += "* quit: Quit OSD Disk Tool\n"; helpStr += "* format; Formats disk\n"; helpStr += "* ls <path>: Lists contents of <path>.\n"; helpStr += "* create <path>: Creates a file and stores contents in <path>\n"; helpStr += "* cat <path>: Dumps contents of <file>.\n"; helpStr += "* save <real-file>: Saves disk to <real-file>\n"; helpStr += "* read <real-file>: Reads <real-file> onto disk\n"; helpStr += "* rm <file>: Removes <file>\n"; helpStr += "* copy <source> <destination>: Copy <source> to <destination>\n"; helpStr += "* append <source> <destination>: Appends contents of <source> to <destination>\n"; helpStr += "* rename <old-file> <new-file>: Renames <old-file> to <new-file>\n"; helpStr += "* mkdir <directory>: Creates a new directory called <directory>\n"; helpStr += "* cd <directory>: Changes current working directory to <directory>\n"; helpStr += "* pwd: Get current working directory\n"; helpStr += "* help: Prints this help screen\n"; return helpStr; } <|endoftext|>
<commit_before>#include "Debug.h" #include "Theme.h" #include "Color.h" #include <cstdio> #include <cstring> #include "SDL.h" #include "SDL_rwops.h" Theme::Theme() { mFontWidth = 8; mFontHeight = 8; mWidth = 480; mHeight = 360; mBasePath = "assets/"; mBackgroundPath = mBasePath+"gui.png"; mFontPath = mBasePath+"font.png"; } bool Theme::load(const std::string& path) { mPath = path; if (!loadDefinition(path)) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Could not load theme", ("Could not load "+path+". Perhaps you need to set the working directory?").c_str(), NULL); return false; } return true; } const std::string& Theme::getName() const { return mName; } const std::string& Theme::getPath() const { return mPath; } const std::string& Theme::getFontPath() const { return mFontPath; } const std::string& Theme::getBackgroundPath() const { return mBackgroundPath; } int Theme::getFontWidth() const { return mFontWidth; } int Theme::getFontHeight() const { return mFontHeight; } int Theme::getWidth() const { return mWidth; } int Theme::getHeight() const { return mHeight; } const Theme::Element& Theme::getElement(int index) const { return mElement[index]; } int Theme::getElementCount() const { return mElement.size(); } static char *rwgets(char *buf, int count, SDL_RWops *rw) { int i; buf[count - 1] = '\0'; for (i = 0; i < count - 1; i++) { if (SDL_RWread(rw, buf + i, 1, 1) != 1) { if (i == 0) { return NULL; } break; } if (buf[i] == '\n') { break; } } buf[i] = '\0'; return buf; } bool Theme::loadDefinition(const std::string& path) { SDL_RWops *rw = SDL_RWFromFile(path.c_str(), "r"); if (!rw) return false; int lineCounter = 0; static const char *colorNames[] = { "CurrentRow", "BlockMarker", "EditCursor", "NonEditCursor", "RowCounter", "SelectedRow", "ModalBackground", "ModalBorder", "ModalTitleBackground", "ModalTitleText", "NormalText", "ScrollBar", "PlayHead", "TextCursor", "TextBackground", "TextFocus", "Oscilloscope", NULL, }; static const char *elementNames[] = { "PatternEditor", "SequenceEditor", "MacroEditor", "Oscilloscope", "SongName", "MacroName", "MacroNumber", "SequencePosition", "SequenceLength", "PatternLength", "OctaveNumber", "TouchRegion", NULL }; while (true) { ++lineCounter; char line[500]; if (rwgets(line, sizeof(line), rw) == NULL) break; // Check if comment if (line[0] == '#') continue; char elementName[20], path[100], strParameters[10][50] = {0}; int parameters[10] = {0}; if (sscanf(line, "%19s \"%99[^\"]\" %d %d", elementName, path, &parameters[0], &parameters[1]) >= 4 && strcmp("Font", elementName) == 0) { mFontPath = mBasePath + path; mFontWidth = parameters[0]; mFontHeight = parameters[1]; } else if (sscanf(line, "%19s \"%99[^\"]\" %d %d %d", elementName, path, &parameters[0], &parameters[1], &parameters[2]) >= 4 && (strcmp("GUI", elementName) == 0 || strcmp("Color", elementName) == 0)) { if (strcmp(elementName, "Color") == 0) { ColorType colorType = NumColors; for (int index = 0 ; colorNames[index] ; ++index) { if (strcmp(colorNames[index], path) == 0) { colorType = static_cast<Theme::ColorType>(index); break; } } if (colorType < NumColors) { mColors[colorType] = Color(parameters[0], parameters[1], parameters[2]); } else { debug("Unknown color %s", elementName); } } else { mBackgroundPath = mBasePath + path; mWidth = parameters[0]; mHeight = parameters[1]; } } else if ((sscanf(line, "%19s %d %d %d %d \"%50[^\"]\" \"%50[^\"]\"", elementName, &parameters[0], &parameters[1], &parameters[2], &parameters[3], strParameters[0], strParameters[1]) >= 5 && strcmp("TouchRegion", elementName) == 0) ||sscanf(line, "%19s %d %d %d %d %d %d", elementName, &parameters[0], &parameters[1], &parameters[2], &parameters[3], &parameters[4], &parameters[5]) >= 5) { Element element; element.type = Theme::Unknown; for (int index = 0 ; elementNames[index] ; ++index) { if (strcmp(elementNames[index], elementName) == 0) { element.type = static_cast<Theme::ElementType>(index); break; } } if (element.type != Theme::Unknown) { memcpy(element.parameters, parameters, sizeof(element.parameters)); memcpy(element.strParameters, strParameters, sizeof(element.strParameters)); mElement.push_back(element); } else { debug("Unknown element %s on line %d", elementName, lineCounter); } } else { debug("Weirdness on line %d", lineCounter); } } SDL_RWclose(rw); return true; } const Color& Theme::getColor(ColorType type) const { return mColors[type]; } <commit_msg>Fixed unknown color error message<commit_after>#include "Debug.h" #include "Theme.h" #include "Color.h" #include <cstdio> #include <cstring> #include "SDL.h" #include "SDL_rwops.h" Theme::Theme() { mFontWidth = 8; mFontHeight = 8; mWidth = 480; mHeight = 360; mBasePath = "assets/"; mBackgroundPath = mBasePath+"gui.png"; mFontPath = mBasePath+"font.png"; } bool Theme::load(const std::string& path) { mPath = path; if (!loadDefinition(path)) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Could not load theme", ("Could not load "+path+". Perhaps you need to set the working directory?").c_str(), NULL); return false; } return true; } const std::string& Theme::getName() const { return mName; } const std::string& Theme::getPath() const { return mPath; } const std::string& Theme::getFontPath() const { return mFontPath; } const std::string& Theme::getBackgroundPath() const { return mBackgroundPath; } int Theme::getFontWidth() const { return mFontWidth; } int Theme::getFontHeight() const { return mFontHeight; } int Theme::getWidth() const { return mWidth; } int Theme::getHeight() const { return mHeight; } const Theme::Element& Theme::getElement(int index) const { return mElement[index]; } int Theme::getElementCount() const { return mElement.size(); } static char *rwgets(char *buf, int count, SDL_RWops *rw) { int i; buf[count - 1] = '\0'; for (i = 0; i < count - 1; i++) { if (SDL_RWread(rw, buf + i, 1, 1) != 1) { if (i == 0) { return NULL; } break; } if (buf[i] == '\n') { break; } } buf[i] = '\0'; return buf; } bool Theme::loadDefinition(const std::string& path) { SDL_RWops *rw = SDL_RWFromFile(path.c_str(), "r"); if (!rw) return false; int lineCounter = 0; static const char *colorNames[] = { "CurrentRow", "BlockMarker", "EditCursor", "NonEditCursor", "RowCounter", "SelectedRow", "ModalBackground", "ModalBorder", "ModalTitleBackground", "ModalTitleText", "NormalText", "ScrollBar", "PlayHead", "TextCursor", "TextBackground", "TextFocus", "Oscilloscope", NULL, }; static const char *elementNames[] = { "PatternEditor", "SequenceEditor", "MacroEditor", "Oscilloscope", "SongName", "MacroName", "MacroNumber", "SequencePosition", "SequenceLength", "PatternLength", "OctaveNumber", "TouchRegion", NULL }; while (true) { ++lineCounter; char line[500]; if (rwgets(line, sizeof(line), rw) == NULL) break; // Check if comment if (line[0] == '#') continue; char elementName[20], path[100], strParameters[10][50] = {0}; int parameters[10] = {0}; if (sscanf(line, "%19s \"%99[^\"]\" %d %d", elementName, path, &parameters[0], &parameters[1]) >= 4 && strcmp("Font", elementName) == 0) { mFontPath = mBasePath + path; mFontWidth = parameters[0]; mFontHeight = parameters[1]; } else if (sscanf(line, "%19s \"%99[^\"]\" %d %d %d", elementName, path, &parameters[0], &parameters[1], &parameters[2]) >= 4 && (strcmp("GUI", elementName) == 0 || strcmp("Color", elementName) == 0)) { if (strcmp(elementName, "Color") == 0) { ColorType colorType = NumColors; for (int index = 0 ; colorNames[index] ; ++index) { if (strcmp(colorNames[index], path) == 0) { colorType = static_cast<Theme::ColorType>(index); break; } } if (colorType < NumColors) { mColors[colorType] = Color(parameters[0], parameters[1], parameters[2]); } else { debug("Unknown color %s", path); } } else { mBackgroundPath = mBasePath + path; mWidth = parameters[0]; mHeight = parameters[1]; } } else if ((sscanf(line, "%19s %d %d %d %d \"%50[^\"]\" \"%50[^\"]\"", elementName, &parameters[0], &parameters[1], &parameters[2], &parameters[3], strParameters[0], strParameters[1]) >= 5 && strcmp("TouchRegion", elementName) == 0) ||sscanf(line, "%19s %d %d %d %d %d %d", elementName, &parameters[0], &parameters[1], &parameters[2], &parameters[3], &parameters[4], &parameters[5]) >= 5) { Element element; element.type = Theme::Unknown; for (int index = 0 ; elementNames[index] ; ++index) { if (strcmp(elementNames[index], elementName) == 0) { element.type = static_cast<Theme::ElementType>(index); break; } } if (element.type != Theme::Unknown) { memcpy(element.parameters, parameters, sizeof(element.parameters)); memcpy(element.strParameters, strParameters, sizeof(element.strParameters)); mElement.push_back(element); } else { debug("Unknown element %s on line %d", elementName, lineCounter); } } else { debug("Weirdness on line %d", lineCounter); } } SDL_RWclose(rw); return true; } const Color& Theme::getColor(ColorType type) const { return mColors[type]; } <|endoftext|>
<commit_before>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; // cout << "mRetina Ratio: " << app::toPixels( 1.0 ) << endl; // cout << "mWindowWidth : " << mWindowWidth << " mWindowHeight: " << mWindowHeight << endl; // cout << "mImageWidth : " << mImageWidth << " mImageHeight: " << mImageHeight << endl; // cout << "mTileWidth : " << mTileWidth << " mTileHeight: " << mTileHeight << endl; // cout << "mNumTilesX : " << mNumTilesX << " mNumTilesY: " << mNumTilesY << endl; } bool Tiler::nextTile() { if( mCurrentTile >= mNumTilesX * mNumTilesY ) { // suck the pixels out of the final tile mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , mWindowRef->getSize() ), mWindowRef->getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { // first tile of this frame mCurrentTile = 0; mSurface = Surface( mImageWidth, mImageHeight, false ); } else { // suck the pixels out of the previous tile mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , mWindowRef->getSize() ), mWindowRef->getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; // cout << "TILE NUMBER: " << mCurrentTile << endl; // cout << "mCurrentArea.x1: " << mCurrentArea.x1 << " mCurrentArea.y1: " << mCurrentArea.y1 << endl; // cout << "mCurrentArea.x2: " << mCurrentArea.x2 << " mCurrentArea.y2: " << mCurrentArea.y2 << endl; // cout << "AREA: " << mCurrentArea.getWidth() << " " << mCurrentArea.getHeight() << endl; // cout << endl; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } ci::Surface Tiler::getSurface() { while ( nextTile() ) { } return mSurface; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); // cout << endl; // cout << "LEFT: " << left << endl; // cout << "RIGHT: " << right << endl; // cout << "TOP: " << top << endl; // cout << "BOTTOM: " << bottom << endl; // cout << "NEAR: " << nearPlane << endl; // cout << "FAR: " << farPlane << endl; // cout << endl; if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { float sx = (float) mCurrentArea.x1 / (float)mImageWidth; float sy = (float) mCurrentArea.y1 / (float)mImageHeight; float ex = (float) mCurrentArea.x2 / (float)mImageWidth; float ey = (float) mCurrentArea.y2 / (float)mImageHeight; vec2 ul = vec2(sx, sy); vec2 ur = vec2(ex, sy); vec2 lr = vec2(ex, ey); vec2 ll = vec2(sx, ey); if( mDrawBgFn ) { mDrawBgFn( ul, ur, lr, ll ); } CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ); gl::pushProjectionMatrix(); float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::pushProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } }<commit_msg>cleaned up Tiler<commit_after>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; cout << "mRetina Ratio: " << app::toPixels( 1.0 ) << endl; cout << "mWindowWidth : " << mWindowWidth << " mWindowHeight: " << mWindowHeight << endl; cout << "mImageWidth : " << mImageWidth << " mImageHeight: " << mImageHeight << endl; cout << "mTileWidth : " << mTileWidth << " mTileHeight: " << mTileHeight << endl; cout << "mNumTilesX : " << mNumTilesX << " mNumTilesY: " << mNumTilesY << endl; } bool Tiler::nextTile() { if( mCurrentTile >= mNumTilesX * mNumTilesY ) { // suck the pixels out of the final tile // mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , mWindowRef->getSize() ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { // first tile of this frame mCurrentTile = 0; mSurface = Surface( mImageWidth, mImageHeight, false ); } else { // suck the pixels out of the previous tile mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); // mSurface.copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , mWindowRef->getSize() ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; // cout << "TILE NUMBER: " << mCurrentTile << endl; // cout << "mCurrentArea.x1: " << mCurrentArea.x1 << " mCurrentArea.y1: " << mCurrentArea.y1 << endl; // cout << "mCurrentArea.x2: " << mCurrentArea.x2 << " mCurrentArea.y2: " << mCurrentArea.y2 << endl; // cout << "AREA: " << mCurrentArea.getWidth() << " " << mCurrentArea.getHeight() << endl; // cout << endl; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } ci::Surface Tiler::getSurface() { while ( nextTile() ) { } return mSurface; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); // cout << endl; // cout << "LEFT: " << left << endl; // cout << "RIGHT: " << right << endl; // cout << "TOP: " << top << endl; // cout << "BOTTOM: " << bottom << endl; // cout << "NEAR: " << nearPlane << endl; // cout << "FAR: " << farPlane << endl; // cout << endl; if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { float sx = (float) mCurrentArea.x1 / (float)mImageWidth; float sy = (float) mCurrentArea.y1 / (float)mImageHeight; float ex = (float) mCurrentArea.x2 / (float)mImageWidth; float ey = (float) mCurrentArea.y2 / (float)mImageHeight; vec2 ul = vec2(sx, sy); vec2 ur = vec2(ex, sy); vec2 lr = vec2(ex, ey); vec2 ll = vec2(sx, ey); float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); if( mDrawBgFn ) { gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); mDrawBgFn( ul, ur, lr, ll ); gl::popViewport(); gl::popMatrices(); } CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); gl::pushProjectionMatrix(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::popProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } }<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <sys/stat.h> #include "Network.h" // Returns the path to the default weights directory std::string getWeightsDir(char* argvZero) { std::string executablePath = realpath(argvZero, NULL); size_t index = executablePath.rfind('/', executablePath.rfind('/') - 1); return executablePath.substr(0, index) + "/files/weights"; } // Print options and usage void printHelp() { std::cout << " Usage: trainer <training_file> [options]\n\n" " Options:\n" " -i, --input-nodes\t Set number of input nodes\n" " -h, --hidden-nodes\t Set number of hidden nodes\n" " -o, --output-nodes\t Set number of output nodes\n" " -l, --hidden-layers\t Set number of hidden layers\n" " --help\t\t Print this message\n\n" " Example:\n" " ./bin/trainer training_set.tra -h 5 -l 1\n\n"; } // Validate option is an integer void isValInt(char* opt, char* val) { std::string valStr = val; try { std::stoi(valStr); } catch (std::invalid_argument ia) { std::cerr << " ERROR: Invalid value '" << val << "' for option '" << opt << "' (Value is not an Int)\n"; } } // Print errors and return exit code 1 void error(int errorCode, std::string info = "") { switch (errorCode) { case ERRFILE : std::cerr << " ERROR: Training file " << info << " is " "unreadable or does not exist\n"; case ERRDIR : std::cerr << " ERROR: Train class does not currently support " "directories for training file argument\n"; case ERRNODE : std::cerr << " ERROR: Must have at least one " << info << " node.\n"; default: std::cerr << " ERROR: Unknown error.\n"; } exit(1); } // Check parameters void checkParams(std::vector< std::string > options) { if (std::stoi(options[0]) <= 0) { error(ERRNODE, "input"); } if (std::stoi(options[2]) <= 0) { error(ERRNODE, "output"); } if (std::stoi(options[1]) > 0 && std::stoi(options[3]) <= 0) { std::cerr << " ERROR: Hidden layers are set to one or greater" " but hidden nodes are set to zero.\n"; exit(1); } if (std::stoi(options[1]) <= 0 && std::stoi(options[3]) > 0) { std::cerr << " ERROR: Hidden nodes are set to one or greater" " but hidden layers are set to zero.\n"; exit(1); } // TODO: Confirm number of inputs matches (first line - 1) of .tra file // Get number of output nodes if unspecified } // Parse options std::vector<std::string> parseOptions(int argc, char* argv[]) { std::string trainingFile = "NULL"; std::string inputNodes = "0"; std::string hiddenNodes = "0"; std::string outputNodes = "0"; std::string hiddenLayers = "0"; std::vector<std::string> options; options.push_back(inputNodes); options.push_back(hiddenNodes); options.push_back(outputNodes); options.push_back(hiddenLayers); options.push_back(trainingFile); for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg == "--help") { printHelp(); exit(0); } else if (arg == "-i" || arg == "--input-nodes") { isValInt(argv[i], argv[i+1]); options[0] = argv[i+1]; i++; } else if (arg == "-h" || arg == "--hidden-nodes") { isValInt(argv[i], argv[i+1]); options[1] = argv[i+1]; i++; } else if (arg == "-o" || arg == "--output-nodes") { isValInt(argv[i], argv[i+1]); options[2] = argv[i+1]; i++; } else if (arg == "-l" || arg == "--hidden-layers") { isValInt(argv[i], argv[i+1]); options[3] = argv[i+1]; i++; } else if (trainingFile == "NULL") { trainingFile = argv[i]; struct stat s; if (stat(argv[i], &s) == 0) { if (s.st_mode & S_IFDIR) { std::ifstream tFile(trainingFile); if (tFile.good()) { options[4] = argv[i]; } exit(1); } else if (s.st_mode & S_IFREG) { // TODO: Support directories as training file argument error(ERRDIR); } else { error(ERRFILE, trainingFile); } } else { error(ERRFILE, trainingFile); } } else { std::cerr << " ERROR: Invalid option \"" << argv[i] << "\"\n\n"; printHelp(); exit(1); } } if (trainingFile == "NULL") { std::cerr << " ERROR: Training file was not provided.\n\n"; printHelp(); exit(1); } checkParams(options); return options; } // Main method int main(int argc, char* argv[]) { std::vector< std::string > options = parseOptions(argc, argv); // Initialize network Network myNeuralNet = Network(std::stoi(options[0]), std::stoi(options[1]), std::stoi(options[2]), std::stoi(options[3])); // Variables int numInputs = std::stoi(options[0]); int numOutputs = std::stoi(options[2]); std::ifstream tFile(options[4]); std::string val; float totalError = 1.0; /* // Iterate through training file while (!tFile.eof()) { std::vector<float> inputVec; std::vector<float> outputVec(numOutputs, 0.01); // Set input and output vectors for (int i = 0; i < numInputs; i++) { std::getline(tFile, val, ','); inputVec.push_back(std::stof(val)); } std::getline(tFile, val, ','); outputVec[std::stoi(val)] = 0.99; totalError = myNeuralNet.train(inputVec, outputVec); } myNeuralNet.writeWeightFile(getWeightsDir(argv[0])); */ return 0; } <commit_msg>fixing bug mixing up files and dirs<commit_after>#include <iostream> #include <vector> #include <sys/stat.h> #include "Network.h" // Returns the path to the default weights directory std::string getWeightsDir(char* argvZero) { std::string executablePath = realpath(argvZero, NULL); size_t index = executablePath.rfind('/', executablePath.rfind('/') - 1); return executablePath.substr(0, index) + "/files/weights"; } // Print options and usage void printHelp() { std::cout << " Usage: trainer <training_file> [options]\n\n" " Options:\n" " -i, --input-nodes\t Set number of input nodes\n" " -h, --hidden-nodes\t Set number of hidden nodes\n" " -o, --output-nodes\t Set number of output nodes\n" " -l, --hidden-layers\t Set number of hidden layers\n" " --help\t\t Print this message\n\n" " Example:\n" " ./bin/trainer training_set.tra -h 5 -l 1\n\n"; } // Validate option is an integer void isValInt(char* opt, char* val) { std::string valStr = val; try { std::stoi(valStr); } catch (std::invalid_argument ia) { std::cerr << " ERROR: Invalid value '" << val << "' for option '" << opt << "' (Value is not an Int)\n"; } } // Print errors and return exit code 1 void error(int errorCode, std::string info = "") { switch (errorCode) { case ERRFILE : std::cerr << " ERROR: Training file " << info << " is " "unreadable or does not exist\n"; break; case ERRDIR : std::cerr << " ERROR: Train class does not currently support " "directories for training file argument\n"; break; case ERRNODE : std::cerr << " ERROR: Must have at least one " << info << " node.\n"; break; default: std::cerr << " ERROR: Unknown error.\n"; break; } exit(1); } // Check parameters void checkParams(std::vector< std::string > options) { if (std::stoi(options[0]) <= 0) { error(ERRNODE, "input"); } if (std::stoi(options[2]) <= 0) { error(ERRNODE, "output"); } if (std::stoi(options[1]) > 0 && std::stoi(options[3]) <= 0) { std::cerr << " ERROR: Hidden layers are set to one or greater" " but hidden nodes are set to zero.\n"; exit(1); } if (std::stoi(options[1]) <= 0 && std::stoi(options[3]) > 0) { std::cerr << " ERROR: Hidden nodes are set to one or greater" " but hidden layers are set to zero.\n"; exit(1); } // TODO: Confirm number of inputs matches (first line - 1) of .tra file // Get number of output nodes if unspecified } // Parse options std::vector<std::string> parseOptions(int argc, char* argv[]) { std::string trainingFile = "NULL"; std::string inputNodes = "0"; std::string hiddenNodes = "0"; std::string outputNodes = "0"; std::string hiddenLayers = "0"; std::vector<std::string> options; options.push_back(inputNodes); options.push_back(hiddenNodes); options.push_back(outputNodes); options.push_back(hiddenLayers); options.push_back(trainingFile); for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg == "--help") { printHelp(); exit(0); } else if (arg == "-i" || arg == "--input-nodes") { isValInt(argv[i], argv[i+1]); options[0] = argv[i+1]; i++; } else if (arg == "-h" || arg == "--hidden-nodes") { isValInt(argv[i], argv[i+1]); options[1] = argv[i+1]; i++; } else if (arg == "-o" || arg == "--output-nodes") { isValInt(argv[i], argv[i+1]); options[2] = argv[i+1]; i++; } else if (arg == "-l" || arg == "--hidden-layers") { isValInt(argv[i], argv[i+1]); options[3] = argv[i+1]; i++; } else if (trainingFile == "NULL") { trainingFile = argv[i]; struct stat s; if (stat(argv[i], &s) == 0) { if (s.st_mode & S_IFREG) { std::ifstream tFile(trainingFile); if (tFile.good()) { options[4] = argv[i]; } else { error(ERRFILE, trainingFile); } } else if (s.st_mode & S_IFDIR) { // TODO: Support directories as training file argument error(ERRDIR); } else { error(ERRFILE, trainingFile); } } else { error(ERRFILE, trainingFile); } } else { std::cerr << " ERROR: Invalid option \"" << argv[i] << "\"\n\n"; printHelp(); exit(1); } } if (trainingFile == "NULL") { std::cerr << " ERROR: Training file was not provided.\n\n"; printHelp(); exit(1); } checkParams(options); return options; } // Main method int main(int argc, char* argv[]) { std::vector< std::string > options = parseOptions(argc, argv); // Initialize network Network myNeuralNet = Network(std::stoi(options[0]), std::stoi(options[1]), std::stoi(options[2]), std::stoi(options[3])); // Variables int numInputs = std::stoi(options[0]); int numOutputs = std::stoi(options[2]); std::ifstream tFile(options[4]); std::string val; float totalError = 1.0; /* // Iterate through training file while (!tFile.eof()) { std::vector<float> inputVec; std::vector<float> outputVec(numOutputs, 0.01); // Set input and output vectors for (int i = 0; i < numInputs; i++) { std::getline(tFile, val, ','); inputVec.push_back(std::stof(val)); } std::getline(tFile, val, ','); outputVec[std::stoi(val)] = 0.99; totalError = myNeuralNet.train(inputVec, outputVec); } myNeuralNet.writeWeightFile(getWeightsDir(argv[0])); */ return 0; } <|endoftext|>
<commit_before>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> namespace nix { void Value::maybe_deallocte_string() { #ifndef _WIN32 if (dtype == DataType::String) { v_string.~basic_string(); } #endif } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { #ifndef _WIN32 //If the active member is not a string //we have to inialize the string object if (dtype != DataType::String) { new (&v_string) std::string(); } #endif dtype = DataType::String; v_string = value; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, iterally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: assign_variant_from(other); other.maybe_deallocte_string(); other.dtype = DataType::Nothing; other.v_bool = false; break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(other.v_string); break; case DataType::Nothing: set(false); dtype = DataType::Nothing; break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <commit_msg>Value::swap: use swap_helper also for DataType::Nothing<commit_after>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> namespace nix { void Value::maybe_deallocte_string() { #ifndef _WIN32 if (dtype == DataType::String) { v_string.~basic_string(); } #endif } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { #ifndef _WIN32 //If the active member is not a string //we have to inialize the string object if (dtype != DataType::String) { new (&v_string) std::string(); } #endif dtype = DataType::String; v_string = value; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, iterally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: swap_helper<none_t>(other); break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(other.v_string); break; case DataType::Nothing: set(false); dtype = DataType::Nothing; break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include <queue> #include <Chaos/Types.h> #include <Chaos/Concurrent/Thread.h> #include "object.h" #include "parallel_copy.h" namespace gc { struct ForwardNode { BaseObject* from_ref{}; ForwadingCallback callback{}; ForwardNode(BaseObject* ref, ForwadingCallback&& cb) : from_ref(ref) , callback(std::move(cb)) { } }; class Sweeper : private Chaos::UnCopyable { int id_{}; bool running_{true}; bool sweeping_{}; mutable Chaos::Mutex mutex_; Chaos::Condition cond_; Chaos::Thread thread_; byte_t* heaptr_{}; byte_t* fromspace_{}; byte_t* tospace_{}; byte_t* allocptr_{}; byte_t* scanptr_{}; std::size_t object_counter_{}; std::vector<BaseObject*> roots_; mutable Chaos::Mutex forward_mutex_; std::queue<ForwardNode> forward_workers_; static constexpr std::size_t kSemispaceSize = 100 << 9; void worklist_init(void) { scanptr_ = allocptr_; } bool worklist_empty(void) const { return scanptr_ == allocptr_; } void worklist_put(BaseObject* /*obj*/) {} BaseObject* worklist_fetch(void) { auto* ref = as_object(scanptr_); scanptr_ += ref->get_size(); return ref; } BaseObject* copy(BaseObject* from_ref, bool with_worklist = false) { auto* p = allocptr_; allocptr_ += from_ref->get_size(); BaseObject* to_ref{}; if (from_ref->is_int()) to_ref = new (p) Int(std::move(*Chaos::down_cast<Int*>(from_ref))); else if (from_ref->is_pair()) to_ref = new (p) Pair(std::move(*Chaos::down_cast<Pair*>(from_ref))); CHAOS_CHECK(to_ref != nullptr, "copy object failed"); from_ref->set_forward(to_ref); if (with_worklist) worklist_put(to_ref); return to_ref; } BaseObject* forward(BaseObject* from_ref) { auto* to_ref = from_ref->forward(); if (to_ref == nullptr) { to_ref = copy(from_ref, true); ++object_counter_; } return Chaos::down_cast<BaseObject*>(to_ref); } void* alloc(std::size_t n) { if (allocptr_ + n > tospace_ + kSemispaceSize) ParallelCopy::get_instance().collect(); CHAOS_CHECK(allocptr_ + n <= tospace_ + kSemispaceSize, "allocating failed"); auto* p = allocptr_; allocptr_ += n; return p; } void sweeper_closure(void) { while (running_) { { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); while (running_ && !sweeping_) cond_.wait(); if (!running_) break; } // flip fromspace and tospace std::swap(fromspace_, tospace_); allocptr_ = tospace_; object_counter_ = 0; worklist_init(); for (auto* obj : roots_) obj = forward(obj); while (!worklist_empty()) { auto* ref = worklist_fetch(); if (ref->is_pair()) { auto* pair = Chaos::down_cast<Pair*>(ref); auto* first = pair->first(); if (first != nullptr) { if (!in_sweeper(first)) { ParallelCopy::get_instance().generate_work(id_, first, [pair](BaseObject* ref) { pair->set_first(ref); }); } else { pair->set_first(forward(first)); } } auto* second = pair->second(); if (second != nullptr) { if (!in_sweeper(second)) { // FIXME: there's bug need fix in Windows ??? ParallelCopy::get_instance().generate_work(id_, second, [pair](BaseObject* ref) { pair->set_second(ref); }); } else { pair->set_second(forward(second)); } } } } ParallelCopy::get_instance().notify_traced(id_); while (true) { if (ParallelCopy::get_instance().is_traced() && forward_workers_.empty()) break; if (!forward_workers_.empty()) { auto& node = forward_workers_.front(); auto* to_ref = forward(node.from_ref); node.callback(to_ref); forward_workers_.pop(); } } if (sweeping_) { sweeping_ = false; ParallelCopy::get_instance().notify_collected(id_, object_counter_); } } } public: explicit Sweeper(int id) : id_(id) , mutex_() , cond_(mutex_) , thread_([this]{ sweeper_closure(); }) { thread_.start(); heaptr_ = new byte_t[kSemispaceSize * 2]; CHAOS_CHECK(heaptr_ != nullptr, "create semispace failed"); fromspace_ = heaptr_ + kSemispaceSize; tospace_ = heaptr_; allocptr_ = tospace_; } ~Sweeper(void) { stop(); thread_.join(); delete [] heaptr_; } int get_id(void) const { return id_; } void stop(void) { running_ = false; cond_.notify_one(); } void sweeping(void) { sweeping_ = true; cond_.notify_one(); } bool in_sweeper(BaseObject* obj) { auto* p = as_pointer(obj); return p >= heaptr_ && p < (heaptr_ + kSemispaceSize * 2); } bool need_moving(BaseObject* obj) { auto* to_ref = obj->forward(); auto* p = as_pointer(obj); if (to_ref == nullptr && (p < tospace_ || p > tospace_ + kSemispaceSize)) return true; return false; } void put_in_forwarding(BaseObject* from_ref, ForwadingCallback&& cb) { Chaos::ScopedLock<Chaos::Mutex> g(forward_mutex_); if (need_moving(from_ref) && !from_ref->is_generated()) { forward_workers_.push(ForwardNode(from_ref, std::move(cb))); from_ref->set_generated(); } } BaseObject* put_in(int value) { auto* obj = new (alloc(sizeof(Int))) Int(); obj->set_value(value); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* put_in(BaseObject* first, BaseObject* second) { auto* obj = new (alloc(sizeof(Pair))) Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* fetch_out(void) { auto* obj = roots_.back(); roots_.pop_back(); return obj; } }; ParallelCopy::ParallelCopy(void) : sweeper_mutex_() , sweeper_cond_(sweeper_mutex_) { startup_sweepers(); } ParallelCopy::~ParallelCopy(void) { clearup_sweepers(); } void ParallelCopy::startup_sweepers(void) { for (auto i = 0; i < kMaxSweepers; ++i) sweepers_.emplace_back(new Sweeper(i)); } void ParallelCopy::clearup_sweepers(void) { for (auto& s : sweepers_) s->stop(); } int ParallelCopy::put_in_order(void) { int r = order_; order_ = (order_ + 1) % kMaxSweepers; return r; } int ParallelCopy::fetch_out_order(void) { order_ = (order_ - 1 + kMaxSweepers) % kMaxSweepers; return order_; } void ParallelCopy::generate_work(int sweeper_id, BaseObject* from_ref, ForwadingCallback&& cb) { for (auto& s : sweepers_) { if (s->get_id() == sweeper_id) continue; if (s->in_sweeper(from_ref)) s->put_in_forwarding(from_ref, std::move(cb)); } } void ParallelCopy::notify_traced(int /*sweeper_id*/) { ++tracing_counter_; } void ParallelCopy::notify_collected( int /*sweeper_id*/, std::size_t alive_count) { { Chaos::ScopedLock<Chaos::Mutex> g(sweeper_mutex_); ++sweeper_counter_; object_counter_ += alive_count; } sweeper_cond_.notify_one(); } ParallelCopy& ParallelCopy::get_instance(void) { static ParallelCopy ins; return ins; } void ParallelCopy::collect(void) { auto old_count = object_counter_; tracing_counter_ = 0; sweeper_counter_ = 0; object_counter_ = 0; for (auto& s : sweepers_) s->sweeping(); { Chaos::ScopedLock<Chaos::Mutex> g(sweeper_mutex_); while (sweeper_counter_ < kMaxSweepers) sweeper_cond_.wait(); } std::cout << "[" << old_count - object_counter_ << "] objects collected, " << "[" << object_counter_ << "] objects remaining." << std::endl; } BaseObject* ParallelCopy::put_in(int value) { ++object_counter_; return sweepers_[put_in_order()]->put_in(value); } BaseObject* ParallelCopy::put_in(BaseObject* first, BaseObject* second) { ++object_counter_; return sweepers_[put_in_order()]->put_in(first, second); } BaseObject* ParallelCopy::fetch_out(void) { return sweepers_[fetch_out_order()]->fetch_out(); } } <commit_msg>:bug: fix(ParallelCopy): fixed bug of parallel copying gc<commit_after>// Copyright (c) 2017 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include <queue> #include <Chaos/Types.h> #include <Chaos/Concurrent/Thread.h> #include "object.h" #include "parallel_copy.h" namespace gc { struct ForwardNode { BaseObject* from_ref{}; ForwadingCallback callback{}; ForwardNode(BaseObject* ref, ForwadingCallback&& cb) : from_ref(ref) , callback(std::move(cb)) { } }; class Sweeper : private Chaos::UnCopyable { int id_{}; bool running_{true}; bool sweeping_{}; mutable Chaos::Mutex mutex_; Chaos::Condition cond_; Chaos::Thread thread_; byte_t* heaptr_{}; byte_t* fromspace_{}; byte_t* tospace_{}; byte_t* allocptr_{}; byte_t* scanptr_{}; std::size_t object_counter_{}; std::vector<BaseObject*> roots_; mutable Chaos::Mutex forward_mutex_; std::queue<ForwardNode> forward_workers_; static constexpr std::size_t kSemispaceSize = 100 << 9; void worklist_init(void) { scanptr_ = allocptr_; } bool worklist_empty(void) const { return scanptr_ == allocptr_; } void worklist_put(BaseObject* /*obj*/) {} BaseObject* worklist_fetch(void) { auto* ref = as_object(scanptr_); scanptr_ += ref->get_size(); return ref; } BaseObject* copy(BaseObject* from_ref, bool with_worklist = false) { auto* p = allocptr_; allocptr_ += from_ref->get_size(); BaseObject* to_ref{}; if (from_ref->is_int()) to_ref = new (p) Int(std::move(*Chaos::down_cast<Int*>(from_ref))); else if (from_ref->is_pair()) to_ref = new (p) Pair(std::move(*Chaos::down_cast<Pair*>(from_ref))); CHAOS_CHECK(to_ref != nullptr, "copy object failed"); from_ref->set_forward(to_ref); if (with_worklist) worklist_put(to_ref); return to_ref; } BaseObject* forward(BaseObject* from_ref) { auto* to_ref = from_ref->forward(); if (to_ref == nullptr) { to_ref = copy(from_ref, true); ++object_counter_; } return Chaos::down_cast<BaseObject*>(to_ref); } void* alloc(std::size_t n) { if (allocptr_ + n > tospace_ + kSemispaceSize) ParallelCopy::get_instance().collect(); CHAOS_CHECK(allocptr_ + n <= tospace_ + kSemispaceSize, "allocating failed"); auto* p = allocptr_; allocptr_ += n; return p; } void sweeper_closure(void) { while (running_) { { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); while (running_ && !sweeping_) cond_.wait(); if (!running_) break; } // flip fromspace and tospace std::swap(fromspace_, tospace_); allocptr_ = tospace_; object_counter_ = 0; worklist_init(); for (auto* obj : roots_) obj = forward(obj); while (!worklist_empty()) { auto* ref = worklist_fetch(); if (ref->is_pair()) { auto* pair = Chaos::down_cast<Pair*>(ref); auto* first = pair->first(); if (first != nullptr) { if (!in_sweeper(first)) { ParallelCopy::get_instance().generate_work(id_, first, [pair](BaseObject* ref) { pair->set_first(ref); }); } else { pair->set_first(forward(first)); } } auto* second = pair->second(); if (second != nullptr) { if (!in_sweeper(second)) { ParallelCopy::get_instance().generate_work(id_, second, [pair](BaseObject* ref) { pair->set_second(ref); }); } else { pair->set_second(forward(second)); } } } } ParallelCopy::get_instance().notify_traced(id_); while (true) { if (ParallelCopy::get_instance().is_traced() && forward_workers_.empty()) break; Chaos::ScopedLock<Chaos::Mutex> g(forward_mutex_); if (!forward_workers_.empty()) { auto& node = forward_workers_.front(); auto* to_ref = forward(node.from_ref); node.callback(to_ref); forward_workers_.pop(); } } if (sweeping_) { sweeping_ = false; ParallelCopy::get_instance().notify_collected(id_, object_counter_); } } } public: explicit Sweeper(int id) : id_(id) , mutex_() , cond_(mutex_) , thread_([this]{ sweeper_closure(); }) { thread_.start(); heaptr_ = new byte_t[kSemispaceSize * 2]; CHAOS_CHECK(heaptr_ != nullptr, "create semispace failed"); fromspace_ = heaptr_ + kSemispaceSize; tospace_ = heaptr_; allocptr_ = tospace_; } ~Sweeper(void) { stop(); thread_.join(); delete [] heaptr_; } int get_id(void) const { return id_; } void stop(void) { running_ = false; cond_.notify_one(); } void sweeping(void) { sweeping_ = true; cond_.notify_one(); } bool in_sweeper(BaseObject* obj) { auto* p = as_pointer(obj); return p >= heaptr_ && p < (heaptr_ + kSemispaceSize * 2); } bool need_moving(BaseObject* obj) { auto* to_ref = obj->forward(); auto* p = as_pointer(obj); if (to_ref == nullptr && (p < tospace_ || p > tospace_ + kSemispaceSize)) return true; return false; } void put_in_forwarding(BaseObject* from_ref, ForwadingCallback&& cb) { Chaos::ScopedLock<Chaos::Mutex> g(forward_mutex_); if (need_moving(from_ref) && !from_ref->is_generated()) { forward_workers_.push(ForwardNode(from_ref, std::move(cb))); from_ref->set_generated(); } } BaseObject* put_in(int value) { auto* obj = new (alloc(sizeof(Int))) Int(); obj->set_value(value); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* put_in(BaseObject* first, BaseObject* second) { auto* obj = new (alloc(sizeof(Pair))) Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* fetch_out(void) { auto* obj = roots_.back(); roots_.pop_back(); return obj; } }; ParallelCopy::ParallelCopy(void) : sweeper_mutex_() , sweeper_cond_(sweeper_mutex_) { startup_sweepers(); } ParallelCopy::~ParallelCopy(void) { clearup_sweepers(); } void ParallelCopy::startup_sweepers(void) { for (auto i = 0; i < kMaxSweepers; ++i) sweepers_.emplace_back(new Sweeper(i)); } void ParallelCopy::clearup_sweepers(void) { for (auto& s : sweepers_) s->stop(); } int ParallelCopy::put_in_order(void) { int r = order_; order_ = (order_ + 1) % kMaxSweepers; return r; } int ParallelCopy::fetch_out_order(void) { order_ = (order_ - 1 + kMaxSweepers) % kMaxSweepers; return order_; } void ParallelCopy::generate_work(int sweeper_id, BaseObject* from_ref, ForwadingCallback&& cb) { for (auto& s : sweepers_) { if (s->get_id() == sweeper_id) continue; if (s->in_sweeper(from_ref)) s->put_in_forwarding(from_ref, std::move(cb)); } } void ParallelCopy::notify_traced(int /*sweeper_id*/) { ++tracing_counter_; } void ParallelCopy::notify_collected( int /*sweeper_id*/, std::size_t alive_count) { { Chaos::ScopedLock<Chaos::Mutex> g(sweeper_mutex_); ++sweeper_counter_; object_counter_ += alive_count; } sweeper_cond_.notify_one(); } ParallelCopy& ParallelCopy::get_instance(void) { static ParallelCopy ins; return ins; } void ParallelCopy::collect(void) { auto old_count = object_counter_; tracing_counter_ = 0; sweeper_counter_ = 0; object_counter_ = 0; for (auto& s : sweepers_) s->sweeping(); { Chaos::ScopedLock<Chaos::Mutex> g(sweeper_mutex_); while (sweeper_counter_ < kMaxSweepers) sweeper_cond_.wait(); } std::cout << "[" << old_count - object_counter_ << "] objects collected, " << "[" << object_counter_ << "] objects remaining." << std::endl; } BaseObject* ParallelCopy::put_in(int value) { ++object_counter_; return sweepers_[put_in_order()]->put_in(value); } BaseObject* ParallelCopy::put_in(BaseObject* first, BaseObject* second) { ++object_counter_; return sweepers_[put_in_order()]->put_in(first, second); } BaseObject* ParallelCopy::fetch_out(void) { return sweepers_[fetch_out_order()]->fetch_out(); } } <|endoftext|>
<commit_before>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- /* * Detector.cpp * zxing * * Created by Christian Brunschen on 14/05/2008. * Copyright 2008 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <zxing/qrcode/detector/Detector.h> #include <zxing/qrcode/detector/FinderPatternFinder.h> #include <zxing/qrcode/detector/FinderPattern.h> #include <zxing/qrcode/detector/AlignmentPattern.h> #include <zxing/qrcode/detector/AlignmentPatternFinder.h> #include <zxing/qrcode/Version.h> #include <zxing/common/GridSampler.h> #include <zxing/DecodeHints.h> #include <zxing/common/detector/math_utils.h> #include <sstream> #include <cstdlib> namespace math_utils = zxing::common::detector::math_utils; namespace zxing { namespace qrcode { using namespace std; Detector::Detector(Ref<BitMatrix> image) : image_(image) { } Ref<BitMatrix> Detector::getImage() const { return image_; } Ref<ResultPointCallback> Detector::getResultPointCallback() const { return callback_; } Ref<DetectorResult> Detector::detect(DecodeHints const& hints) { callback_ = hints.getResultPointCallback(); FinderPatternFinder finder(image_, hints.getResultPointCallback()); Ref<FinderPatternInfo> info(finder.find(hints)); return processFinderPatternInfo(info); } Ref<DetectorResult> Detector::processFinderPatternInfo(Ref<FinderPatternInfo> info){ Ref<FinderPattern> topLeft(info->getTopLeft()); Ref<FinderPattern> topRight(info->getTopRight()); Ref<FinderPattern> bottomLeft(info->getBottomLeft()); float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); if (moduleSize < 1.0f) { throw zxing::ReaderException("bad module size"); } int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); Version *provisionalVersion = Version::getProvisionalVersionForDimension(dimension); int modulesBetweenFPCenters = provisionalVersion->getDimensionForVersion() - 7; Ref<AlignmentPattern> alignmentPattern; // Anything above version 1 has an alignment pattern if (provisionalVersion->getAlignmentPatternCenters().size() > 0) { // Guess where a "bottom right" finder pattern would have been float bottomRightX = topRight->getX() - topLeft->getX() + bottomLeft->getX(); float bottomRightY = topRight->getY() - topLeft->getY() + bottomLeft->getY(); // Estimate that alignment pattern is closer by 3 modules // from "bottom right" to known top left location float correctionToTopLeft = 1.0f - 3.0f / (float)modulesBetweenFPCenters; int estAlignmentX = (int)(topLeft->getX() + correctionToTopLeft * (bottomRightX - topLeft->getX())); int estAlignmentY = (int)(topLeft->getY() + correctionToTopLeft * (bottomRightY - topLeft->getY())); // Kind of arbitrary -- expand search radius before giving up for (int i = 4; i <= 16; i <<= 1) { try { alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float)i); break; } catch (zxing::ReaderException const& re) { // try next round } } if (alignmentPattern == 0) { // Try anyway } } Ref<PerspectiveTransform> transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); Ref<BitMatrix> bits(sampleGrid(image_, dimension, transform)); std::vector<Ref<ResultPoint> > points(alignmentPattern == 0 ? 3 : 4); points[0].reset(bottomLeft); points[1].reset(topLeft); points[2].reset(topRight); if (alignmentPattern != 0) { points[3].reset(alignmentPattern); } Ref<DetectorResult> result(new DetectorResult(bits, points)); return result; } Ref<PerspectiveTransform> Detector::createTransform(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref < ResultPoint > bottomLeft, Ref<ResultPoint> alignmentPattern, int dimension) { float dimMinusThree = (float)dimension - 3.5f; float bottomRightX; float bottomRightY; float sourceBottomRightX; float sourceBottomRightY; if (alignmentPattern != 0) { bottomRightX = alignmentPattern->getX(); bottomRightY = alignmentPattern->getY(); sourceBottomRightX = dimMinusThree - 3.0f; sourceBottomRightY = sourceBottomRightX; } else { // Don't have an alignment pattern, just make up the bottom-right point bottomRightX = (topRight->getX() - topLeft->getX()) + bottomLeft->getX(); bottomRightY = (topRight->getY() - topLeft->getY()) + bottomLeft->getY(); sourceBottomRightX = dimMinusThree; sourceBottomRightY = dimMinusThree; } Ref<PerspectiveTransform> transform(PerspectiveTransform::quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft->getX(), topLeft->getY(), topRight->getX(), topRight->getY(), bottomRightX, bottomRightY, bottomLeft->getX(), bottomLeft->getY())); return transform; } Ref<BitMatrix> Detector::sampleGrid(Ref<BitMatrix> image, int dimension, Ref<PerspectiveTransform> transform) { GridSampler &sampler = GridSampler::getInstance(); return sampler.sampleGrid(image, dimension, transform); } int Detector::computeDimension(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref<ResultPoint> bottomLeft, float moduleSize) { int tltrCentersDimension = math_utils::round(ResultPoint::distance(topLeft, topRight) / moduleSize); int tlblCentersDimension = math_utils::round(ResultPoint::distance(topLeft, bottomLeft) / moduleSize); int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; switch (dimension & 0x03) { // mod 4 case 0: dimension++; break; // 1? do nothing case 2: dimension--; break; case 3: ostringstream s; s << "Bad dimension: " << dimension; throw zxing::ReaderException(s.str().c_str()); } return dimension; } float Detector::calculateModuleSize(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref<ResultPoint> bottomLeft) { // Take the average return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; } float Detector::calculateModuleSizeOneWay(Ref<ResultPoint> pattern, Ref<ResultPoint> otherPattern) { float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int)pattern->getX(), (int)pattern->getY(), (int)otherPattern->getX(), (int)otherPattern->getY()); float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int)otherPattern->getX(), (int)otherPattern->getY(), (int)pattern->getX(), (int)pattern->getY()); if (isnan(moduleSizeEst1)) { return moduleSizeEst2; } if (isnan(moduleSizeEst2)) { return moduleSizeEst1; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } float Detector::sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); // Now count other way -- don't run off image though of course float scale = 1.0f; int otherToX = fromX - (toX - fromX); if (otherToX < 0) { scale = (float) fromX / (float) (fromX - otherToX); otherToX = 0; } else if (otherToX >= (int)image_->getWidth()) { scale = (float) (image_->getWidth() - 1 - fromX) / (float) (otherToX - fromX); otherToX = image_->getWidth() - 1; } int otherToY = (int) (fromY - (toY - fromY) * scale); scale = 1.0f; if (otherToY < 0) { scale = (float) fromY / (float) (fromY - otherToY); otherToY = 0; } else if (otherToY >= (int)image_->getHeight()) { scale = (float) (image_->getHeight() - 1 - fromY) / (float) (otherToY - fromY); otherToY = image_->getHeight() - 1; } otherToX = (int) (fromX + (otherToX - fromX) * scale); result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); // Middle pixel is double-counted this way; subtract 1 return result - 1.0f; } float Detector::sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm bool steep = abs(toY - fromY) > abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = abs(toX - fromX); int dy = abs(toY - fromY); int error = -dx >> 1; int xstep = fromX < toX ? 1 : -1; int ystep = fromY < toY ? 1 : -1; // In black pixels, looking for white, first or second time. int state = 0; // Loop up until x == toX, but not beyond int xLimit = toX + xstep; for (int x = fromX, y = fromY; x != xLimit; x += xstep) { int realX = steep ? y : x; int realY = steep ? x : y; // Does current pixel mean we have moved white to black or vice versa? if (!((state == 1) ^ image_->get(realX, realY))) { if (state == 2) { return math_utils::distance(x, y, fromX, fromY); } state++; } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } // Found black-white-black; give the benefit of the doubt that the next pixel outside the image // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this. if (state == 2) { return math_utils::distance(toX + xstep, toY, fromX, fromY); } // else we didn't find even black-white-black; no estimate is really possible return NAN; } Ref<AlignmentPattern> Detector::findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) { // Look for an alignment pattern (3 modules in size) around where it // should be int allowance = (int)(allowanceFactor * overallEstModuleSize); int alignmentAreaLeftX = max(0, estAlignmentX - allowance); int alignmentAreaRightX = min((int)(image_->getWidth() - 1), estAlignmentX + allowance); if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { throw zxing::ReaderException("region too small to hold alignment pattern"); } int alignmentAreaTopY = max(0, estAlignmentY - allowance); int alignmentAreaBottomY = min((int)(image_->getHeight() - 1), estAlignmentY + allowance); if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) { throw zxing::ReaderException("region too small to hold alignment pattern"); } AlignmentPatternFinder alignmentFinder(image_, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, callback_); return alignmentFinder.find(); } } } <commit_msg>tabs to spaces<commit_after>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- /* * Detector.cpp * zxing * * Created by Christian Brunschen on 14/05/2008. * Copyright 2008 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <zxing/qrcode/detector/Detector.h> #include <zxing/qrcode/detector/FinderPatternFinder.h> #include <zxing/qrcode/detector/FinderPattern.h> #include <zxing/qrcode/detector/AlignmentPattern.h> #include <zxing/qrcode/detector/AlignmentPatternFinder.h> #include <zxing/qrcode/Version.h> #include <zxing/common/GridSampler.h> #include <zxing/DecodeHints.h> #include <zxing/common/detector/math_utils.h> #include <sstream> #include <cstdlib> namespace math_utils = zxing::common::detector::math_utils; namespace zxing { namespace qrcode { using namespace std; Detector::Detector(Ref<BitMatrix> image) : image_(image) { } Ref<BitMatrix> Detector::getImage() const { return image_; } Ref<ResultPointCallback> Detector::getResultPointCallback() const { return callback_; } Ref<DetectorResult> Detector::detect(DecodeHints const& hints) { callback_ = hints.getResultPointCallback(); FinderPatternFinder finder(image_, hints.getResultPointCallback()); Ref<FinderPatternInfo> info(finder.find(hints)); return processFinderPatternInfo(info); } Ref<DetectorResult> Detector::processFinderPatternInfo(Ref<FinderPatternInfo> info){ Ref<FinderPattern> topLeft(info->getTopLeft()); Ref<FinderPattern> topRight(info->getTopRight()); Ref<FinderPattern> bottomLeft(info->getBottomLeft()); float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); if (moduleSize < 1.0f) { throw zxing::ReaderException("bad module size"); } int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); Version *provisionalVersion = Version::getProvisionalVersionForDimension(dimension); int modulesBetweenFPCenters = provisionalVersion->getDimensionForVersion() - 7; Ref<AlignmentPattern> alignmentPattern; // Anything above version 1 has an alignment pattern if (provisionalVersion->getAlignmentPatternCenters().size() > 0) { // Guess where a "bottom right" finder pattern would have been float bottomRightX = topRight->getX() - topLeft->getX() + bottomLeft->getX(); float bottomRightY = topRight->getY() - topLeft->getY() + bottomLeft->getY(); // Estimate that alignment pattern is closer by 3 modules // from "bottom right" to known top left location float correctionToTopLeft = 1.0f - 3.0f / (float)modulesBetweenFPCenters; int estAlignmentX = (int)(topLeft->getX() + correctionToTopLeft * (bottomRightX - topLeft->getX())); int estAlignmentY = (int)(topLeft->getY() + correctionToTopLeft * (bottomRightY - topLeft->getY())); // Kind of arbitrary -- expand search radius before giving up for (int i = 4; i <= 16; i <<= 1) { try { alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float)i); break; } catch (zxing::ReaderException const& re) { // try next round } } if (alignmentPattern == 0) { // Try anyway } } Ref<PerspectiveTransform> transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); Ref<BitMatrix> bits(sampleGrid(image_, dimension, transform)); std::vector<Ref<ResultPoint> > points(alignmentPattern == 0 ? 3 : 4); points[0].reset(bottomLeft); points[1].reset(topLeft); points[2].reset(topRight); if (alignmentPattern != 0) { points[3].reset(alignmentPattern); } Ref<DetectorResult> result(new DetectorResult(bits, points)); return result; } Ref<PerspectiveTransform> Detector::createTransform(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref < ResultPoint > bottomLeft, Ref<ResultPoint> alignmentPattern, int dimension) { float dimMinusThree = (float)dimension - 3.5f; float bottomRightX; float bottomRightY; float sourceBottomRightX; float sourceBottomRightY; if (alignmentPattern != 0) { bottomRightX = alignmentPattern->getX(); bottomRightY = alignmentPattern->getY(); sourceBottomRightX = dimMinusThree - 3.0f; sourceBottomRightY = sourceBottomRightX; } else { // Don't have an alignment pattern, just make up the bottom-right point bottomRightX = (topRight->getX() - topLeft->getX()) + bottomLeft->getX(); bottomRightY = (topRight->getY() - topLeft->getY()) + bottomLeft->getY(); sourceBottomRightX = dimMinusThree; sourceBottomRightY = dimMinusThree; } Ref<PerspectiveTransform> transform(PerspectiveTransform::quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft->getX(), topLeft->getY(), topRight->getX(), topRight->getY(), bottomRightX, bottomRightY, bottomLeft->getX(), bottomLeft->getY())); return transform; } Ref<BitMatrix> Detector::sampleGrid(Ref<BitMatrix> image, int dimension, Ref<PerspectiveTransform> transform) { GridSampler &sampler = GridSampler::getInstance(); return sampler.sampleGrid(image, dimension, transform); } int Detector::computeDimension(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref<ResultPoint> bottomLeft, float moduleSize) { int tltrCentersDimension = math_utils::round(ResultPoint::distance(topLeft, topRight) / moduleSize); int tlblCentersDimension = math_utils::round(ResultPoint::distance(topLeft, bottomLeft) / moduleSize); int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; switch (dimension & 0x03) { // mod 4 case 0: dimension++; break; // 1? do nothing case 2: dimension--; break; case 3: ostringstream s; s << "Bad dimension: " << dimension; throw zxing::ReaderException(s.str().c_str()); } return dimension; } float Detector::calculateModuleSize(Ref<ResultPoint> topLeft, Ref<ResultPoint> topRight, Ref<ResultPoint> bottomLeft) { // Take the average return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; } float Detector::calculateModuleSizeOneWay(Ref<ResultPoint> pattern, Ref<ResultPoint> otherPattern) { float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int)pattern->getX(), (int)pattern->getY(), (int)otherPattern->getX(), (int)otherPattern->getY()); float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int)otherPattern->getX(), (int)otherPattern->getY(), (int)pattern->getX(), (int)pattern->getY()); if (isnan(moduleSizeEst1)) { return moduleSizeEst2; } if (isnan(moduleSizeEst2)) { return moduleSizeEst1; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } float Detector::sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); // Now count other way -- don't run off image though of course float scale = 1.0f; int otherToX = fromX - (toX - fromX); if (otherToX < 0) { scale = (float) fromX / (float) (fromX - otherToX); otherToX = 0; } else if (otherToX >= (int)image_->getWidth()) { scale = (float) (image_->getWidth() - 1 - fromX) / (float) (otherToX - fromX); otherToX = image_->getWidth() - 1; } int otherToY = (int) (fromY - (toY - fromY) * scale); scale = 1.0f; if (otherToY < 0) { scale = (float) fromY / (float) (fromY - otherToY); otherToY = 0; } else if (otherToY >= (int)image_->getHeight()) { scale = (float) (image_->getHeight() - 1 - fromY) / (float) (otherToY - fromY); otherToY = image_->getHeight() - 1; } otherToX = (int) (fromX + (otherToX - fromX) * scale); result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); // Middle pixel is double-counted this way; subtract 1 return result - 1.0f; } float Detector::sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm bool steep = abs(toY - fromY) > abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = abs(toX - fromX); int dy = abs(toY - fromY); int error = -dx >> 1; int xstep = fromX < toX ? 1 : -1; int ystep = fromY < toY ? 1 : -1; // In black pixels, looking for white, first or second time. int state = 0; // Loop up until x == toX, but not beyond int xLimit = toX + xstep; for (int x = fromX, y = fromY; x != xLimit; x += xstep) { int realX = steep ? y : x; int realY = steep ? x : y; // Does current pixel mean we have moved white to black or vice versa? if (!((state == 1) ^ image_->get(realX, realY))) { if (state == 2) { return math_utils::distance(x, y, fromX, fromY); } state++; } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } // Found black-white-black; give the benefit of the doubt that the next pixel outside the image // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this. if (state == 2) { return math_utils::distance(toX + xstep, toY, fromX, fromY); } // else we didn't find even black-white-black; no estimate is really possible return NAN; } Ref<AlignmentPattern> Detector::findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) { // Look for an alignment pattern (3 modules in size) around where it // should be int allowance = (int)(allowanceFactor * overallEstModuleSize); int alignmentAreaLeftX = max(0, estAlignmentX - allowance); int alignmentAreaRightX = min((int)(image_->getWidth() - 1), estAlignmentX + allowance); if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { throw zxing::ReaderException("region too small to hold alignment pattern"); } int alignmentAreaTopY = max(0, estAlignmentY - allowance); int alignmentAreaBottomY = min((int)(image_->getHeight() - 1), estAlignmentY + allowance); if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) { throw zxing::ReaderException("region too small to hold alignment pattern"); } AlignmentPatternFinder alignmentFinder(image_, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, callback_); return alignmentFinder.find(); } } } <|endoftext|>
<commit_before>/** \file merge_differential_and_full_marc_updates.cc * \brief A tool for creating combined full updates from an older full update and one or more differential updates. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Config files for this program look like this: [Files] loesch_liste = LOEPPN-\d{6} komplett_abzug = SA-MARC-ixtheo-\d{6}.tar.gz differenz_abzug = TA-MARC-ixtheo-\d{6}.tar.gz [SMTPServer] server_address = smtpserv.uni-tuebingen.de server_user = qubob16@uni-tuebingen.de server_password = vv:*i%Nk */ #include <iostream> #include <memory> #include <stdexcept> #include <vector> #include <cstdlib> #include <cstring> #include <dirent.h> #include <sys/types.h> #include <unistd.h> #include "Compiler.h" #include "EmailSender.h" #include "IniFile.h" #include "RegexMatcher.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " default_email_recipient\n"; std::exit(EXIT_FAILURE); } namespace { std::string default_email_recipient; std::string email_server_address; std::string email_server_user; std::string email_server_password; } // unnamed namespace std::string GetHostname() { char buf[1024]; if (unlikely(::gethostname(buf, sizeof buf) != 0)) Error("gethostname(2) failed! (" + std::string(::strerror(errno)) + ")"); buf[sizeof(buf) - 1] = '\0'; return buf; } void SendEmail(const std::string &subject, const std::string &message_body, const EmailSender::Priority priority) { if (not EmailSender::SendEmail(::email_server_user, ::default_email_recipient, subject, message_body, priority)) Error("failed to send an email!"); } void LogSendEmailAndDie(const std::string &one_line_message) { std::cerr << one_line_message << '\n'; SendEmail(std::string(::progname) + " failed! (from " + GetHostname() + ")", "Please have a look at the log for details.\n", EmailSender::VERY_HIGH); std::exit(EXIT_FAILURE); } // Populates "filenames" with a list of regular files and returns the number of matching filenames that were found // in the current working directory. unsigned GetListOfRegularFiles(const std::string &filename_regex, std::vector<std::string> * const filenames) { filenames->clear(); std::string err_msg; std::unique_ptr<RegexMatcher> matcher(RegexMatcher::RegexMatcherFactory(filename_regex, &err_msg)); if (unlikely(not err_msg.empty())) LogSendEmailAndDie("in GetListOfRegularFiles: bad file regex: \"" + filename_regex +"\"."); DIR * const directory_stream(::opendir(".")); if (unlikely(directory_stream == nullptr)) LogSendEmailAndDie("in GetListOfRegularFiles: opendir(3) failed(" + std::string(::strerror(errno)) + ")"); struct dirent *entry; while ((entry = ::readdir(directory_stream)) != nullptr) { if (entry->d_type == DT_REG and matcher->matched(entry->d_name)) filenames->emplace_back(entry->d_name); } ::closedir(directory_stream); return filenames->size(); } const std::string CONF_FILE_PATH("/var/lib/tuelib/cronjobs/handle_partial_updates.conf"); int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); ::default_email_recipient = argv[1]; try { const IniFile ini_file(CONF_FILE_PATH); ::email_server_address = ini_file.getString("SMTPServer", "server_address"); ::email_server_user = ini_file.getString("SMTPServer", "server_user"); ::email_server_password = ini_file.getString("SMTPServer", "server_password"); std::vector<std::string> filenames; GetListOfRegularFiles(".*\\.cc", &filenames); for (const auto &filename : filenames) std::cout << filename << '\n'; SendEmail(std::string(::progname), "Succeeded.\n", EmailSender::VERY_LOW); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Work in progress.<commit_after>/** \file merge_differential_and_full_marc_updates.cc * \brief A tool for creating combined full updates from an older full update and one or more differential updates. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Config files for this program look like this: [Files] loesch_liste = LOEPPN-\d{6} komplett_abzug = SA-MARC-ixtheo-\d{6}.tar.gz differenz_abzug = TA-MARC-ixtheo-\d{6}.tar.gz [SMTPServer] server_address = smtpserv.uni-tuebingen.de server_user = qubob16@uni-tuebingen.de server_password = vv:*i%Nk */ #include <algorithm> #include <iostream> #include <memory> #include <stdexcept> #include <vector> #include <cstdlib> #include <cstring> #include <dirent.h> #include <sys/types.h> #include <unistd.h> #include "Archive.h" #include "Compiler.h" #include "EmailSender.h" #include "File.h" #include "FileUtil.h" #include "IniFile.h" #include "RegexMatcher.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " default_email_recipient\n"; std::exit(EXIT_FAILURE); } namespace { std::string default_email_recipient; std::string email_server_address; std::string email_server_user; std::string email_server_password; } // unnamed namespace void Log(const std::string &log_message) { std::cerr << ::progname << ": " << log_message << '\n'; } std::string GetHostname() { char buf[1024]; if (unlikely(::gethostname(buf, sizeof buf) != 0)) Error("gethostname(2) failed! (" + std::string(::strerror(errno)) + ")"); buf[sizeof(buf) - 1] = '\0'; return buf; } void SendEmail(const std::string &subject, const std::string &message_body, const EmailSender::Priority priority) { if (not EmailSender::SendEmail(::email_server_user, ::default_email_recipient, subject, message_body, priority)) Error("failed to send an email!"); } void LogSendEmailAndDie(const std::string &one_line_message) { Log(one_line_message); SendEmail(std::string(::progname) + " failed! (from " + GetHostname() + ")", "Please have a look at the log for details.\n", EmailSender::VERY_HIGH); std::exit(EXIT_FAILURE); } // Populates "filenames" with a list of regular files and returns the number of matching filenames that were found // in the current working directory. The list will be sorted in alphanumerical order. unsigned GetSortedListOfRegularFiles(const std::string &filename_regex, std::vector<std::string> * const filenames) { filenames->clear(); std::string err_msg; std::unique_ptr<RegexMatcher> matcher(RegexMatcher::RegexMatcherFactory(filename_regex, &err_msg)); if (unlikely(not err_msg.empty())) LogSendEmailAndDie("in GetListOfRegularFiles: bad file regex: \"" + filename_regex +"\"."); DIR * const directory_stream(::opendir(".")); if (unlikely(directory_stream == nullptr)) LogSendEmailAndDie("in GetListOfRegularFiles: opendir(3) failed(" + std::string(::strerror(errno)) + ")"); struct dirent *entry; while ((entry = ::readdir(directory_stream)) != nullptr) { if (entry->d_type == DT_REG and matcher->matched(entry->d_name)) filenames->emplace_back(entry->d_name); } ::closedir(directory_stream); std::sort(filenames->begin(), filenames->end()); return filenames->size(); } std::string PickCompleteDumpFilename(const std::string &complete_dump_pattern) { std::vector<std::string> complete_dump_filenames; GetSortedListOfRegularFiles(complete_dump_pattern, &complete_dump_filenames); if (unlikely(complete_dump_filenames.empty())) LogSendEmailAndDie("did not find a complete MARC dump matching \"" + complete_dump_pattern + "\"!"); const std::string &chosen_filename(complete_dump_filenames.back()); Log("picking \"" + chosen_filename + "\" as the complete MARC dump."); return chosen_filename; } std::string ExtractDateFromFilename(const std::string &filename) { static const std::string DATE_EXTRACTION_REGEX(".*(\\d{6}).*"); static RegexMatcher *matcher; if (matcher == nullptr) { std::string err_msg; matcher = RegexMatcher::RegexMatcherFactory(DATE_EXTRACTION_REGEX, &err_msg); if (unlikely(not err_msg.empty())) LogSendEmailAndDie("in ExtractDate: failed to compile regex: \"" + DATE_EXTRACTION_REGEX +"\"."); } if (unlikely(not matcher->matched(filename))) LogSendEmailAndDie("in ExtractDate: \"" + filename + "\" failed to match the regex \"" + DATE_EXTRACTION_REGEX + "\"!"); return (*matcher)[1]; } void GetFilesMoreRecentThan(const std::string &cutoff_date, const std::string &filename_pattern, std::vector<std::string> * const filenames) { GetSortedListOfRegularFiles(filename_pattern, filenames); const auto first_deletion_position(filenames->begin()); auto last_deletion_position(filenames->begin()); while (last_deletion_position < filenames->end() and ExtractDateFromFilename(*last_deletion_position) <= cutoff_date) ++last_deletion_position; const auto erase_count(std::distance(first_deletion_position, last_deletion_position)); if (unlikely(erase_count > 0)) { Log("Warning: ignoring " + std::to_string(erase_count) + " files matching \"" + filename_pattern + "\" because they are too old for the cut-off date " + cutoff_date + "!"); filenames->erase(first_deletion_position, last_deletion_position); } } std::string GetWorkingDirectoryName() { std::string dirname, basename; FileUtil::DirnameAndBasename(::progname, &dirname, &basename); return basename + ".working_directory"; } void ChangeDirectoryOrDie(const std::string &directory) { if (unlikely(::chdir(directory.c_str()) != 0)) LogSendEmailAndDie("failed to change directory to \"" + directory + "\"! " + std::string(::strerror(errno)) + ")"); } void CreateAndChangeIntoTheWorkingDirectory() { const std::string working_directory(GetWorkingDirectoryName()); if (not FileUtil::MakeDirectory(working_directory)) LogSendEmailAndDie("in CreateAndChangeIntoTheWorkingDirectory failed to create \"" + working_directory + "\"!"); ChangeDirectoryOrDie(working_directory); } void ExtractMarcFilesFromArchive(const std::string &archive_name, const std::string &name_prefix = "") { ArchiveReader reader(archive_name); ArchiveReader::EntryInfo file_info; while (reader.getNext(&file_info)) { if (unlikely(not file_info.isRegularFile())) LogSendEmailAndDie("in ExtractMarcFilesFromArchive: unexpectedly, the entry \"" + file_info.getFilename() + "\" in \"" + archive_name + "\" is not a regular file!"); const std::string output_filename(name_prefix + file_info.getFilename()); File disc_file(output_filename, "w"); char buf[8192]; size_t read_count; while ((read_count = reader.read(buf, sizeof buf)) > 0) { if (unlikely(disc_file.write(buf, read_count) != read_count)) LogSendEmailAndDie("in ExtractMarcFilesFromArchive: failed to write data to \"" + output_filename + "\"! (No room?)"); } } } void ExtractAndCombineMarcFilesFromArchive(const std::string &complete_dump_filename) { CreateAndChangeIntoTheWorkingDirectory(); ExtractMarcFilesFromArchive("../" + complete_dump_filename); } const std::string CONF_FILE_PATH("/var/lib/tuelib/cronjobs/merge_differential_and_full_marc_updates.conf"); int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); ::default_email_recipient = argv[1]; try { const IniFile ini_file(CONF_FILE_PATH); ::email_server_address = ini_file.getString("SMTPServer", "server_address"); ::email_server_user = ini_file.getString("SMTPServer", "server_user"); ::email_server_password = ini_file.getString("SMTPServer", "server_password"); const std::string deletion_list_pattern(ini_file.getString("Files", "deletion_list")); const std::string complete_dump_pattern(ini_file.getString("Files", "complete_dump")); const std::string incremental_dump_pattern(ini_file.getString("Files", "incremental_dump")); const std::string complete_dump_filename(PickCompleteDumpFilename(complete_dump_pattern)); const std::string complete_dump_filename_date(ExtractDateFromFilename(complete_dump_filename)); std::vector<std::string> deletion_list_filenames; GetFilesMoreRecentThan(complete_dump_filename_date, deletion_list_pattern, &deletion_list_filenames); if (not deletion_list_filenames.empty()) Log("identified " + std::to_string(deletion_list_filenames.size()) + " deletion list filenames for application."); std::vector<std::string> incremental_dump_filenames; GetFilesMoreRecentThan(complete_dump_filename_date, incremental_dump_pattern, &incremental_dump_filenames); if (not incremental_dump_filenames.empty()) Log("identified " + std::to_string(incremental_dump_filenames.size()) + " incremental dump filenames for application."); if (deletion_list_filenames.empty() and incremental_dump_filenames.empty()) SendEmail(std::string(::progname), "No recent deletion lists nor incremental dump filenames.\nTherefore we have nothing to do!\n", EmailSender::VERY_LOW); CreateAndChangeIntoTheWorkingDirectory(); ExtractAndCombineMarcFilesFromArchive(complete_dump_filename); SendEmail(std::string(::progname), "Succeeded.\n", EmailSender::VERY_LOW); } catch (const std::exception &x) { LogSendEmailAndDie("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>#ifndef __SIMFQT_SVC_SIMFQT_SERVICE_HPP #define __SIMFQT_SVC_SIMFQT_SERVICE_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_service_types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // SimFQT #include <simfqt/SIMFQT_Types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // Forward declarations. namespace stdair { class STDAIR_Service; struct BookingRequestStruct; struct BasLogParams; struct BasDBParams; struct BookingRequestStruct; } namespace SIMFQT { // Forward declaration class SIMFQT_ServiceContext; /** Interface for the SIMFQT Services. */ class SIMFQT_Service { public: // /////////// Business Methods ///////////// /** Calculate the fares corresponding to a given list of travel solutions. <br>The stdair::Fare_T attribute of each travel solution of the list is calculated. @param stdair::BookingRequestStruct& Booking request. @param stdair::TravelSolutionList_T& List of travel solution. */ void getFares (const stdair::BookingRequestStruct&, stdair::TravelSolutionList_T&); public: // ////////////////// Constructors and Destructors ////////////////// /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>A reference on an output stream is given, so that log outputs can be directed onto that stream. <br>Moreover, database connection parameters are given, so that a session can be created on the corresponding database. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::BasDBParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, a reference on an output stream is given, so that log outputs can be directed onto that stream. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, as no reference on any output stream is given, it is assumed that the StdAir log service has already been initialised with the proper log output stream by some other methods in the calling chain (for instance, when the SIMFQT_Service is itself being initialised by another library service such as SIMCRS_Service). @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr, const stdair::Filename_T& iFareInputFilename); /** Destructor. */ ~SIMFQT_Service(); private: // /////// Construction and Destruction helper methods /////// /** Default constructor. */ SIMFQT_Service (); /** Default copy constructor. */ SIMFQT_Service (const SIMFQT_Service&); /** Initialise the (SIMFQT) service context (i.e., the SIMFQT_ServiceContext object). */ void initServiceContext (); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. */ void initStdAirService (const stdair::BasLogParams&, const stdair::BasDBParams&); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. */ void initStdAirService (const stdair::BasLogParams&); /** Initialise. <br>The CSV file, describing the airline fares for the simulator, is parsed and the inventories are generated accordingly. @param const stdair::Filename_T& Filename of the input fare file. */ void init (const stdair::Filename_T& iFareInputFilename); /** Finalise. */ void finalise (); private: // ///////// Service Context ///////// /** Simfqt context. */ SIMFQT_ServiceContext* _simfqtServiceContext; }; } #endif // __SIMFQT_SVC_SIMFQT_SERVICE_HPP <commit_msg>[SimFQT][Dev] SimFQT now receives directly a TravelSolution (rather than a SegmentPathList).<commit_after>#ifndef __SIMFQT_SVC_SIMFQT_SERVICE_HPP #define __SIMFQT_SVC_SIMFQT_SERVICE_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_service_types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // SimFQT #include <simfqt/SIMFQT_Types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // Forward declarations. namespace stdair { class STDAIR_Service; struct BookingRequestStruct; struct BasLogParams; struct BasDBParams; struct BookingRequestStruct; } namespace SIMFQT { // Forward declaration class SIMFQT_ServiceContext; /** Interface for the SIMFQT Services. */ class SIMFQT_Service { public: // /////////// Business Methods ///////////// /** Calculate the fares corresponding to a given list of travel solutions. <br>The stdair::Fare_T attribute of each travel solution of the list is calculated. @param stdair::BookingRequestStruct& Booking request. @param stdair::TravelSolutionList_T& List of travel solution. */ void getFares (const stdair::BookingRequestStruct&, stdair::TravelSolutionList_T&); public: // ////////////////// Constructors and Destructors ////////////////// /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>A reference on an output stream is given, so that log outputs can be directed onto that stream. <br>Moreover, database connection parameters are given, so that a session can be created on the corresponding database. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::BasDBParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, a reference on an output stream is given, so that log outputs can be directed onto that stream. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, as no reference on any output stream is given, it is assumed that the StdAir log service has already been initialised with the proper log output stream by some other methods in the calling chain (for instance, when the SIMFQT_Service is itself being initialised by another library service such as SIMCRS_Service). @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr, const stdair::Filename_T& iFareInputFilename); /** Destructor. */ ~SIMFQT_Service(); private: // /////// Construction and Destruction helper methods /////// /** Default constructor. */ SIMFQT_Service (); /** Default copy constructor. */ SIMFQT_Service (const SIMFQT_Service&); /** Initialise the (SIMFQT) service context (i.e., the SIMFQT_ServiceContext object). */ void initServiceContext (); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. */ void initStdAirService (const stdair::BasLogParams&, const stdair::BasDBParams&); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. */ void initStdAirService (const stdair::BasLogParams&); /** Initialise. <br>The CSV file, describing the airline fares for the simulator, is parsed and the inventories are generated accordingly. @param const stdair::Filename_T& Filename of the input fare file. */ void init (const stdair::Filename_T& iFareInputFilename); /** Finalise. */ void finalise (); private: // ///////// Service Context ///////// /** Simfqt context. */ SIMFQT_ServiceContext* _simfqtServiceContext; }; } #endif // __SIMFQT_SVC_SIMFQT_SERVICE_HPP <|endoftext|>
<commit_before>/** * \file commands.hxx * Interface definition for encapsulated commands. * Started Spring 2001 by David Megginson, david@megginson.com * This code is released into the Public Domain. * * $Id$ */ #ifndef __COMMANDS_HXX #define __COMMANDS_HXX #include <simgear/compiler.h> #include STL_STRING #include <map> #include <vector> #include "props.hxx" SG_USING_STD(string); SG_USING_STD(map); SG_USING_STD(vector); /** * Manage commands. * * <p>This class allows the application to register and unregister * commands, and provides shortcuts for executing them. Commands * are simple functions that take a const pointer to an SGPropertyNode * as an argument and return a bool value indicating success or failure. * The property node may be ignored, or it may contain values that * the command uses as parameters.</p> * * <p>There are convenience methods for invoking a command function * with no arguments or with a single, primitive argument.</p> * * @author David Megginson, david@megginson.com */ class SGCommandMgr { public: /** * Type for a command function. */ typedef bool (*command_t) (const SGPropertyNode * arg); /** * Default constructor. */ SGCommandMgr (); /** * Destructor. */ virtual ~SGCommandMgr (); /** * Register a new command with the manager. * * @param name The command name. Any existing command with * the same name will silently be overwritten. * @param command A pointer to a one-arg function returning * a bool result. The argument is always a const pointer to * an SGPropertyNode (which may contain multiple values). */ virtual void addCommand (const string &name, command_t command); /** * Look up an existing command. * * @param name The command name. * @return A pointer to the command, or 0 if there is no registered * command with the name specified. */ virtual command_t getCommand (const string &name) const; /** * Get a list of all existing command names. * * @return A (possibly empty) vector of the names of all registered * commands. */ virtual vector<string> getCommandNames () const; /** * Execute a command. * * This is the primary method for invoking a command; the others * are convenience methods that invoke this one indirectly. * * @param name The name of the command. * @param arg A const pointer to an SGPropertyNode. The node * may have a value and/or children, etc., so that it is possible * to pass an arbitrarily complex data structure to a command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, const SGPropertyNode * arg) const; /** * Execute a command with no argument. * * The command function will receive a pointer to a property node * with no value and no children. * * @param name The name of the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name) const; /** * Execute a command with a single bool argument. * * The command function will receive a pointer to a property node * with a bool value and no children. * * @param name The name of the command. * @param arg The bool argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, bool arg) const; /** * Execute a command with a single int argument. * * The command function will receive a pointer to a property node * with a int value and no children. * * @param name The name of the command. * @param arg The int argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, int arg) const; /** * Execute a command with a single long argument. * * The command function will receive a pointer to a property node * with a long value and no children. * * @param name The name of the command. * @param arg The long argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, long arg) const; /** * Execute a command with a single float argument. * * The command function will receive a pointer to a property node * with a float value and no children. * * @param name The name of the command. * @param arg The float argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, float arg) const; /** * Execute a command with a single double argument. * * The command function will receive a pointer to a property node * with a double value and no children. * * @param name The name of the command. * @param arg The double argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, double arg) const; /** * Execute a command with a single string argument. * * The command function will receive a pointer to a property node * with a string value and no children. * * @param name The name of the command. * @param arg The string argument to the command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, string arg) const; private: typedef map<string,command_t> command_map; command_map _commands; }; #endif // __COMMANDS_HXX // end of commands.hxx <commit_msg>- added SGCommandState class so that commands can compile and save copies of their arguments - modified prototype for command functions -- they now take a pointer to a pointer of an SGCommandState object (which they will normally subclass) so that they can cache state between invocations - commented out convenience execute methods until they're actually needed<commit_after>/** * \file commands.hxx * Interface definition for encapsulated commands. * Started Spring 2001 by David Megginson, david@megginson.com * This code is released into the Public Domain. * * $Id$ */ #ifndef __COMMANDS_HXX #define __COMMANDS_HXX #include <simgear/compiler.h> #include STL_STRING #include <map> #include <vector> #include "props.hxx" SG_USING_STD(string); SG_USING_STD(map); SG_USING_STD(vector); /** * Stored state for a command. * * <p>This class allows a command to cache parts of its state between * invocations with the same parameters. Nearly every command that * actually uses this will subclass it in some way. The command * allocates the structure, but it is up to the caller to delete it * when it is no longer necessary, unless the command deletes it * and replaces the value with 0 or another command-state object * first.</p> * * <p>Note that this class is for caching only; all of the information * in it must be recoverable by other means, since the state could * arbitrarily disappear between invocations if the caller decides to * delete it.</p> * * <p>By default, the command state includes a place to keep a copy of * the parameters.</p> * * @author David Megginson, david@megginson.com */ class SGCommandState { public: SGCommandState (); SGCommandState (const SGPropertyNode * args); virtual ~SGCommandState (); virtual void setArgs (const SGPropertyNode * args); virtual const SGPropertyNode * getArgs () const { return _args; } private: SGPropertyNode * _args; }; /** * Manage commands. * * <p>This class allows the application to register and unregister * commands, and provides shortcuts for executing them. Commands are * simple functions that take a const pointer to an SGPropertyNode and * a pointer to a pointer variable (which should be 0 initially) where * the function can store compiled copies of its arguments, etc. to * avoid expensive recalculations. If the command deletes the * SGCommandState, it must replace it with a new pointer or 0; * otherwise, the caller is free to delete and zero the pointer at any * time and the command will start fresh with the next invocation. * The command must return a bool value indicating success or failure. * The property node may be ignored, or it may contain values that the * command uses as parameters.</p> * * <p>There are convenience methods for invoking a command function * with no arguments or with a single, primitive argument.</p> * * @author David Megginson, david@megginson.com */ class SGCommandMgr { public: /** * Type for a command function. */ typedef bool (*command_t) (const SGPropertyNode * arg, SGCommandState ** state); /** * Default constructor. */ SGCommandMgr (); /** * Destructor. */ virtual ~SGCommandMgr (); /** * Register a new command with the manager. * * @param name The command name. Any existing command with * the same name will silently be overwritten. * @param command A pointer to a one-arg function returning * a bool result. The argument is always a const pointer to * an SGPropertyNode (which may contain multiple values). */ virtual void addCommand (const string &name, command_t command); /** * Look up an existing command. * * @param name The command name. * @return A pointer to the command, or 0 if there is no registered * command with the name specified. */ virtual command_t getCommand (const string &name) const; /** * Get a list of all existing command names. * * @return A (possibly empty) vector of the names of all registered * commands. */ virtual vector<string> getCommandNames () const; /** * Execute a command. * * This is the primary method for invoking a command; the others * are convenience methods that invoke this one indirectly. * * @param name The name of the command. * @param arg A const pointer to an SGPropertyNode. The node * may have a value and/or children, etc., so that it is possible * to pass an arbitrarily complex data structure to a command. * @return true if the command is present and executes successfully, * false otherwise. */ virtual bool execute (const string &name, const SGPropertyNode * arg, SGCommandState ** state) const; // /** // * Execute a command with no argument. // * // * The command function will receive a pointer to a property node // * with no value and no children. // * // * @param name The name of the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name) const; // /** // * Execute a command with a single bool argument. // * // * The command function will receive a pointer to a property node // * with a bool value and no children. // * // * @param name The name of the command. // * @param arg The bool argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, bool arg) const; // /** // * Execute a command with a single int argument. // * // * The command function will receive a pointer to a property node // * with a int value and no children. // * // * @param name The name of the command. // * @param arg The int argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, int arg) const; // /** // * Execute a command with a single long argument. // * // * The command function will receive a pointer to a property node // * with a long value and no children. // * // * @param name The name of the command. // * @param arg The long argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, long arg) const; // /** // * Execute a command with a single float argument. // * // * The command function will receive a pointer to a property node // * with a float value and no children. // * // * @param name The name of the command. // * @param arg The float argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, float arg) const; // /** // * Execute a command with a single double argument. // * // * The command function will receive a pointer to a property node // * with a double value and no children. // * // * @param name The name of the command. // * @param arg The double argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, double arg) const; // /** // * Execute a command with a single string argument. // * // * The command function will receive a pointer to a property node // * with a string value and no children. // * // * @param name The name of the command. // * @param arg The string argument to the command. // * @return true if the command is present and executes successfully, // * false otherwise. // */ // virtual bool execute (const string &name, string arg) const; private: typedef map<string,command_t> command_map; command_map _commands; }; #endif // __COMMANDS_HXX // end of commands.hxx <|endoftext|>
<commit_before>#include "jsonfile.hpp" #include "xmlfile.hpp" #include "world.hpp" using namespace Headway; World::World(QObject* parent) : QObject(parent) { createWorld(); } World::World(const World& other) : QObject(other.parent()), generations_(other.generations()), count_(other.count()), matrix(new Matrix<bool>(*(other.matrix))) { } World::~World() noexcept { delete matrix; } bool World::createWorld(quint32 width, quint32 height, quint64 generations) noexcept { if (width == 0) { emit error("Width must not be zero."); return false; } if (height == 0) { emit error("Height must not be zero."); return false; } if (matrix != nullptr) delete matrix; matrix = new Matrix<bool>(width, height); matrix->fill(false); generations_ = generations; emit generationsChanged(generations); count_ = 0; emit countChanged(0); return true; } bool World::loadFile(const QUrl& fileUrl) noexcept { QTemporaryFile backupFile(QDir::temp().filePath("XXXXXX.xml")); backupFile.open(); const QString backupPath = backupFile.fileName(); const QUrl backupUrl = QUrl::fromLocalFile(backupPath); QSharedPointer<File> file; const QString filePath = fileUrl.toLocalFile(); try { if (filePath.endsWith(QStringLiteral(".xml"), Qt::CaseInsensitive)) { file = QSharedPointer<File>(new XmlFile(filePath)); } else if (filePath.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive)) { file = QSharedPointer<File>(new JsonFile(filePath)); } else { emit error("Unknown file type."); return false; } if (filePath != backupPath) // if reading backup, do not overwrite it saveFile(backupUrl); if (!createWorld(file->readWidth(), file->readHeight(), file->readGenerations())) return false; while (file->hasNext()) { quint32 x, y; file->readCoordinate(x, y); createCell(x, y); } } catch (FileException& e) { if (filePath != backupPath) // if reading backup fails, do not read backup again loadFile(backupUrl); backupFile.close(); emit error(QStringLiteral("File is invalid: ") + e.error()); return false; } backupFile.close(); return true; } bool World::saveFile(const QUrl& fileUrl) noexcept { const QString filePath = fileUrl.toLocalFile(); try { if (filePath.endsWith(QStringLiteral(".xml"), Qt::CaseInsensitive)) { XmlFile::write(filePath, *this); } else if (filePath.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive)) { JsonFile::write(filePath, *this); } else { emit error("Unknown file type."); return false; } } catch (FileException& e) { emit error(e.error()); return false; } return true; } bool World::isValid(quint32 x, quint32 y) const noexcept { return x < width() && y < height(); } bool World::isAlive(quint32 x, quint32 y) const noexcept { if (!isValid(x ,y)) return false; return matrix->get(x, y); } bool World::createCell(quint32 x, quint32 y) noexcept { if (isValid(x, y) && !isAlive(x, y)) { matrix->set(x, y, true); emit countChanged(++count_); return true; } return false; } bool World::killCell(quint32 x, quint32 y) noexcept { if (isValid(x, y) && isAlive(x, y)) { matrix->set(x, y, false); emit countChanged(--count_); return true; } return false; } quint8 World::neighbors(quint32 x, quint32 y) const noexcept { quint8 amount = 0; for (quint32 b = y - 1; b <= y + 1; ++b) { for (quint32 a = x - 1; a <= x + 1; ++a) { if (y == b && x == a) continue; // ignore self if (isValid(a, b) && isAlive(a, b)) ++amount; } } return amount; } bool World::random(quint64 number) noexcept { if (number > matrix->size() - count_) { emit error("Number of cells exceeds available space."); return false; } QRandomGenerator* chaos = QRandomGenerator::global(); while (number > 0) { quint32 x = chaos->bounded(width()); quint32 y = chaos->bounded(height()); if (createCell(x, y)) // if cell did not exist --number; } return true; } void World::next() noexcept { Headway::Matrix<quint8> cache(width(), height()); // store neighbor information for (quint32 y = 0; y < height(); ++y) { for (quint32 x = 0; x < width(); ++x) { quint8 n = neighbors(x, y); cache.set(x, y, n); } } blockSignals(true); // emit countChanged only once for (quint32 y = 0; y < height(); ++y) { for (quint32 x = 0; x < width(); ++x) { quint8 n = cache.get(x, y); if (n <= 1 || n >= 4) killCell(x, y); else if (n == 3) createCell(x, y); } } blockSignals(false); emit countChanged(count_); emit generationsChanged(++generations_); } bool World::operator==(const World& other) const { return *matrix == *(other.matrix) && generations_ == other.generations_ && count_ == other.count_; } bool World::operator!=(const World& other) const { return !(*this == other); } <commit_msg>remove overengineered backup routine<commit_after>#include "jsonfile.hpp" #include "xmlfile.hpp" #include "world.hpp" using namespace Headway; World::World(QObject* parent) : QObject(parent) { createWorld(); } World::World(const World& other) : QObject(other.parent()), generations_(other.generations()), count_(other.count()), matrix(new Matrix<bool>(*(other.matrix))) { } World::~World() noexcept { delete matrix; } bool World::createWorld(quint32 width, quint32 height, quint64 generations) noexcept { if (width == 0) { emit error("Width must not be zero."); return false; } if (height == 0) { emit error("Height must not be zero."); return false; } if (matrix != nullptr) delete matrix; matrix = new Matrix<bool>(width, height); matrix->fill(false); generations_ = generations; emit generationsChanged(generations); count_ = 0; emit countChanged(0); return true; } bool World::loadFile(const QUrl& fileUrl) noexcept { QSharedPointer<File> file; const QString filePath = fileUrl.toLocalFile(); try { if (filePath.endsWith(QStringLiteral(".xml"), Qt::CaseInsensitive)) { file = QSharedPointer<File>(new XmlFile(filePath)); } else if (filePath.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive)) { file = QSharedPointer<File>(new JsonFile(filePath)); } else { emit error("Unknown file type."); return false; } if (!createWorld(file->readWidth(), file->readHeight(), file->readGenerations())) return false; while (file->hasNext()) { quint32 x, y; file->readCoordinate(x, y); createCell(x, y); } } catch (FileException& e) { emit error(QStringLiteral("File is invalid: ") + e.error()); return false; } return true; } bool World::saveFile(const QUrl& fileUrl) noexcept { const QString filePath = fileUrl.toLocalFile(); try { if (filePath.endsWith(QStringLiteral(".xml"), Qt::CaseInsensitive)) { XmlFile::write(filePath, *this); } else if (filePath.endsWith(QStringLiteral(".json"), Qt::CaseInsensitive)) { JsonFile::write(filePath, *this); } else { emit error("Unknown file type."); return false; } } catch (FileException& e) { emit error(e.error()); return false; } return true; } bool World::isValid(quint32 x, quint32 y) const noexcept { return x < width() && y < height(); } bool World::isAlive(quint32 x, quint32 y) const noexcept { if (!isValid(x ,y)) return false; return matrix->get(x, y); } bool World::createCell(quint32 x, quint32 y) noexcept { if (isValid(x, y) && !isAlive(x, y)) { matrix->set(x, y, true); emit countChanged(++count_); return true; } return false; } bool World::killCell(quint32 x, quint32 y) noexcept { if (isValid(x, y) && isAlive(x, y)) { matrix->set(x, y, false); emit countChanged(--count_); return true; } return false; } quint8 World::neighbors(quint32 x, quint32 y) const noexcept { quint8 amount = 0; for (quint32 b = y - 1; b <= y + 1; ++b) { for (quint32 a = x - 1; a <= x + 1; ++a) { if (y == b && x == a) continue; // ignore self if (isValid(a, b) && isAlive(a, b)) ++amount; } } return amount; } bool World::random(quint64 number) noexcept { if (number > matrix->size() - count_) { emit error("Number of cells exceeds available space."); return false; } QRandomGenerator* chaos = QRandomGenerator::global(); while (number > 0) { quint32 x = chaos->bounded(width()); quint32 y = chaos->bounded(height()); if (createCell(x, y)) // if cell did not exist --number; } return true; } void World::next() noexcept { Headway::Matrix<quint8> cache(width(), height()); // store neighbor information for (quint32 y = 0; y < height(); ++y) { for (quint32 x = 0; x < width(); ++x) { quint8 n = neighbors(x, y); cache.set(x, y, n); } } blockSignals(true); // emit countChanged only once for (quint32 y = 0; y < height(); ++y) { for (quint32 x = 0; x < width(); ++x) { quint8 n = cache.get(x, y); if (n <= 1 || n >= 4) killCell(x, y); else if (n == 3) createCell(x, y); } } blockSignals(false); emit countChanged(count_); emit generationsChanged(++generations_); } bool World::operator==(const World& other) const { return *matrix == *(other.matrix) && generations_ == other.generations_ && count_ == other.count_; } bool World::operator!=(const World& other) const { return !(*this == other); } <|endoftext|>
<commit_before>/** @file assembler.cpp * Implementation of Assembler class methods * @author Alexander Potashev * Copyright 2009 MDSP team */ #include "assembler.h" #include "operation.h" Assembler::Assembler( std::vector<SemanticUnit *> units) { this->units = units; } Assembler::~Assembler() { } std::map<unsigned int, hostUInt8> Assembler::run() { /* This variable is used to keep track of the current address in * program memory while following the sequence of semantic units */ unsigned int pc = 0; // which type is better to use here? /* map from semantic units in the source code to the current * addresses in program memory */ std::map<SemanticUnit *, unsigned int> unit_addr; /* map from label identifiers to its absolute byte addresses * in program memory */ std::map<std::string, unsigned int> label_addr; for ( int i = 0; i < (int)units.size(); i ++) { unit_addr[units[i]] = pc; if ( units[i]->type() == UNIT_LABEL) { label_addr[units[i]->str()] = pc; } else if ( units[i]->type() == UNIT_OPERATION) { pc ++; // add operation length in command memory words } } /* map from program memory byte addresses to encoded instructions * starting at those addresses */ std::map<unsigned int, ByteLine *> op_list; for ( int i = 0; i < (int)units.size(); i ++) { if ( units[i]->type() == UNIT_OPERATION) { pc = unit_addr[units[i]]; if ( op_list.find( pc) != op_list.end()) { throw; // 2 operations at the same address } op_list[pc] = encodeOperation( units[i], pc); } } /* TODO: use class MemoryModel (when it will come usable) */ /* map from byte addresses in program memory to the values * of those bytes */ std::map<unsigned int, hostUInt8> addr_byte; for ( std::map<unsigned int, ByteLine *>::iterator op = op_list.begin(); op != op_list.end(); op ++) { unsigned int start_addr = op->first * 4; // in bytes ByteLine *bytes = op->second; for ( int i = 0; i < (int)bytes->getSizeOfLine(); i ++) { if ( addr_byte.find( start_addr + i) != addr_byte.end()) { throw; // there already is a byte at this address } addr_byte[start_addr + i] = bytes->getByteVal( i); } } return addr_byte; } ByteLine *Assembler::encodeOperation( SemanticUnit *operation, unsigned int pc) { /* This method is only applicable to assembler commands */ assert( operation->type() == UNIT_OPERATION); Operation op; if ( *operation == "brm") { assert( operation->nOperands() == 2); hostUInt8 sd = 0; if ( (*operation)[0]->isIndirectGpr() && (*operation)[1]->isDirectGpr()) { sd = 1; // m(reg) -> reg } else if ( (*operation)[0]->isDirectGpr() && (*operation)[1]->isIndirectGpr()) { sd = 0; // reg -> m(reg) } else { throw; // invalid combination of opcode and operands } op.setMOVE( BRM, sd, 0, getGprNum( (*operation)[0]->str()), getGprNum( (*operation)[1]->str())); } else if ( *operation == "brr") { assert( operation->nOperands() == 2); assert( (*operation)[0]->isDirectGpr() && (*operation)[1]->isDirectGpr()); op.setMOVE( BRR, 0, 0, getGprNum( (*operation)[0]->str()), getGprNum( (*operation)[1]->str())); } else if ( *operation == "ld") { assert( operation->nOperands() == 2); assert( (*operation)[0]->isConstInt()); hostUInt8 sd = 0; if ( (*operation)[1]->isDirectGpr()) { sd = 0; // <const> -> reg } else if ( (*operation)[1]->isIndirectGpr()) { sd = 1; // <const> -> m(reg) } else { throw; // invalid combination of opcode and operands } /* LD command always has an imm16 operand */ int imm = (*operation)[0]->integer(); assert( imm >= 0 && imm <= 0xffff); hostUInt16 imm16 = (hostUInt16)imm; op.setMOVE( LD, sd, imm16, 0, getGprNum( (*operation)[1]->str())); } else if ( *operation == "add") { hostUInt8 am = 0; hostUInt8 rs1 = 0; hostUInt8 rs2 = 0; hostUInt8 rd = 0; hostUInt16 imm10 = 0; if ( operation->nOperands() == 3) { assert( (*operation)[0]->isDirectOrIndirectGpr()); assert( (*operation)[1]->isDirectOrIndirectGpr()); assert( (*operation)[2]->isDirectOrIndirectGpr()); rs1 = getGprNum( (*operation)[0]->str()); rs2 = getGprNum( (*operation)[1]->str()); rd = getGprNum( (*operation)[2]->str()); if ( (*operation)[0]->isDirectGpr() && (*operation)[1]->isDirectGpr() && (*operation)[2]->isDirectGpr()) { am = 0; // register direct (all operands are registers) } else if ( (*operation)[0]->isIndirectGpr() && (*operation)[1]->isIndirectGpr() && (*operation)[2]->isIndirectGpr()) { am = 2; // register indirect (all operands are in memory) } else { throw; // wrong operand types for 'add' } } else { throw; // wrong numbers of operands for 'add' } op.setALU( NOP, ADD, NOP, am, imm10, rs1, rs2, rd); } else { throw; } return op.encode(); } int Assembler::getGprNum( std::string id) { assert( id[0] == '%' && id[1] == 'r'); assert( isdigit( id[2])); if ( id.size() == 3) { return (int)(id[2] - '0'); } else if ( id.size() == 4) { assert( isdigit( id[3])); int x = 10 * (int)(id[2] - '0') + (int)(id[3] - '0'); assert( x <= 31); return x; } else { throw; } } <commit_msg>asm: implement 'nop' command<commit_after>/** @file assembler.cpp * Implementation of Assembler class methods * @author Alexander Potashev * Copyright 2009 MDSP team */ #include "assembler.h" #include "operation.h" Assembler::Assembler( std::vector<SemanticUnit *> units) { this->units = units; } Assembler::~Assembler() { } std::map<unsigned int, hostUInt8> Assembler::run() { /* This variable is used to keep track of the current address in * program memory while following the sequence of semantic units */ unsigned int pc = 0; // which type is better to use here? /* map from semantic units in the source code to the current * addresses in program memory */ std::map<SemanticUnit *, unsigned int> unit_addr; /* map from label identifiers to its absolute byte addresses * in program memory */ std::map<std::string, unsigned int> label_addr; for ( int i = 0; i < (int)units.size(); i ++) { unit_addr[units[i]] = pc; if ( units[i]->type() == UNIT_LABEL) { label_addr[units[i]->str()] = pc; } else if ( units[i]->type() == UNIT_OPERATION) { pc ++; // add operation length in command memory words } } /* map from program memory byte addresses to encoded instructions * starting at those addresses */ std::map<unsigned int, ByteLine *> op_list; for ( int i = 0; i < (int)units.size(); i ++) { if ( units[i]->type() == UNIT_OPERATION) { pc = unit_addr[units[i]]; if ( op_list.find( pc) != op_list.end()) { assert(0); throw; // 2 operations at the same address } op_list[pc] = encodeOperation( units[i], pc); } } /* TODO: use class MemoryModel (when it will come usable) */ /* map from byte addresses in program memory to the values * of those bytes */ std::map<unsigned int, hostUInt8> addr_byte; for ( std::map<unsigned int, ByteLine *>::iterator op = op_list.begin(); op != op_list.end(); op ++) { unsigned int start_addr = op->first * 4; // in bytes ByteLine *bytes = op->second; for ( int i = 0; i < (int)bytes->getSizeOfLine(); i ++) { if ( addr_byte.find( start_addr + i) != addr_byte.end()) { assert(0); throw; // there already is a byte at this address } addr_byte[start_addr + i] = bytes->getByteVal( i); } } return addr_byte; } ByteLine *Assembler::encodeOperation( SemanticUnit *operation, unsigned int pc) { /* This method is only applicable to assembler commands */ assert( operation->type() == UNIT_OPERATION); Operation op; if ( *operation == "brm") { assert( operation->nOperands() == 2); hostUInt8 sd = 0; if ( (*operation)[0]->isIndirectGpr() && (*operation)[1]->isDirectGpr()) { sd = 1; // m(reg) -> reg } else if ( (*operation)[0]->isDirectGpr() && (*operation)[1]->isIndirectGpr()) { sd = 0; // reg -> m(reg) } else { assert(0); throw; // invalid combination of opcode and operands } op.setMOVE( BRM, sd, 0, getGprNum( (*operation)[0]->str()), getGprNum( (*operation)[1]->str())); } else if ( *operation == "brr") { assert( operation->nOperands() == 2); assert( (*operation)[0]->isDirectGpr() && (*operation)[1]->isDirectGpr()); op.setMOVE( BRR, 0, 0, getGprNum( (*operation)[0]->str()), getGprNum( (*operation)[1]->str())); } else if ( *operation == "ld") { assert( operation->nOperands() == 2); assert( (*operation)[0]->isConstInt()); hostUInt8 sd = 0; if ( (*operation)[1]->isDirectGpr()) { sd = 0; // <const> -> reg } else if ( (*operation)[1]->isIndirectGpr()) { sd = 1; // <const> -> m(reg) } else { assert(0); throw; // invalid combination of opcode and operands } /* LD command always has an imm16 operand */ int imm = (*operation)[0]->integer(); assert( imm >= 0 && imm <= 0xffff); hostUInt16 imm16 = (hostUInt16)imm; op.setMOVE( LD, sd, imm16, 0, getGprNum( (*operation)[1]->str())); } else if ( *operation == "add") { hostUInt8 am = 0; hostUInt8 rs1 = 0; hostUInt8 rs2 = 0; hostUInt8 rd = 0; hostUInt16 imm10 = 0; if ( operation->nOperands() == 3) { assert( (*operation)[0]->isDirectOrIndirectGpr()); assert( (*operation)[1]->isDirectOrIndirectGpr()); assert( (*operation)[2]->isDirectOrIndirectGpr()); rs1 = getGprNum( (*operation)[0]->str()); rs2 = getGprNum( (*operation)[1]->str()); rd = getGprNum( (*operation)[2]->str()); if ( (*operation)[0]->isDirectGpr() && (*operation)[1]->isDirectGpr() && (*operation)[2]->isDirectGpr()) { am = 0; // register direct (all operands are registers) } else if ( (*operation)[0]->isIndirectGpr() && (*operation)[1]->isIndirectGpr() && (*operation)[2]->isIndirectGpr()) { am = 2; // register indirect (all operands are in memory) } else { assert(0); throw; // wrong operand types for 'add' } } else { assert(0); throw; // wrong numbers of operands for 'add' } op.setALU( NOP, ADD, NOP, am, imm10, rs1, rs2, rd); } else if ( *operation == "nop") { if ( operation->nOperands() != 0) { assert(0); throw; } op.setALU( NOP, NOP, NOP, 0, 0, 0, 0, 0); } else { cout << "Unknown operation: " << operation->str() << endl; throw; } return op.encode(); } int Assembler::getGprNum( std::string id) { assert( id[0] == '%' && id[1] == 'r'); assert( isdigit( id[2])); if ( id.size() == 3) { return (int)(id[2] - '0'); } else if ( id.size() == 4) { assert( isdigit( id[3])); int x = 10 * (int)(id[2] - '0') + (int)(id[3] - '0'); assert( x <= 31); return x; } else { throw; } } <|endoftext|>
<commit_before>// // overuse_detector_test.cpp // WebRTC_QoS // // Created by Volvet Zhang on 16/10/11. // Copyright © 2016年 volvet. All rights reserved. // #include <assert.h> #include <string> #include "overuse_detector_test.hpp" using namespace std; namespace webrtc { const double KRTPTimestampToMS = 1.0/90.0; std::string BandwdithState2String(BandwidthUsage state) { if( state == kBwNormal ){ return "BW Normal"; } else if ( state == kBwOverusing ) { return "BW Overusing"; } return "BW Underusning"; } OveruseDetectorTest::OveruseDetectorTest() : mRandom(123456789) { OverUseDetectorOptions options; m_pInterArrival = new InterArrival(5*90, KRTPTimestampToMS, true); m_pOveruseEstimator = new OveruseEstimator(options); m_pOveruseDetector = new OveruseDetector(options); mNow = 0; mReceiveTimestamp = 0; mRTPTimestamp = 0; } OveruseDetectorTest::~OveruseDetectorTest() { if( m_pInterArrival ){ delete m_pInterArrival; m_pInterArrival = nullptr; } if( m_pOveruseDetector ) { delete m_pOveruseDetector; m_pOveruseDetector = nullptr; } if( m_pOveruseEstimator ){ delete m_pOveruseEstimator; m_pOveruseEstimator = nullptr; } } void OveruseDetectorTest::UpdateDetector(uint32_t rtp_timestamp, int64_t receive_timestamp, size_t packet_size) { uint32_t timestamp_delta; int64_t arrive_time_delta; int size_delta; if( m_pInterArrival->ComputeDeltas(rtp_timestamp, receive_timestamp, packet_size, &timestamp_delta, &arrive_time_delta, &size_delta)) { double timestamp_delta_ms = timestamp_delta / 90.0; m_pOveruseEstimator->Update(arrive_time_delta, timestamp_delta_ms, size_delta, m_pOveruseDetector->State()); m_pOveruseDetector->Detect(m_pOveruseEstimator->offset(), timestamp_delta_ms, m_pOveruseEstimator->num_of_deltas(), receive_timestamp); } } int OveruseDetectorTest::Run100000Samples(int packets_per_frame, size_t packet_size, int mean_ms, int standard_deviation_ms) { int unique_overuse = 0; int last_overuse = -1; for( int i=0;i<1000000;i++ ){ for( int j=0;j<packets_per_frame;j++ ){ UpdateDetector(mRTPTimestamp, mReceiveTimestamp, packet_size); } mRTPTimestamp += mean_ms * 90; mNow += mean_ms; mReceiveTimestamp = std::max<int64_t>( mReceiveTimestamp, mNow + static_cast<int64_t>(mRandom.Gaussian(0, standard_deviation_ms) + 0.5) ); if( kBwOverusing == m_pOveruseDetector->State() ){ if( last_overuse + 1 != i ){ unique_overuse ++; } } } return unique_overuse; } int OveruseDetectorTest::RunUntilOveruse(int packets_per_frame, size_t packet_size, int mean_ms, int standard_deviation_ms, int drift_per_frame_ms) { for(int i=0;i<1000;i++ ){ for( int j=0;j<packets_per_frame;j++ ){ UpdateDetector(mRTPTimestamp, mReceiveTimestamp, packet_size); } mRTPTimestamp += mean_ms * 90; mNow += mean_ms*2; //+ drift_per_frame_ms; mReceiveTimestamp = std::max<int64_t>( mReceiveTimestamp, mNow + static_cast<int64_t>(mRandom.Gaussian(0, standard_deviation_ms) + 0.5) ); if( kBwOverusing == m_pOveruseDetector->State() ){ return i+1; } //printf("%s\n", BandwdithState2String(m_pOveruseDetector->State()).c_str()); } return -1; } void OveruseDetectorTest::GaussionRandom() { const static int MAX_BUCKET_SIZE = 100; int buckets[MAX_BUCKET_SIZE]; memset(buckets, 0, sizeof(buckets)); for( int i=0;i<10000;i++ ){ int index = mRandom.Gaussian(49, 10); if( index >= 0 && index < MAX_BUCKET_SIZE ){ buckets[index] ++; } } for( int i=0;i<MAX_BUCKET_SIZE;i++ ){ printf("Bucket i:%d, %d ", i, buckets[i]); } printf("\n"); } void OveruseDetectorTest::SimpleNonOveruse30fps() { size_t packet_size = 1200; uint32_t frame_duration_ms = 33; uint32_t rtp_timestamp = 10*90; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); mNow += frame_duration_ms; rtp_timestamp += frame_duration_ms * 90; assert(kBwNormal == m_pOveruseDetector->State()); //printf("%s\n", BandwdithState2String(m_pOveruseDetector->State()).c_str()); } } void OveruseDetectorTest::SimpleNonOveruseWithReceiveVariance() { size_t packet_size = 1200; uint32_t rtp_timestamp = 10*90; uint32_t frame_duration_ms = 10; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); rtp_timestamp += frame_duration_ms * 90; if( i%2 ){ mNow += frame_duration_ms - 5; } else { mNow += frame_duration_ms + 5; } assert(kBwNormal == m_pOveruseDetector->State()); } } void OveruseDetectorTest::SimpleNonOveruseWithRtpTimevariance() { uint32_t frame_duration_ms = 10; uint32_t rtp_timestamp = 10*90; size_t packet_size = 1200; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); mNow += frame_duration_ms; if( i % 2 ){ rtp_timestamp += (frame_duration_ms - 5)*90; } else { rtp_timestamp += (frame_duration_ms + 5)*90; } assert(kBwNormal == m_pOveruseDetector->State()); } } void OveruseDetectorTest::SimpleOveruse2000kbit30fps() { size_t packet_size = 1200; int packets_per_frame = 6; int frame_duration_ms = 33; int drift_per_frame_ms = 1; int sigma_ms = 0; int unique_overuse = Run100000Samples(packets_per_frame, packet_size, frame_duration_ms, sigma_ms); assert( 0 == unique_overuse ); int frames_until_overuse = RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms, sigma_ms, drift_per_frame_ms); printf("frames_until_overuse = %d\n", frames_until_overuse); assert( -1 != frames_until_overuse); } } <commit_msg>overuse case: enable drift<commit_after>// // overuse_detector_test.cpp // WebRTC_QoS // // Created by Volvet Zhang on 16/10/11. // Copyright © 2016年 volvet. All rights reserved. // #include <assert.h> #include <string> #include "overuse_detector_test.hpp" using namespace std; namespace webrtc { const double KRTPTimestampToMS = 1.0/90.0; std::string BandwdithState2String(BandwidthUsage state) { if( state == kBwNormal ){ return "BW Normal"; } else if ( state == kBwOverusing ) { return "BW Overusing"; } return "BW Underusning"; } OveruseDetectorTest::OveruseDetectorTest() : mRandom(123456789) { OverUseDetectorOptions options; m_pInterArrival = new InterArrival(5*90, KRTPTimestampToMS, true); m_pOveruseEstimator = new OveruseEstimator(options); m_pOveruseDetector = new OveruseDetector(options); mNow = 0; mReceiveTimestamp = 0; mRTPTimestamp = 0; } OveruseDetectorTest::~OveruseDetectorTest() { if( m_pInterArrival ){ delete m_pInterArrival; m_pInterArrival = nullptr; } if( m_pOveruseDetector ) { delete m_pOveruseDetector; m_pOveruseDetector = nullptr; } if( m_pOveruseEstimator ){ delete m_pOveruseEstimator; m_pOveruseEstimator = nullptr; } } void OveruseDetectorTest::UpdateDetector(uint32_t rtp_timestamp, int64_t receive_timestamp, size_t packet_size) { uint32_t timestamp_delta; int64_t arrive_time_delta; int size_delta; if( m_pInterArrival->ComputeDeltas(rtp_timestamp, receive_timestamp, packet_size, &timestamp_delta, &arrive_time_delta, &size_delta)) { double timestamp_delta_ms = timestamp_delta / 90.0; m_pOveruseEstimator->Update(arrive_time_delta, timestamp_delta_ms, size_delta, m_pOveruseDetector->State()); m_pOveruseDetector->Detect(m_pOveruseEstimator->offset(), timestamp_delta_ms, m_pOveruseEstimator->num_of_deltas(), receive_timestamp); } } int OveruseDetectorTest::Run100000Samples(int packets_per_frame, size_t packet_size, int mean_ms, int standard_deviation_ms) { int unique_overuse = 0; int last_overuse = -1; for( int i=0;i<1000000;i++ ){ for( int j=0;j<packets_per_frame;j++ ){ UpdateDetector(mRTPTimestamp, mReceiveTimestamp, packet_size); } mRTPTimestamp += mean_ms * 90; mNow += mean_ms; mReceiveTimestamp = std::max<int64_t>( mReceiveTimestamp, mNow + static_cast<int64_t>(mRandom.Gaussian(0, standard_deviation_ms) + 0.5) ); if( kBwOverusing == m_pOveruseDetector->State() ){ if( last_overuse + 1 != i ){ unique_overuse ++; } } } return unique_overuse; } int OveruseDetectorTest::RunUntilOveruse(int packets_per_frame, size_t packet_size, int mean_ms, int standard_deviation_ms, int drift_per_frame_ms) { for(int i=0;i<1000;i++ ){ for( int j=0;j<packets_per_frame;j++ ){ UpdateDetector(mRTPTimestamp, mReceiveTimestamp, packet_size); } mRTPTimestamp += mean_ms * 90; mNow += mean_ms + drift_per_frame_ms; mReceiveTimestamp = std::max<int64_t>( mReceiveTimestamp, mNow + static_cast<int64_t>(mRandom.Gaussian(0, standard_deviation_ms) + 0.5) ); if( kBwOverusing == m_pOveruseDetector->State() ){ return i+1; } //printf("%s\n", BandwdithState2String(m_pOveruseDetector->State()).c_str()); } return -1; } void OveruseDetectorTest::GaussionRandom() { const static int MAX_BUCKET_SIZE = 100; int buckets[MAX_BUCKET_SIZE]; memset(buckets, 0, sizeof(buckets)); for( int i=0;i<10000;i++ ){ int index = mRandom.Gaussian(49, 10); if( index >= 0 && index < MAX_BUCKET_SIZE ){ buckets[index] ++; } } for( int i=0;i<MAX_BUCKET_SIZE;i++ ){ printf("Bucket i:%d, %d ", i, buckets[i]); } printf("\n"); } void OveruseDetectorTest::SimpleNonOveruse30fps() { size_t packet_size = 1200; uint32_t frame_duration_ms = 33; uint32_t rtp_timestamp = 10*90; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); mNow += frame_duration_ms; rtp_timestamp += frame_duration_ms * 90; assert(kBwNormal == m_pOveruseDetector->State()); //printf("%s\n", BandwdithState2String(m_pOveruseDetector->State()).c_str()); } } void OveruseDetectorTest::SimpleNonOveruseWithReceiveVariance() { size_t packet_size = 1200; uint32_t rtp_timestamp = 10*90; uint32_t frame_duration_ms = 10; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); rtp_timestamp += frame_duration_ms * 90; if( i%2 ){ mNow += frame_duration_ms - 5; } else { mNow += frame_duration_ms + 5; } assert(kBwNormal == m_pOveruseDetector->State()); } } void OveruseDetectorTest::SimpleNonOveruseWithRtpTimevariance() { uint32_t frame_duration_ms = 10; uint32_t rtp_timestamp = 10*90; size_t packet_size = 1200; for( int i=0;i<1000;i++ ) { UpdateDetector(rtp_timestamp, mNow, packet_size); mNow += frame_duration_ms; if( i % 2 ){ rtp_timestamp += (frame_duration_ms - 5)*90; } else { rtp_timestamp += (frame_duration_ms + 5)*90; } assert(kBwNormal == m_pOveruseDetector->State()); } } void OveruseDetectorTest::SimpleOveruse2000kbit30fps() { size_t packet_size = 1200; int packets_per_frame = 6; int frame_duration_ms = 33; int drift_per_frame_ms = 1; int sigma_ms = 0; int unique_overuse = Run100000Samples(packets_per_frame, packet_size, frame_duration_ms, sigma_ms); assert( 0 == unique_overuse ); int frames_until_overuse = RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms, sigma_ms, drift_per_frame_ms); printf("frames_until_overuse = %d\n", frames_until_overuse); assert( -1 != frames_until_overuse); } } <|endoftext|>
<commit_before>/// \author A0112054Y #include "stdafx.h" #include "../../../You-Utils/log.h" #include "../../../You-DataStore/datastore.h" #include "../../../You-DataStore/transaction.h" #include "../model.h" #include "../controller.h" #include "update_task.h" namespace You { namespace QueryEngine { namespace Internal { namespace Action { namespace { using Transaction = You::DataStore::Transaction; using DataStore = You::DataStore::DataStore; using Log = You::Utils::Log; } const std::wstring UpdateTask::logCategory = Query::logCategory + L"[UpdateTask]"; std::unique_ptr<Query> UpdateTask::getReverse() { return std::unique_ptr<Query>(new UpdateTask( previous.getID(), previous.getDescription(), previous.getDeadline(), previous.getPriority(), previous.getDependencies(), previous.isCompleted())); } Task UpdateTask::buildUpdatedTask(const State& state) const { auto current = state.get().graph().getTask(this->id); auto builder = Controller::Builder::fromTask(current); #pragma region Update the fields iff it is requested if (this->description) { builder.description(this->description.get()); } if (this->deadline) { builder.deadline(this->deadline.get()); } if (this->priority) { builder.priority(this->priority.get()); } if (this->dependencies) { builder.dependencies(this->dependencies.get()); } Task newTask = builder; if (this->completed) { newTask.setCompleted(this->completed.get()); } #pragma endregion return newTask; } void UpdateTask::modifyState(State& state, const Task& task) const { Log::debug << (boost::wformat(L"%1% : Updating %2% - \"%3%\"\n") % logCategory % task.getID() % task.getDescription()).str(); Controller::Graph::updateTask(state.graph(), task); } void UpdateTask::makeTransaction(const Task& updated) const { auto serialized = Controller::Serializer::serialize(updated); Transaction t(DataStore::get().begin()); DataStore::get().put(this->id, serialized); t.commit(); } Response UpdateTask::execute(State& state) { previous = state.graph().getTask(id); auto updated = buildUpdatedTask(state); modifyState(state, updated); return updated; } } // namespace Action } // namespace Internal } // namespace QueryEngine } // namespace You <commit_msg>Fix update task bug<commit_after>/// \author A0112054Y #include "stdafx.h" #include "../../../You-Utils/log.h" #include "../../../You-DataStore/datastore.h" #include "../../../You-DataStore/transaction.h" #include "../model.h" #include "../controller.h" #include "update_task.h" namespace You { namespace QueryEngine { namespace Internal { namespace Action { namespace { using Transaction = You::DataStore::Transaction; using DataStore = You::DataStore::DataStore; using Log = You::Utils::Log; } const std::wstring UpdateTask::logCategory = Query::logCategory + L"[UpdateTask]"; std::unique_ptr<Query> UpdateTask::getReverse() { return std::unique_ptr<Query>(new UpdateTask( previous.getID(), previous.getDescription(), previous.getDeadline(), previous.getPriority(), previous.getDependencies(), previous.isCompleted())); } Task UpdateTask::buildUpdatedTask(const State& state) const { auto current = state.get().graph().getTask(this->id); auto builder = Controller::Builder::fromTask(current); #pragma region Update the fields iff it is requested if (this->description) { builder.description(this->description.get()); } if (this->deadline) { builder.deadline(this->deadline.get()); } if (this->priority) { builder.priority(this->priority.get()); } if (this->dependencies) { builder.dependencies(this->dependencies.get()); } Task newTask = builder; if (this->completed) { newTask.setCompleted(this->completed.get()); } #pragma endregion return newTask; } void UpdateTask::modifyState(State& state, const Task& task) const { Log::debug << (boost::wformat(L"%1% : Updating %2% - \"%3%\"\n") % logCategory % task.getID() % task.getDescription()).str(); Controller::Graph::updateTask(state.graph(), task); } void UpdateTask::makeTransaction(const Task& updated) const { auto serialized = Controller::Serializer::serialize(updated); Transaction t(DataStore::get().begin()); DataStore::get().put(this->id, serialized); t.commit(); } Response UpdateTask::execute(State& state) { previous = state.graph().getTask(id); auto updated = buildUpdatedTask(state); modifyState(state, updated); makeTransaction(updated); return updated; } } // namespace Action } // namespace Internal } // namespace QueryEngine } // namespace You <|endoftext|>
<commit_before>#include "cxxopts.hpp" // see https://www.gitmemory.com/issue/ddemidov/amgcl/162/668662041 for inspiration #include <amgcl/io/mm.hpp> #include <amgcl/adapter/crs_tuple.hpp> #include <amgcl/amg.hpp> #if defined(SOLVER_BACKEND_CUDA) # include <amgcl/adapter/eigen.hpp> # include <amgcl/backend/cuda.hpp> # include <amgcl/relaxation/cusparse_ilu0.hpp> using Backend = amgcl::backend::cuda<double>; #else using Backend = amgcl::backend::builtin<double>; #endif #include <amgcl/make_solver.hpp> #include <amgcl/make_block_solver.hpp> #include <amgcl/solver/bicgstab.hpp> #include <amgcl/solver/gmres.hpp> #include <amgcl/solver/runtime.hpp> #include <amgcl/preconditioner/runtime.hpp> #include <amgcl/amg.hpp> #include <amgcl/coarsening/smoothed_aggregation.hpp> #include <amgcl/coarsening/plain_aggregates.hpp> #include <amgcl/coarsening/ruge_stuben.hpp> #include <amgcl/coarsening/aggregation.hpp> #include <amgcl/relaxation/spai0.hpp> #include <amgcl/relaxation/ilu0.hpp> #include <amgcl/adapter/crs_tuple.hpp> #include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> // ./amgcl-block-matrices -A ../data/B_test.mtx -b 3 int main(int argc, char *argv[]) { //namespace po = boost::program_options; namespace io = amgcl::io; using std::vector; using std::string; cxxopts::Options options("amgcl_block_matrices", "check AMG for different block sizes"); options .allow_unrecognised_options() .add_options() ("A,matrix", "System matrix in the MatrixMarket format.", cxxopts::value<std::string>()) ("b,block-size", "The block size of the system matrix. ", cxxopts::value<int>()->default_value("1")) ("h,help", "Print help") ; auto vm = options.parse(argc, argv); if (vm.count("help")) { std::cout << options.help() << std::endl; return 0; } for (int i = 0; i < argc; ++i) { if (i) std::cout << " "; std::cout << argv[i]; } std::cout << std::endl; boost::property_tree::ptree prm; if (vm.count("prm-file")) { read_json(vm["prm-file"].as<string>(), prm); } if (vm.count("prm")) { for(const string &v : vm["prm"].as<vector<string>>()) { amgcl::put(prm, v); } } size_t n, block_size = 1; vector<ptrdiff_t> ptr, col; vector<double> val; if (vm.count("block-size")) { block_size = vm["block-size"].as<int>(); } if (vm.count("matrix")) { string Afile = vm["matrix"].as<string>(); auto [rows, cols] = io::mm_reader(Afile)(ptr, col, val); std::cout << "rows: " << rows << std::endl; std::cout << "cols: " << cols << std::endl; n = rows; } // We use the tuple of CRS arrays to represent the system matrix. // Note that std::tie creates a tuple of references, so no data is actually // copied here: auto A = std::tie(n, ptr, col, val); std::vector<double> rhs (n, 0.0); std::vector<double> x (n, 0.0); // Set RHS := Ax where x = 1 for (size_t i = 0; i < n; ++i) { double s = 0; for (ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) { s += val[j]; } rhs[i] = s; } if (block_size == 1) { // scalar case using Solver1 = amgcl::make_solver< amgcl::runtime::preconditioner<Backend>, amgcl::runtime::solver::wrapper<Backend>>; //using Solver2 = amgcl::make_block_solver< using Solver2 = amgcl::make_solver< // Use AMG as preconditioner: amgcl::amg< Backend, amgcl::coarsening::smoothed_aggregation, amgcl::relaxation::spai0 >, // And BiCGStab as iterative solver: amgcl::solver::bicgstab<Backend>>; using Solver3 = amgcl::make_solver< // Use AMG as preconditioner: amgcl::amg< Backend, amgcl::coarsening::ruge_stuben, amgcl::relaxation::spai0 //amgcl::relaxation::ilu0 >, // And GMRES as iterative solver: amgcl::solver::gmres<Backend>>; try { Solver2::params prm; Solver2::backend_params bprm; // prm.precond.direct_coarse = false; prm.precond.direct_coarse = true; prm.solver.maxiter = 1200; prm.solver.verbose = true; //prm.precond.coarsening ... Solver2 solve( A, prm, bprm ); auto f_b = Backend::copy_vector(rhs, bprm); auto x_b = Backend::copy_vector(x, bprm); //auto [iters, error] = solve(A, rhs, x); auto [iters, error] = solve(A, *f_b, *x_b); #if defined(SOLVER_BACKEND_VEXCL) vex::copy(*x_b, x); #elif defined(SOLVER_BACKEND_VIENNACL) viennacl::fast_copy(*x_b, x); #elif defined(SOLVER_BACKEND_CUDA) thrust::copy(x_b->begin(), x_b->end(), x.begin()); #else std::copy(&(*x_b)[0], &(*x_b)[0] + n, &x[0]); #endif // Output the number of iterations, the relative error: std::cout << "Iters: " << iters << std::endl << "Error: " << error << std::endl; // std::cout << "x = [ "; // for (auto el : x) { // std::cout << el << ", "; // } // std::cout << "]\n"; } catch(std::runtime_error &e) { std::cout << "caught exception: " << e.what() << std::endl; } } else { // Compose the solver type using dmat_type = amgcl::static_matrix<double, 3, 3>; using dvec_type = amgcl::static_matrix<double, 3, 1>; using SBackend = amgcl::backend::builtin<double>; // the outer iterative solver backend using PBackend = amgcl::backend::builtin<float>; // the PSolver backend using UBackend = amgcl::backend::builtin<dmat_type>; // the USolver backend using BlockSolver = amgcl::make_block_solver< // preconditioner amgcl::amg< UBackend, amgcl::coarsening::aggregation, amgcl::relaxation::ilu0 >, // solver amgcl::solver::gmres<UBackend>>; using Solver = amgcl::make_solver< // preconditioner amgcl::amg< UBackend, amgcl::coarsening::aggregation, amgcl::relaxation::ilu0 >, // solver amgcl::solver::gmres<UBackend>>; try { // see `tutorial/3.CoupCons3D/coupcons3d.cpp` #if 0 BlockSolver::params prm; prm.solver.maxiter = 1200; prm.solver.verbose = true; BlockSolver::backend_params bprm; prm.precond.direct_coarse = false; auto Ab = amgcl::adapter::block_matrix<dmat_type>(A); auto rhsb = reinterpret_cast<dvec_type*>(rhs.data()); auto xb = reinterpret_cast<dvec_type*>(x.data()); auto RHS = amgcl::make_iterator_range(rhsb, rhsb + n / 3); auto X = amgcl::make_iterator_range(xb, xb + n / block_size); Solver solve0( Ab, prm, bprm ); auto [iters0, error0] = solve0(Ab, RHS, X); std::cout << "Iters0: " << iters0 << std::endl << "Error0: " << error0 << std::endl; BlockSolver solve( A, prm, bprm ); auto [iters, error] = solve(A, rhs, x); std::cout << "Iters: " << iters << std::endl << "Error: " << error << std::endl; // std::cout << "x = [ "; // for (auto el : x) { // std::cout << el << ", "; // } // std::cout << "]\n"; #endif } catch(std::runtime_error &e) { std::cout << "caught exception: " << e.what() << std::endl; } } } <commit_msg>added `cusparse` initialization<commit_after>#include "cxxopts.hpp" // see https://www.gitmemory.com/issue/ddemidov/amgcl/162/668662041 for inspiration #include <amgcl/io/mm.hpp> #include <amgcl/adapter/crs_tuple.hpp> #include <amgcl/amg.hpp> #if defined(SOLVER_BACKEND_CUDA) # include <amgcl/adapter/eigen.hpp> # include <amgcl/backend/cuda.hpp> # include <amgcl/relaxation/cusparse_ilu0.hpp> using Backend = amgcl::backend::cuda<double>; #else using Backend = amgcl::backend::builtin<double>; #endif #include <amgcl/make_solver.hpp> #include <amgcl/make_block_solver.hpp> #include <amgcl/solver/bicgstab.hpp> #include <amgcl/solver/gmres.hpp> #include <amgcl/solver/runtime.hpp> #include <amgcl/preconditioner/runtime.hpp> #include <amgcl/amg.hpp> #include <amgcl/coarsening/smoothed_aggregation.hpp> #include <amgcl/coarsening/plain_aggregates.hpp> #include <amgcl/coarsening/ruge_stuben.hpp> #include <amgcl/coarsening/aggregation.hpp> #include <amgcl/relaxation/spai0.hpp> #include <amgcl/relaxation/ilu0.hpp> #include <amgcl/adapter/crs_tuple.hpp> #include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> // ./amgcl-block-matrices -A ../data/B_test.mtx -b 3 int main(int argc, char *argv[]) { //namespace po = boost::program_options; namespace io = amgcl::io; using std::vector; using std::string; cxxopts::Options options("amgcl_block_matrices", "check AMG for different block sizes"); options .allow_unrecognised_options() .add_options() ("A,matrix", "System matrix in the MatrixMarket format.", cxxopts::value<std::string>()) ("b,block-size", "The block size of the system matrix. ", cxxopts::value<int>()->default_value("1")) ("h,help", "Print help") ; auto vm = options.parse(argc, argv); if (vm.count("help")) { std::cout << options.help() << std::endl; return 0; } for (int i = 0; i < argc; ++i) { if (i) std::cout << " "; std::cout << argv[i]; } std::cout << std::endl; boost::property_tree::ptree prm; if (vm.count("prm-file")) { read_json(vm["prm-file"].as<string>(), prm); } if (vm.count("prm")) { for(const string &v : vm["prm"].as<vector<string>>()) { amgcl::put(prm, v); } } size_t n, block_size = 1; vector<ptrdiff_t> ptr, col; vector<double> val; if (vm.count("block-size")) { block_size = vm["block-size"].as<int>(); } if (vm.count("matrix")) { string Afile = vm["matrix"].as<string>(); auto [rows, cols] = io::mm_reader(Afile)(ptr, col, val); std::cout << "rows: " << rows << std::endl; std::cout << "cols: " << cols << std::endl; n = rows; } // We use the tuple of CRS arrays to represent the system matrix. // Note that std::tie creates a tuple of references, so no data is actually // copied here: auto A = std::tie(n, ptr, col, val); std::vector<double> rhs (n, 0.0); std::vector<double> x (n, 0.0); // Set RHS := Ax where x = 1 for (size_t i = 0; i < n; ++i) { double s = 0; for (ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) { s += val[j]; } rhs[i] = s; } if (block_size == 1) { // scalar case using Solver1 = amgcl::make_solver< amgcl::runtime::preconditioner<Backend>, amgcl::runtime::solver::wrapper<Backend>>; //using Solver2 = amgcl::make_block_solver< using Solver2 = amgcl::make_solver< // Use AMG as preconditioner: amgcl::amg< Backend, amgcl::coarsening::smoothed_aggregation, amgcl::relaxation::spai0 >, // And BiCGStab as iterative solver: amgcl::solver::bicgstab<Backend>>; using Solver3 = amgcl::make_solver< // Use AMG as preconditioner: amgcl::amg< Backend, amgcl::coarsening::ruge_stuben, amgcl::relaxation::spai0 //amgcl::relaxation::ilu0 >, // And GMRES as iterative solver: amgcl::solver::gmres<Backend>>; try { Solver2::params prm; Solver2::backend_params bprm; // prm.precond.direct_coarse = false; prm.precond.direct_coarse = true; prm.solver.maxiter = 1200; prm.solver.verbose = true; //prm.precond.coarsening ... #if defined(SOLVER_BACKEND_VEXCL) vex::Context ctx(vex::Filter::Env); std::cout << ctx << std::endl; bprm.q = ctx; #elif defined(SOLVER_BACKEND_VIENNACL) std::cout << viennacl::ocl::current_device().name() << " (" << viennacl::ocl::current_device().vendor() << ")\n\n"; #elif defined(SOLVER_BACKEND_CUDA) cusparseCreate(&bprm.cusparse_handle); { int dev; cudaGetDevice(&dev); cudaDeviceProp prop; cudaGetDeviceProperties(&prop, dev); std::cout << prop.name << std::endl << std::endl; } #endif Solver2 solve( A, prm, bprm ); auto f_b = Backend::copy_vector(rhs, bprm); auto x_b = Backend::copy_vector(x, bprm); //auto [iters, error] = solve(A, rhs, x); auto [iters, error] = solve(A, *f_b, *x_b); #if defined(SOLVER_BACKEND_VEXCL) vex::copy(*x_b, x); #elif defined(SOLVER_BACKEND_VIENNACL) viennacl::fast_copy(*x_b, x); #elif defined(SOLVER_BACKEND_CUDA) thrust::copy(x_b->begin(), x_b->end(), x.begin()); #else std::copy(&(*x_b)[0], &(*x_b)[0] + n, &x[0]); #endif // Output the number of iterations, the relative error: std::cout << "Iters: " << iters << std::endl << "Error: " << error << std::endl; // std::cout << "x = [ "; // for (auto el : x) { // std::cout << el << ", "; // } // std::cout << "]\n"; } catch(std::runtime_error &e) { std::cout << "caught exception: " << e.what() << std::endl; } } else { // Compose the solver type using dmat_type = amgcl::static_matrix<double, 3, 3>; using dvec_type = amgcl::static_matrix<double, 3, 1>; using SBackend = amgcl::backend::builtin<double>; // the outer iterative solver backend using PBackend = amgcl::backend::builtin<float>; // the PSolver backend using UBackend = amgcl::backend::builtin<dmat_type>; // the USolver backend using BlockSolver = amgcl::make_block_solver< // preconditioner amgcl::amg< UBackend, amgcl::coarsening::aggregation, amgcl::relaxation::ilu0 >, // solver amgcl::solver::gmres<UBackend>>; using Solver = amgcl::make_solver< // preconditioner amgcl::amg< UBackend, amgcl::coarsening::aggregation, amgcl::relaxation::ilu0 >, // solver amgcl::solver::gmres<UBackend>>; try { // see `tutorial/3.CoupCons3D/coupcons3d.cpp` #if 0 BlockSolver::params prm; prm.solver.maxiter = 1200; prm.solver.verbose = true; BlockSolver::backend_params bprm; prm.precond.direct_coarse = false; auto Ab = amgcl::adapter::block_matrix<dmat_type>(A); auto rhsb = reinterpret_cast<dvec_type*>(rhs.data()); auto xb = reinterpret_cast<dvec_type*>(x.data()); auto RHS = amgcl::make_iterator_range(rhsb, rhsb + n / 3); auto X = amgcl::make_iterator_range(xb, xb + n / block_size); Solver solve0( Ab, prm, bprm ); auto [iters0, error0] = solve0(Ab, RHS, X); std::cout << "Iters0: " << iters0 << std::endl << "Error0: " << error0 << std::endl; BlockSolver solve( A, prm, bprm ); auto [iters, error] = solve(A, rhs, x); std::cout << "Iters: " << iters << std::endl << "Error: " << error << std::endl; // std::cout << "x = [ "; // for (auto el : x) { // std::cout << el << ", "; // } // std::cout << "]\n"; #endif } catch(std::runtime_error &e) { std::cout << "caught exception: " << e.what() << std::endl; } } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2012 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mixer.cpp * * Control channel input/output mixer and failsafe. */ #include <nuttx/config.h> #include <nuttx/arch.h> #include <sys/types.h> #include <stdbool.h> #include <string.h> #include <assert.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <drivers/drv_pwm_output.h> #include <systemlib/mixer/mixer.h> extern "C" { //#define DEBUG #include "px4io.h" } /* * Count of periodic calls in which we have no FMU input. */ static unsigned fmu_input_drops; #define FMU_INPUT_DROP_LIMIT 20 /* current servo arm/disarm state */ bool mixer_servos_armed = false; /* selected control values and count for mixing */ static uint16_t *control_values; static int control_count; static int mixer_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &control); static MixerGroup mixer_group(mixer_callback, 0); void mixer_tick(void) { bool should_arm; /* * Decide which set of inputs we're using. */ if (system_state.mixer_use_fmu) { /* we have recent control data from the FMU */ control_count = PX4IO_CONTROL_CHANNELS; control_values = &system_state.fmu_channel_data[0]; /* check that we are receiving fresh data from the FMU */ if (!system_state.fmu_data_received) { fmu_input_drops++; /* too many frames without FMU input, time to go to failsafe */ if (fmu_input_drops >= FMU_INPUT_DROP_LIMIT) { system_state.mixer_use_fmu = false; } } else { fmu_input_drops = 0; system_state.fmu_data_received = false; } } else if (system_state.rc_channels > 0) { /* we have control data from an R/C input */ control_count = system_state.rc_channels; control_values = &system_state.rc_channel_data[0]; } else { /* we have no control input */ /* XXX builtin failsafe would activate here */ control_count = 0; } /* * Run the mixers if we have any control data at all. */ if (control_count > 0) { float outputs[IO_SERVO_COUNT]; unsigned mixed; /* mix */ mixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT); /* scale to PWM and update the servo outputs as required */ for (unsigned i = 0; i < IO_SERVO_COUNT; i++) { if (i < mixed) { /* scale to servo output */ system_state.servos[i] = (outputs[i] * 500.0f) + 1500; } else { /* set to zero to inhibit PWM pulse output */ system_state.servos[i] = 0; } /* * If we are armed, update the servo output. */ if (system_state.armed && system_state.arm_ok) up_pwm_servo_set(i, system_state.servos[i]); } } /* * Decide whether the servos should be armed right now. */ should_arm = system_state.armed && system_state.arm_ok && (control_count > 0); if (should_arm && !mixer_servos_armed) { /* need to arm, but not armed */ up_pwm_servo_arm(true); mixer_servos_armed = true; } else if (!should_arm && mixer_servos_armed) { /* armed but need to disarm */ up_pwm_servo_arm(false); mixer_servos_armed = false; } } static int mixer_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &control) { /* if the control index refers to an input that's not valid, we can't return it */ if (control_index >= control_count) return -1; /* scale from current PWM units (1000-2000) to mixer input values */ control = ((float)control_values[control_index] - 1500.0f) / 500.0f; return 0; } static char mixer_text[256]; static unsigned mixer_text_length = 0; void mixer_handle_text(const void *buffer, size_t length) { px4io_mixdata *msg = (px4io_mixdata *)buffer; debug("mixer text %u", length); if (length < sizeof(px4io_mixdata)) return; unsigned text_length = length - sizeof(px4io_mixdata); switch (msg->action) { case F2I_MIXER_ACTION_RESET: debug("reset"); mixer_group.reset(); mixer_text_length = 0; /* FALLTHROUGH */ case F2I_MIXER_ACTION_APPEND: debug("append %d", length); /* check for overflow - this is really fatal */ if ((mixer_text_length + text_length + 1) > sizeof(mixer_text)) return; /* append mixer text and nul-terminate */ memcpy(&mixer_text[mixer_text_length], msg->text, text_length); mixer_text_length += text_length; mixer_text[mixer_text_length] = '\0'; debug("buflen %u", mixer_text_length); /* process the text buffer, adding new mixers as their descriptions can be parsed */ unsigned resid = mixer_text_length; mixer_group.load_from_buf(&mixer_text[0], resid); /* if anything was parsed */ if (resid != mixer_text_length) { debug("used %u", mixer_text_length - resid); /* copy any leftover text to the base of the buffer for re-use */ if (resid > 0) memcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid); mixer_text_length = resid; } break; } }<commit_msg>Removed text reuse, causing crash with stack trace<commit_after>/**************************************************************************** * * Copyright (C) 2012 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mixer.cpp * * Control channel input/output mixer and failsafe. */ #include <nuttx/config.h> #include <nuttx/arch.h> #include <sys/types.h> #include <stdbool.h> #include <string.h> #include <assert.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <drivers/drv_pwm_output.h> #include <systemlib/mixer/mixer.h> extern "C" { //#define DEBUG #include "px4io.h" } /* * Count of periodic calls in which we have no FMU input. */ static unsigned fmu_input_drops; #define FMU_INPUT_DROP_LIMIT 20 /* current servo arm/disarm state */ bool mixer_servos_armed = false; /* selected control values and count for mixing */ static uint16_t *control_values; static int control_count; static int mixer_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &control); static MixerGroup mixer_group(mixer_callback, 0); void mixer_tick(void) { bool should_arm; /* * Decide which set of inputs we're using. */ if (system_state.mixer_use_fmu) { /* we have recent control data from the FMU */ control_count = PX4IO_CONTROL_CHANNELS; control_values = &system_state.fmu_channel_data[0]; /* check that we are receiving fresh data from the FMU */ if (!system_state.fmu_data_received) { fmu_input_drops++; /* too many frames without FMU input, time to go to failsafe */ if (fmu_input_drops >= FMU_INPUT_DROP_LIMIT) { system_state.mixer_use_fmu = false; } } else { fmu_input_drops = 0; system_state.fmu_data_received = false; } } else if (system_state.rc_channels > 0) { /* we have control data from an R/C input */ control_count = system_state.rc_channels; control_values = &system_state.rc_channel_data[0]; } else { /* we have no control input */ /* XXX builtin failsafe would activate here */ control_count = 0; } /* * Run the mixers if we have any control data at all. */ if (control_count > 0) { float outputs[IO_SERVO_COUNT]; unsigned mixed; /* mix */ mixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT); /* scale to PWM and update the servo outputs as required */ for (unsigned i = 0; i < IO_SERVO_COUNT; i++) { if (i < mixed) { /* scale to servo output */ system_state.servos[i] = (outputs[i] * 500.0f) + 1500; } else { /* set to zero to inhibit PWM pulse output */ system_state.servos[i] = 0; } /* * If we are armed, update the servo output. */ if (system_state.armed && system_state.arm_ok) up_pwm_servo_set(i, system_state.servos[i]); } } /* * Decide whether the servos should be armed right now. */ should_arm = system_state.armed && system_state.arm_ok && (control_count > 0); if (should_arm && !mixer_servos_armed) { /* need to arm, but not armed */ up_pwm_servo_arm(true); mixer_servos_armed = true; } else if (!should_arm && mixer_servos_armed) { /* armed but need to disarm */ up_pwm_servo_arm(false); mixer_servos_armed = false; } } static int mixer_callback(uintptr_t handle, uint8_t control_group, uint8_t control_index, float &control) { /* if the control index refers to an input that's not valid, we can't return it */ if (control_index >= control_count) return -1; /* scale from current PWM units (1000-2000) to mixer input values */ control = ((float)control_values[control_index] - 1500.0f) / 500.0f; return 0; } static char mixer_text[256]; static unsigned mixer_text_length = 0; void mixer_handle_text(const void *buffer, size_t length) { px4io_mixdata *msg = (px4io_mixdata *)buffer; debug("mixer text %u", length); if (length < sizeof(px4io_mixdata)) return; unsigned text_length = length - sizeof(px4io_mixdata); switch (msg->action) { case F2I_MIXER_ACTION_RESET: debug("reset"); mixer_group.reset(); mixer_text_length = 0; /* FALLTHROUGH */ case F2I_MIXER_ACTION_APPEND: debug("append %d", length); /* check for overflow - this is really fatal */ if ((mixer_text_length + text_length + 1) > sizeof(mixer_text)) return; /* append mixer text and nul-terminate */ memcpy(&mixer_text[mixer_text_length], msg->text, text_length); mixer_text_length += text_length; mixer_text[mixer_text_length] = '\0'; debug("buflen %u", mixer_text_length); /* process the text buffer, adding new mixers as their descriptions can be parsed */ unsigned resid = mixer_text_length; mixer_group.load_from_buf(&mixer_text[0], resid); /* if anything was parsed */ if (resid != mixer_text_length) { debug("used %u", mixer_text_length - resid); // copy any leftover text to the base of the buffer for re-use // if (resid > 0) // memcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid); // mixer_text_length = resid; } break; } }<|endoftext|>
<commit_before>// // AmstradCPC.cpp // Clock Signal // // Created by Thomas Harte on 30/07/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include "../../Storage/Disk/Parsers/CPM.hpp" #include "../../Storage/Disk/Encodings/MFM.hpp" static bool strcmp_insensitive(const char *a, const char *b) { if(strlen(a) != strlen(b)) return false; while(*a) { if(tolower(*a) != towlower(*b)) return false; a++; b++; } return true; } static bool is_implied_extension(const std::string &extension) { return extension == " " || strcmp_insensitive(extension.c_str(), "BAS") || strcmp_insensitive(extension.c_str(), "BIN"); } static void right_trim(std::string &string) { string.erase(std::find_if(string.rbegin(), string.rend(), [](int ch) { return !std::isspace(ch); }).base(), string.end()); } static std::string RunCommandFor(const Storage::Disk::CPM::File &file) { // Trim spaces from the name. std::string name = file.name; right_trim(name); // Form the basic command. std::string command = "run\"" + name; // Consider whether the extension is required. if(!is_implied_extension(file.type)) { std::string type = file.type; right_trim(type); command += "." + type; } // Add a newline and return. return command + "\n"; } static void InspectCatalogue( const Storage::Disk::CPM::Catalogue &catalogue, StaticAnalyser::Target &target) { std::vector<Storage::Disk::CPM::File> candidate_files = catalogue.files; // Remove all files with untypable characters. candidate_files.erase( std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File &file) { for(auto c : file.name + file.type) { if(c < 32) return true; } return false; }), candidate_files.end()); // If that leaves a mix of 'system' (i.e. hidden) and non-system files, remove the system files. bool are_all_system = true; for(auto &file : candidate_files) { if(!file.system) { are_all_system = false; break; } } if(!are_all_system) { candidate_files.erase( std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File &file) { return file.system; }), candidate_files.end()); } // If there's just one file, run that. if(candidate_files.size() == 1) { target.loadingCommand = RunCommandFor(candidate_files[0]); return; } // If only one file is [potentially] BASIC, run that one; otherwise if only one has a suffix // that AMSDOS allows to be omitted, pick that one. int basic_files = 0; int implicit_suffixed_files = 0; size_t last_basic_file = 0; size_t last_implicit_suffixed_file = 0; for(size_t c = 0; c < candidate_files.size(); c++) { // Files with nothing but spaces in their name can't be loaded by the user, so disregard them. if(candidate_files[c].type == " " && candidate_files[c].name == " ") continue; // Check for whether this is [potentially] BASIC. if(candidate_files[c].data.size() >= 128 && !((candidate_files[c].data[18] >> 1) & 7)) { basic_files++; last_basic_file = c; } // Check suffix for emptiness. if(is_implied_extension(candidate_files[c].type)) { implicit_suffixed_files++; last_implicit_suffixed_file = c; } } if(basic_files == 1 || implicit_suffixed_files == 1) { size_t selected_file = (basic_files == 1) ? last_basic_file : last_implicit_suffixed_file; target.loadingCommand = RunCommandFor(candidate_files[selected_file]); return; } // One more guess: if only one remaining candidate file has a different name than the others, // assume it is intended to stand out. std::map<std::string, int> name_counts; std::map<std::string, size_t> indices_by_name; size_t index = 0; for(auto &file : candidate_files) { name_counts[file.name]++; indices_by_name[file.name] = index; index++; } if(name_counts.size() == 2) { for(auto &pair : name_counts) { if(pair.second == 1) { target.loadingCommand = RunCommandFor(candidate_files[indices_by_name[pair.first]]); return; } } } // Desperation. target.loadingCommand = "cat\n"; } static bool CheckBootSector(const std::shared_ptr<Storage::Disk::Disk> &disk, StaticAnalyser::Target &target) { Storage::Encodings::MFM::Parser parser(true, disk); std::shared_ptr<Storage::Encodings::MFM::Sector> boot_sector = parser.get_sector(0, 0, 0x41); if(boot_sector != nullptr) { // Check that the first 64 bytes of the sector aren't identical; if they are then probably // this disk was formatted and the filler byte never replaced. bool matched = true; for(size_t c = 1; c < 64; c++) { if(boot_sector->data[c] != boot_sector->data[0]) { matched = false; break; } } // This is a system disk, then launch it as though it were CP/M. if(!matched) { target.loadingCommand = "|cpm\n"; return true; } } return false; } void StaticAnalyser::AmstradCPC::AddTargets(const Media &media, std::list<Target> &destination) { Target target; target.machine = Target::AmstradCPC; target.probability = 1.0; target.media.disks = media.disks; target.media.tapes = media.tapes; target.media.cartridges = media.cartridges; target.amstradcpc.model = AmstradCPCModel::CPC6128; if(!target.media.tapes.empty()) { // Ugliness flows here: assume the CPC isn't smart enough to pause between pressing // enter and responding to the follow-on prompt to press a key, so just type for // a while. Yuck! target.loadingCommand = "|tape\nrun\"\n1234567890"; } if(!target.media.disks.empty()) { Storage::Disk::CPM::ParameterBlock data_format; data_format.sectors_per_track = 9; data_format.tracks = 40; data_format.block_size = 1024; data_format.first_sector = 0xc1; data_format.catalogue_allocation_bitmap = 0xc000; data_format.reserved_tracks = 0; std::unique_ptr<Storage::Disk::CPM::Catalogue> data_catalogue = Storage::Disk::CPM::GetCatalogue(target.media.disks.front(), data_format); if(data_catalogue) { InspectCatalogue(*data_catalogue, target); } else { if(!CheckBootSector(target.media.disks.front(), target)) { Storage::Disk::CPM::ParameterBlock system_format; system_format.sectors_per_track = 9; system_format.tracks = 40; system_format.block_size = 1024; system_format.first_sector = 0x41; system_format.catalogue_allocation_bitmap = 0xc000; system_format.reserved_tracks = 2; std::unique_ptr<Storage::Disk::CPM::Catalogue> system_catalogue = Storage::Disk::CPM::GetCatalogue(target.media.disks.front(), system_format); if(system_catalogue) { InspectCatalogue(*system_catalogue, target); } } } } destination.push_back(target); } <commit_msg>Switches the CPC static analyser to maintaining a vector of pointers rather than a complete copy of files.<commit_after>// // AmstradCPC.cpp // Clock Signal // // Created by Thomas Harte on 30/07/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include "../../Storage/Disk/Parsers/CPM.hpp" #include "../../Storage/Disk/Encodings/MFM.hpp" static bool strcmp_insensitive(const char *a, const char *b) { if(strlen(a) != strlen(b)) return false; while(*a) { if(tolower(*a) != towlower(*b)) return false; a++; b++; } return true; } static bool is_implied_extension(const std::string &extension) { return extension == " " || strcmp_insensitive(extension.c_str(), "BAS") || strcmp_insensitive(extension.c_str(), "BIN"); } static void right_trim(std::string &string) { string.erase(std::find_if(string.rbegin(), string.rend(), [](int ch) { return !std::isspace(ch); }).base(), string.end()); } static std::string RunCommandFor(const Storage::Disk::CPM::File &file) { // Trim spaces from the name. std::string name = file.name; right_trim(name); // Form the basic command. std::string command = "run\"" + name; // Consider whether the extension is required. if(!is_implied_extension(file.type)) { std::string type = file.type; right_trim(type); command += "." + type; } // Add a newline and return. return command + "\n"; } static void InspectCatalogue( const Storage::Disk::CPM::Catalogue &catalogue, StaticAnalyser::Target &target) { std::vector<const Storage::Disk::CPM::File *> candidate_files; candidate_files.reserve(catalogue.files.size()); for(auto &file : catalogue.files) { candidate_files.push_back(&file); } // Remove all files with untypable characters. candidate_files.erase( std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File *file) { for(auto c : file->name + file->type) { if(c < 32) return true; } return false; }), candidate_files.end()); // If that leaves a mix of 'system' (i.e. hidden) and non-system files, remove the system files. bool are_all_system = true; for(auto file : candidate_files) { if(!file->system) { are_all_system = false; break; } } if(!are_all_system) { candidate_files.erase( std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File *file) { return file->system; }), candidate_files.end()); } // If there's just one file, run that. if(candidate_files.size() == 1) { target.loadingCommand = RunCommandFor(*candidate_files[0]); return; } // If only one file is [potentially] BASIC, run that one; otherwise if only one has a suffix // that AMSDOS allows to be omitted, pick that one. int basic_files = 0; int implicit_suffixed_files = 0; size_t last_basic_file = 0; size_t last_implicit_suffixed_file = 0; for(size_t c = 0; c < candidate_files.size(); c++) { // Files with nothing but spaces in their name can't be loaded by the user, so disregard them. if(candidate_files[c]->type == " " && candidate_files[c]->name == " ") continue; // Check for whether this is [potentially] BASIC. if(candidate_files[c]->data.size() >= 128 && !((candidate_files[c]->data[18] >> 1) & 7)) { basic_files++; last_basic_file = c; } // Check suffix for emptiness. if(is_implied_extension(candidate_files[c]->type)) { implicit_suffixed_files++; last_implicit_suffixed_file = c; } } if(basic_files == 1 || implicit_suffixed_files == 1) { size_t selected_file = (basic_files == 1) ? last_basic_file : last_implicit_suffixed_file; target.loadingCommand = RunCommandFor(*candidate_files[selected_file]); return; } // One more guess: if only one remaining candidate file has a different name than the others, // assume it is intended to stand out. std::map<std::string, int> name_counts; std::map<std::string, size_t> indices_by_name; size_t index = 0; for(auto file : candidate_files) { name_counts[file->name]++; indices_by_name[file->name] = index; index++; } if(name_counts.size() == 2) { for(auto &pair : name_counts) { if(pair.second == 1) { target.loadingCommand = RunCommandFor(*candidate_files[indices_by_name[pair.first]]); return; } } } // Desperation. target.loadingCommand = "cat\n"; } static bool CheckBootSector(const std::shared_ptr<Storage::Disk::Disk> &disk, StaticAnalyser::Target &target) { Storage::Encodings::MFM::Parser parser(true, disk); std::shared_ptr<Storage::Encodings::MFM::Sector> boot_sector = parser.get_sector(0, 0, 0x41); if(boot_sector != nullptr) { // Check that the first 64 bytes of the sector aren't identical; if they are then probably // this disk was formatted and the filler byte never replaced. bool matched = true; for(size_t c = 1; c < 64; c++) { if(boot_sector->data[c] != boot_sector->data[0]) { matched = false; break; } } // This is a system disk, then launch it as though it were CP/M. if(!matched) { target.loadingCommand = "|cpm\n"; return true; } } return false; } void StaticAnalyser::AmstradCPC::AddTargets(const Media &media, std::list<Target> &destination) { Target target; target.machine = Target::AmstradCPC; target.probability = 1.0; target.media.disks = media.disks; target.media.tapes = media.tapes; target.media.cartridges = media.cartridges; target.amstradcpc.model = AmstradCPCModel::CPC6128; if(!target.media.tapes.empty()) { // Ugliness flows here: assume the CPC isn't smart enough to pause between pressing // enter and responding to the follow-on prompt to press a key, so just type for // a while. Yuck! target.loadingCommand = "|tape\nrun\"\n1234567890"; } if(!target.media.disks.empty()) { Storage::Disk::CPM::ParameterBlock data_format; data_format.sectors_per_track = 9; data_format.tracks = 40; data_format.block_size = 1024; data_format.first_sector = 0xc1; data_format.catalogue_allocation_bitmap = 0xc000; data_format.reserved_tracks = 0; std::unique_ptr<Storage::Disk::CPM::Catalogue> data_catalogue = Storage::Disk::CPM::GetCatalogue(target.media.disks.front(), data_format); if(data_catalogue) { InspectCatalogue(*data_catalogue, target); } else { if(!CheckBootSector(target.media.disks.front(), target)) { Storage::Disk::CPM::ParameterBlock system_format; system_format.sectors_per_track = 9; system_format.tracks = 40; system_format.block_size = 1024; system_format.first_sector = 0x41; system_format.catalogue_allocation_bitmap = 0xc000; system_format.reserved_tracks = 2; std::unique_ptr<Storage::Disk::CPM::Catalogue> system_catalogue = Storage::Disk::CPM::GetCatalogue(target.media.disks.front(), system_format); if(system_catalogue) { InspectCatalogue(*system_catalogue, target); } } } } destination.push_back(target); } <|endoftext|>
<commit_before>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ #include <stdlib.h> #include <math.h> #include "normal.hpp" const int log_two_of_sum_count=4; // Higher number means better approximation const double scaling_factor=sqrt((double) (1<<log_two_of_sum_count)/((double)RAND_MAX*sqrt(1.0/12.0)) ); double generate_normal_rv(void) { /* Generate a (mean=0, var=1) Gaussian RV approximation using central limit theorem */ int i; int accum=0; for(i=0;i<(1<<log_two_of_sum_count);i++) accum+=rand()>>log_two_of_sum_count; return ((double)accum - (double)(RAND_MAX>>1))*scaling_factor; } #ifdef UNIT_TEST #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int i; double moment_1=0.0; double moment_2=0.0; for(i=0;i<100000;i++) { double x=generate_normal_rv(); moment_1+=x; moment_2+=x*x; } printf("1st moment: %lf (should be near 0.0)\n",moment_1/100000.0); printf("2nd moment: %lf (should be near 1.0)\n",moment_2/100000.0); return 0; } #endif <commit_msg>Fixing a scaling factor and probably breaking the build for some platform...<commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ #include <stdlib.h> #include <math.h> #include "normal.hpp" const int log_two_of_sum_count=4; // Higher number means better approximation const double scaling_factor=sqrt(1<<log_two_of_sum_count)/((double)RAND_MAX*sqrt(1.0/12.0)); double generate_normal_rv(void) { /* Generate a (mean=0, var=1) Gaussian RV approximation using central limit theorem */ int i; int accum=0; for(i=0;i<(1<<log_two_of_sum_count);i++) accum+=rand()>>log_two_of_sum_count; return ((double)accum - (double)(RAND_MAX>>1))*scaling_factor; } #ifdef UNIT_TEST #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int i; double moment_1=0.0; double moment_2=0.0; for(i=0;i<100000;i++) { double x=generate_normal_rv(); moment_1+=x; moment_2+=x*x; } printf("1st moment: %lf (should be near 0.0)\n",moment_1/100000.0); printf("2nd moment: %lf (should be near 1.0)\n",moment_2/100000.0); return 0; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ldapuserprofilebe.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:23:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILEBE_HXX_ #define EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILEBE_HXX_ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROF_HXX_ #include "ldapuserprof.hxx" #endif #ifndef EXTENSIONS_CONFIG_LDAP_LDAPACCESS_HXX_ #include "ldapaccess.hxx" #endif #ifndef EXTENSIONS_CONFIG_LDAP_LADPUSERPROFILELAYER_HXX_ #include "ldapuserprofilelayer.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSINGLELAYERSTRATUM_HPP_ #include <com/sun/star/configuration/backend/XSingleLayerStratum.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif // _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/CannotConnectException.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_INSUFFICIENTACCESSRIGHTSEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/InsufficientAccessRightsException.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_INSUFFICIENTACCESSRIGHTSEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CONNECTIONLOSTEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/ConnectionLostException.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_CONNECTIONLOSTEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif // _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif // _CPPUHELPER_COMPBASE3_HXX_ #define CONTEXT_ITEM_PREFIX_ "/modules/com.sun.star.configuration/bootstrap/" namespace extensions { namespace config { namespace ldap { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace ldap= css::ldap ; namespace backend = css::configuration::backend ; namespace container = css::container; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ typedef cppu::WeakComponentImplHelper2<backend::XSingleLayerStratum, lang::XServiceInfo> BackendBase ; struct LdapProfileMutexHolder { osl::Mutex mMutex; }; /** Implements the PlatformBackend service, a specialization of the SingleLayerStratum service for retreiving LDAP user profile configuration settings from a LDAP repsoitory. */ class LdapUserProfileBe : private LdapProfileMutexHolder, public BackendBase { public : LdapUserProfileBe(const uno::Reference<uno::XComponentContext>& xContext); // throw(backend::BackendAccessException, backend::BackendSetupException, RuntimeException); ~LdapUserProfileBe(void) ; // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( ) throw (uno::RuntimeException) ; virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName ) throw (uno::RuntimeException) ; virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( ) throw (uno::RuntimeException) ; //XSingleLayerStratum virtual uno::Reference<backend::XLayer> SAL_CALL getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException) ; virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL getUpdatableLayer( const rtl::OUString& aLayerId ) throw (backend::BackendAccessException, lang::NoSupportException, lang::IllegalArgumentException, uno::RuntimeException) ; /** Provides the implementation name. @return implementation name */ static rtl::OUString SAL_CALL getLdapUserProfileBeName(void) ; /** Provides the supported services names @return service names */ static uno::Sequence<rtl::OUString> SAL_CALL getLdapUserProfileBeServiceNames(void) ; private: /** Build OO/LDAP attribute mapping table */ void initializeMappingTable (const rtl::OUString& aFileMapName); /** Check if LDAP is configured */ bool readLdapConfiguration(LdapDefinition& aDefinition); bool getLdapStringParam(uno::Reference<container::XNameAccess>& xAccess, const rtl::OUString& aLdapSetting, rtl::OString& aServerParameter); void mapGenericException(ldap::LdapGenericException& aException) throw (backend::InsufficientAccessRightsException, backend::ConnectionLostException, backend::BackendAccessException); /** Connect to LDAP server */ void connectToLdapServer(const LdapDefinition& aDefinition ); /** Get URL of OO-to-LDAP Mapping File */ rtl::OUString getMappingFileUrl(const rtl::OUString& aFileMapName) const; /** Service Factory object */ uno::Reference<lang::XMultiServiceFactory> mFactory; /** Component Context */ uno::Reference<uno::XComponentContext> mContext ; /** Object for LDAP functionality */ LdapUserProfileSourceRef mLdapSource; /**Currently logged in user */ rtl::OUString mLoggedOnUser ; /** DN of currently logged in user */ rtl::OString mUserDN; } ; //------------------------------------------------------------------------------ }}} #endif // EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.5.472); FILE MERGED 2008/04/01 15:15:04 thb 1.5.472.3: #i85898# Stripping all external header guards 2008/04/01 12:29:42 thb 1.5.472.2: #i85898# Stripping all external header guards 2008/03/31 12:31:26 rt 1.5.472.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ldapuserprofilebe.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILEBE_HXX_ #define EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILEBE_HXX_ #include "ldapuserprof.hxx" #include "ldapaccess.hxx" #include "ldapuserprofilelayer.hxx" #include <com/sun/star/configuration/backend/XSingleLayerStratum.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/configuration/backend/CannotConnectException.hpp> #include <com/sun/star/configuration/backend/InsufficientAccessRightsException.hpp> #include <com/sun/star/configuration/backend/ConnectionLostException.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <cppuhelper/compbase2.hxx> #define CONTEXT_ITEM_PREFIX_ "/modules/com.sun.star.configuration/bootstrap/" namespace extensions { namespace config { namespace ldap { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace ldap= css::ldap ; namespace backend = css::configuration::backend ; namespace container = css::container; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ typedef cppu::WeakComponentImplHelper2<backend::XSingleLayerStratum, lang::XServiceInfo> BackendBase ; struct LdapProfileMutexHolder { osl::Mutex mMutex; }; /** Implements the PlatformBackend service, a specialization of the SingleLayerStratum service for retreiving LDAP user profile configuration settings from a LDAP repsoitory. */ class LdapUserProfileBe : private LdapProfileMutexHolder, public BackendBase { public : LdapUserProfileBe(const uno::Reference<uno::XComponentContext>& xContext); // throw(backend::BackendAccessException, backend::BackendSetupException, RuntimeException); ~LdapUserProfileBe(void) ; // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( ) throw (uno::RuntimeException) ; virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName ) throw (uno::RuntimeException) ; virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( ) throw (uno::RuntimeException) ; //XSingleLayerStratum virtual uno::Reference<backend::XLayer> SAL_CALL getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException) ; virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL getUpdatableLayer( const rtl::OUString& aLayerId ) throw (backend::BackendAccessException, lang::NoSupportException, lang::IllegalArgumentException, uno::RuntimeException) ; /** Provides the implementation name. @return implementation name */ static rtl::OUString SAL_CALL getLdapUserProfileBeName(void) ; /** Provides the supported services names @return service names */ static uno::Sequence<rtl::OUString> SAL_CALL getLdapUserProfileBeServiceNames(void) ; private: /** Build OO/LDAP attribute mapping table */ void initializeMappingTable (const rtl::OUString& aFileMapName); /** Check if LDAP is configured */ bool readLdapConfiguration(LdapDefinition& aDefinition); bool getLdapStringParam(uno::Reference<container::XNameAccess>& xAccess, const rtl::OUString& aLdapSetting, rtl::OString& aServerParameter); void mapGenericException(ldap::LdapGenericException& aException) throw (backend::InsufficientAccessRightsException, backend::ConnectionLostException, backend::BackendAccessException); /** Connect to LDAP server */ void connectToLdapServer(const LdapDefinition& aDefinition ); /** Get URL of OO-to-LDAP Mapping File */ rtl::OUString getMappingFileUrl(const rtl::OUString& aFileMapName) const; /** Service Factory object */ uno::Reference<lang::XMultiServiceFactory> mFactory; /** Component Context */ uno::Reference<uno::XComponentContext> mContext ; /** Object for LDAP functionality */ LdapUserProfileSourceRef mLdapSource; /**Currently logged in user */ rtl::OUString mLoggedOnUser ; /** DN of currently logged in user */ rtl::OString mUserDN; } ; //------------------------------------------------------------------------------ }}} #endif // EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ <|endoftext|>
<commit_before>AliGenerator* AddMCGenPythia8(Float_t e_cms = 2760., Bool_t kCR = kTRUE) { // Add Pythia 8 generator: // - Color reconnection = ON/OFF gSystem->Load("liblhapdf.so"); AliGenerator *genP = NULL; genP = CreatePythia8Gen(e_cms, kCR); return genP; } AliGenerator* CreatePythia8Gen(Float_t e_cms, Bool_t kCR) { gSystem->Load("libpythia6.so"); gSystem->Load("libAliPythia6.so"); gSystem->Load("libpythia8.so"); gSystem->Load("libAliPythia8.so"); gSystem->Setenv("PYTHIA8DATA", gSystem->ExpandPathName("$ALICE_ROOT/PYTHIA8/pythia8175/xmldoc")); gSystem->Setenv("LHAPDF", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF")); gSystem->Setenv("LHAPATH", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF/PDFsets")); AliGenPythiaPlus* gener = new AliGenPythiaPlus(AliPythia8::Instance()); // set process (MB) gener->SetProcess(kPyMbDefault); // // charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb // if(ptHardMin>0.) { // gener->SetProcess(kPyJets); // gener->SetPtHard((float)ptHardMin,(float)ptHardMax); // } else // gener->SetProcess(kPyMb); // Minimum Bias // Centre of mass energy gener->SetEnergyCMS(e_cms); // in GeV // Event list gener->SetEventListRange(-1, 2); // color reconnection (AliPythia8::Instance())->ReadString("Tune:pp = 5");//CR //gener->UseNewMultipleInteractionsScenario(); // for all Pythia versions >= 6.3 if(kCR) (AliPythia8::Instance())->ReadString("BeamRemnants:reconnectColours = on"); else (AliPythia8::Instance())->ReadString("BeamRemnants:reconnectColours = off"); // vertex position and smearing //gener->SetVertexSmear(kPerEvent); // structure function // use kCTEQ5l for Perugia tunes // except for tunes: Perugia * (325, MRSTLO*), Perugia 6 (326, CTEQ6L), // Perugia 11 M (355, MRST LO**), Perugia 11 C (356, CTEQ6L1) //gener->SetStrucFunc(kCTEQ5L); return gener; } <commit_msg>adding library, removing comments<commit_after>AliGenerator* AddMCGenPythia8(Float_t e_cms = 2760., Bool_t kCR = kTRUE) { // Add Pythia 8 generator: // - Color reconnection = ON/OFF gSystem->Load("liblhapdf.so"); AliGenerator *genP = NULL; genP = CreatePythia8Gen(e_cms, kCR); return genP; } AliGenerator* CreatePythia8Gen(Float_t e_cms, Bool_t kCR) { gSystem->Load("libpythia6.so"); gSystem->Load("libEGPythia6.so"); gSystem->Load("libAliPythia6.so"); gSystem->Load("libpythia8.so"); gSystem->Load("libAliPythia8.so"); gSystem->Setenv("PYTHIA8DATA", gSystem->ExpandPathName("$ALICE_ROOT/PYTHIA8/pythia8175/xmldoc")); gSystem->Setenv("LHAPDF", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF")); gSystem->Setenv("LHAPATH", gSystem->ExpandPathName("$ALICE_ROOT/LHAPDF/PDFsets")); AliGenPythiaPlus* gener = new AliGenPythiaPlus(AliPythia8::Instance()); // set process (MB) gener->SetProcess(kPyMbDefault); // Centre of mass energy gener->SetEnergyCMS(e_cms); // in GeV // Event list gener->SetEventListRange(-1, 2); // color reconnection (AliPythia8::Instance())->ReadString("Tune:pp = 5");//CR if(kCR) (AliPythia8::Instance())->ReadString("BeamRemnants:reconnectColours = on"); else (AliPythia8::Instance())->ReadString("BeamRemnants:reconnectColours = off"); return gener; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/scheduler/processor.h" #include "cybertron/common/log.h" #include "cybertron/common/types.h" #include "cybertron/croutine/croutine.h" #include "cybertron/event/perf_event_cache.h" #include "cybertron/scheduler/processor_context.h" #include "cybertron/scheduler/scheduler.h" #include "cybertron/time/time.h" namespace apollo { namespace cybertron { namespace scheduler { using apollo::cybertron::event::PerfEventCache; using apollo::cybertron::event::SchedPerf; void ProcessorContext::RemoveCRoutine(uint64_t croutine_id) { WriteLockGuard<AtomicRWLock> lg(rw_lock_); auto it = cr_map_.find(croutine_id); if (it != cr_map_.end()) { it->second->Stop(); cr_map_.erase(it); } } int ProcessorContext::RqSize() { ReadLockGuard<AtomicRWLock> lg(rw_lock_); return cr_map_.size(); } void ProcessorContext::Notify(uint64_t routine_id) { PerfEventCache::Instance()->AddSchedEvent(SchedPerf::NOTIFY_IN, routine_id, proc_index_, 0, 0, -1, -1); ReadLockGuard<AtomicRWLock> lg(rw_lock_); auto routine = cr_map_[routine_id]; { auto lock = routine->GetLock(); lock.lock(); if (routine->state() == RoutineState::DATA_WAIT) { routine->set_state(RoutineState::READY); } } if (!notified_.exchange(true)) { processor_->Notify(); return; } } void ProcessorContext::ShutDown() { if (!stop_) { stop_ = true; } processor_->Stop(); } } // namespace scheduler } // namespace cybertron } // namespace apollo <commit_msg>framework: quick fix timer deadlock issue<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/scheduler/processor.h" #include "cybertron/common/log.h" #include "cybertron/common/types.h" #include "cybertron/croutine/croutine.h" #include "cybertron/event/perf_event_cache.h" #include "cybertron/scheduler/processor_context.h" #include "cybertron/scheduler/scheduler.h" #include "cybertron/time/time.h" namespace apollo { namespace cybertron { namespace scheduler { using apollo::cybertron::event::PerfEventCache; using apollo::cybertron::event::SchedPerf; void ProcessorContext::RemoveCRoutine(uint64_t croutine_id) { WriteLockGuard<AtomicRWLock> lg(rw_lock_); auto it = cr_map_.find(croutine_id); if (it != cr_map_.end()) { it->second->Stop(); cr_map_.erase(it); } } int ProcessorContext::RqSize() { ReadLockGuard<AtomicRWLock> lg(rw_lock_); return cr_map_.size(); } void ProcessorContext::Notify(uint64_t routine_id) { PerfEventCache::Instance()->AddSchedEvent(SchedPerf::NOTIFY_IN, routine_id, proc_index_, 0, 0, -1, -1); ReadLockGuard<AtomicRWLock> lg(rw_lock_); auto routine = cr_map_[routine_id]; { auto lock = routine->GetLock(); lock.try_lock(); if (routine->state() == RoutineState::DATA_WAIT) { routine->set_state(RoutineState::READY); } } if (!notified_.exchange(true)) { processor_->Notify(); return; } } void ProcessorContext::ShutDown() { if (!stop_) { stop_ = true; } processor_->Stop(); } } // namespace scheduler } // namespace cybertron } // namespace apollo <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 12/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TAttAxis.h" #include "TBuffer.h" #include "TStyle.h" #include "TVirtualPad.h" #include "TColor.h" #include "TClass.h" #include "TMathBase.h" #include <stdlib.h> ClassImp(TAttAxis); /** \class TAttAxis \ingroup Base \ingroup GraphicsAtt Manages histogram axis attributes. They are: - The number of divisions - The line axis' color - The labels' color - The labels' font - The labels' offset - The labels' size - The tick marks' - The axis title's offset - The axis title's size - The axis title's color - The axis title's font */ TAttAxis::TAttAxis() { // Constructor. ResetAttAxis(); } //////////////////////////////////////////////////////////////////////////////// /// Destructor. TAttAxis::~TAttAxis() { } //////////////////////////////////////////////////////////////////////////////// /// Copy of the object. void TAttAxis::Copy(TAttAxis &attaxis) const { attaxis.fNdivisions = fNdivisions; attaxis.fAxisColor = fAxisColor; attaxis.fLabelColor = fLabelColor; attaxis.fLabelFont = fLabelFont; attaxis.fLabelOffset = fLabelOffset; attaxis.fLabelSize = fLabelSize; attaxis.fTickLength = fTickLength; attaxis.fTitleOffset = fTitleOffset; attaxis.fTitleSize = fTitleSize; attaxis.fTitleColor = fTitleColor; attaxis.fTitleFont = fTitleFont; } //////////////////////////////////////////////////////////////////////////////// /// Reset axis attributes void TAttAxis::ResetAttAxis(Option_t *option) { if (gStyle) { fNdivisions = gStyle->GetNdivisions(option); fAxisColor = gStyle->GetAxisColor(option); fLabelColor = gStyle->GetLabelColor(option); fLabelFont = gStyle->GetLabelFont(option); fLabelOffset = gStyle->GetLabelOffset(option); fLabelSize = gStyle->GetLabelSize(option); fTickLength = gStyle->GetTickLength(option); fTitleOffset = gStyle->GetTitleOffset(option); fTitleSize = gStyle->GetTitleSize(option); fTitleColor = gStyle->GetTitleColor(option); fTitleFont = gStyle->GetTitleFont(option); } else { fNdivisions = 510; fAxisColor = 1; fLabelColor = 1; fLabelFont = 62; fLabelOffset = 0.005; fLabelSize = 0.04; fTickLength = 0.03; fTitleOffset = 1; fTitleSize = fLabelSize; fTitleColor = 1; fTitleFont = 62; } } //////////////////////////////////////////////////////////////////////////////// /// Save axis attributes as C++ statement(s) on output stream out void TAttAxis::SaveAttributes(std::ostream &out, const char *name, const char *subname) { if (fNdivisions != 510) { out<<" "<<name<<subname<<"->SetNdivisions("<<fNdivisions<<");"<<std::endl; } if (fAxisColor != 1) { if (fAxisColor > 228) { TColor::SaveColor(out, fAxisColor); out<<" "<<name<<subname<<"->SetAxisColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetAxisColor("<<fAxisColor<<");"<<std::endl; } if (fLabelColor != 1) { if (fLabelColor > 228) { TColor::SaveColor(out, fLabelColor); out<<" "<<name<<subname<<"->SetLabelColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetLabelColor("<<fLabelColor<<");"<<std::endl; } if (fLabelFont != 62) { out<<" "<<name<<subname<<"->SetLabelFont("<<fLabelFont<<");"<<std::endl; } if (TMath::Abs(fLabelOffset-0.005) > 0.0001) { out<<" "<<name<<subname<<"->SetLabelOffset("<<fLabelOffset<<");"<<std::endl; } if (TMath::Abs(fLabelSize-0.035) > 0.001) { out<<" "<<name<<subname<<"->SetLabelSize("<<fLabelSize<<");"<<std::endl; } if (TMath::Abs(fTitleSize-0.035) > 0.001) { out<<" "<<name<<subname<<"->SetTitleSize("<<fTitleSize<<");"<<std::endl; } if (TMath::Abs(fTickLength-0.03) > 0.001) { out<<" "<<name<<subname<<"->SetTickLength("<<fTickLength<<");"<<std::endl; } if (TMath::Abs(fTitleOffset) > 0.001) { out<<" "<<name<<subname<<"->SetTitleOffset("<<fTitleOffset<<");"<<std::endl; } if (fTitleColor != 1) { if (fTitleColor > 228) { TColor::SaveColor(out, fTitleColor); out<<" "<<name<<subname<<"->SetTitleColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetTitleColor("<<fTitleColor<<");"<<std::endl; } if (fTitleFont != 62) { out<<" "<<name<<subname<<"->SetTitleFont("<<fTitleFont<<");"<<std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Set color of the line axis and tick marks void TAttAxis::SetAxisColor(Color_t color, Float_t alpha) { if (alpha<1.) fAxisColor = TColor::GetColorTransparent(color, alpha); else fAxisColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set color of labels void TAttAxis::SetLabelColor(Color_t color, Float_t alpha) { if (alpha<1.) fLabelColor = TColor::GetColorTransparent(color, alpha); else fLabelColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set labels' font. void TAttAxis::SetLabelFont(Style_t font) { fLabelFont = font; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set distance between the axis and the labels /// The distance is expressed in per cent of the pad width void TAttAxis::SetLabelOffset(Float_t offset) { fLabelOffset = offset; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set size of axis labels /// The size is expressed in per cent of the pad width void TAttAxis::SetLabelSize(Float_t size) { fLabelSize = size; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the number of divisions for this axis. /// /// - if optim = kTRUE (default), the number of divisions will be /// optimized around the specified value. /// - if optim = kFALSE, or n < 0, the axis will be forced to use /// exactly n divisions. ///~~~ {.cpp} /// n = n1 + 100*n2 + 10000*n3 ///~~~ /// Where n1 is the number of primary divisions, /// n2 is the number of second order divisions and /// n3 is the number of third order divisions. /// /// e.g. 512 means 12 primary and 5 secondary divisions. /// /// If the number of divisions is "optimized" (see above) n1, n2, n3 are /// maximum values. void TAttAxis::SetNdivisions(Int_t n, Bool_t optim) { Int_t ndiv = (n%1000000); Bool_t isOptimized = optim && (ndiv>0); Int_t current_maxDigits = abs(fNdivisions)/1000000; fNdivisions = abs(ndiv) + current_maxDigits*1000000; if (!isOptimized) fNdivisions = -fNdivisions; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// ///see function above void TAttAxis::SetNdivisions(Int_t n1, Int_t n2, Int_t n3, Bool_t optim) { SetNdivisions(n1+100*n2+10000*n3, optim); } //////////////////////////////////////////////////////////////////////////////// /// This function sets the maximum number of digits permitted for the axis labels /// above which the notation with 10^N is used. /// /// For example, to accept 6 digits number like 900000 on the X axis of the /// histogram `h` call: /// /// ~~~ {.cpp} /// h->GetXaxis()->SetMaxDigits(6); /// ~~~ /// /// The default value is 5. /// /// The default value for all axis can be set with the static function /// `TGaxis::SetMaxDigits`. void TAttAxis::SetMaxDigits(Int_t maxDigits) { Bool_t isOptimized = fNdivisions>0; Int_t absDiv = abs(fNdivisions); Int_t current_maxDigits = absDiv/1000000; Int_t current_Ndivisions = absDiv - (current_maxDigits*1000000); fNdivisions = (current_Ndivisions + (maxDigits*1000000)); if (!isOptimized) fNdivisions = -fNdivisions; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set tick mark length /// The length is expressed in per cent of the pad width void TAttAxis::SetTickLength(Float_t length) { fTickLength = length; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set distance between the axis and the axis title /// Offset is a correction factor with respect to the "standard" value. /// - offset = 1 uses standard position that is computed in function /// of the label offset and size. /// - offset = 1.2 will add 20 per cent more to the standard offset. /// - offset = 0 automatic placement for the Y axis title (default). void TAttAxis::SetTitleOffset(Float_t offset) { fTitleOffset = offset; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set size of axis title /// The size is expressed in per cent of the pad width void TAttAxis::SetTitleSize(Float_t size) { fTitleSize = size; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set color of axis title void TAttAxis::SetTitleColor(Color_t color) { fTitleColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the title font. void TAttAxis::SetTitleFont(Style_t font) { fTitleFont = font; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TAttAxis. void TAttAxis::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 3) { R__b.ReadClassBuffer(TAttAxis::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution R__b >> fNdivisions; R__b >> fAxisColor; R__b >> fLabelColor; R__b >> fLabelFont; R__b >> fLabelOffset; R__b >> fLabelSize; R__b >> fTickLength; R__b >> fTitleOffset; if (R__v > 1 && R__b.GetVersionOwner() > 900) R__b >> fTitleSize; else fTitleSize = fLabelSize; if (R__v > 2) { R__b >> fTitleColor; R__b >> fTitleFont; } //====end of old versions } else { R__b.WriteClassBuffer(TAttAxis::Class(),this); } } <commit_msg>Cosmetics changes in the doc.<commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 12/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TAttAxis.h" #include "TBuffer.h" #include "TStyle.h" #include "TVirtualPad.h" #include "TColor.h" #include "TClass.h" #include "TMathBase.h" #include <stdlib.h> ClassImp(TAttAxis); /** \class TAttAxis \ingroup Base \ingroup GraphicsAtt Manages histogram axis attributes. They are: - The number of divisions - The line axis' color - The labels' color - The labels' font - The labels' offset - The labels' size - The tick marks' - The axis title's offset - The axis title's size - The axis title's color - The axis title's font */ TAttAxis::TAttAxis() { // Constructor. ResetAttAxis(); } //////////////////////////////////////////////////////////////////////////////// /// Destructor. TAttAxis::~TAttAxis() { } //////////////////////////////////////////////////////////////////////////////// /// Copy of the object. void TAttAxis::Copy(TAttAxis &attaxis) const { attaxis.fNdivisions = fNdivisions; attaxis.fAxisColor = fAxisColor; attaxis.fLabelColor = fLabelColor; attaxis.fLabelFont = fLabelFont; attaxis.fLabelOffset = fLabelOffset; attaxis.fLabelSize = fLabelSize; attaxis.fTickLength = fTickLength; attaxis.fTitleOffset = fTitleOffset; attaxis.fTitleSize = fTitleSize; attaxis.fTitleColor = fTitleColor; attaxis.fTitleFont = fTitleFont; } //////////////////////////////////////////////////////////////////////////////// /// Reset axis attributes. void TAttAxis::ResetAttAxis(Option_t *option) { if (gStyle) { fNdivisions = gStyle->GetNdivisions(option); fAxisColor = gStyle->GetAxisColor(option); fLabelColor = gStyle->GetLabelColor(option); fLabelFont = gStyle->GetLabelFont(option); fLabelOffset = gStyle->GetLabelOffset(option); fLabelSize = gStyle->GetLabelSize(option); fTickLength = gStyle->GetTickLength(option); fTitleOffset = gStyle->GetTitleOffset(option); fTitleSize = gStyle->GetTitleSize(option); fTitleColor = gStyle->GetTitleColor(option); fTitleFont = gStyle->GetTitleFont(option); } else { fNdivisions = 510; fAxisColor = 1; fLabelColor = 1; fLabelFont = 62; fLabelOffset = 0.005; fLabelSize = 0.04; fTickLength = 0.03; fTitleOffset = 1; fTitleSize = fLabelSize; fTitleColor = 1; fTitleFont = 62; } } //////////////////////////////////////////////////////////////////////////////// /// Save axis attributes as C++ statement(s) on output stream out. void TAttAxis::SaveAttributes(std::ostream &out, const char *name, const char *subname) { if (fNdivisions != 510) { out<<" "<<name<<subname<<"->SetNdivisions("<<fNdivisions<<");"<<std::endl; } if (fAxisColor != 1) { if (fAxisColor > 228) { TColor::SaveColor(out, fAxisColor); out<<" "<<name<<subname<<"->SetAxisColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetAxisColor("<<fAxisColor<<");"<<std::endl; } if (fLabelColor != 1) { if (fLabelColor > 228) { TColor::SaveColor(out, fLabelColor); out<<" "<<name<<subname<<"->SetLabelColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetLabelColor("<<fLabelColor<<");"<<std::endl; } if (fLabelFont != 62) { out<<" "<<name<<subname<<"->SetLabelFont("<<fLabelFont<<");"<<std::endl; } if (TMath::Abs(fLabelOffset-0.005) > 0.0001) { out<<" "<<name<<subname<<"->SetLabelOffset("<<fLabelOffset<<");"<<std::endl; } if (TMath::Abs(fLabelSize-0.035) > 0.001) { out<<" "<<name<<subname<<"->SetLabelSize("<<fLabelSize<<");"<<std::endl; } if (TMath::Abs(fTitleSize-0.035) > 0.001) { out<<" "<<name<<subname<<"->SetTitleSize("<<fTitleSize<<");"<<std::endl; } if (TMath::Abs(fTickLength-0.03) > 0.001) { out<<" "<<name<<subname<<"->SetTickLength("<<fTickLength<<");"<<std::endl; } if (TMath::Abs(fTitleOffset) > 0.001) { out<<" "<<name<<subname<<"->SetTitleOffset("<<fTitleOffset<<");"<<std::endl; } if (fTitleColor != 1) { if (fTitleColor > 228) { TColor::SaveColor(out, fTitleColor); out<<" "<<name<<subname<<"->SetTitleColor(ci);" << std::endl; } else out<<" "<<name<<subname<<"->SetTitleColor("<<fTitleColor<<");"<<std::endl; } if (fTitleFont != 62) { out<<" "<<name<<subname<<"->SetTitleFont("<<fTitleFont<<");"<<std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Set color of the line axis and tick marks. void TAttAxis::SetAxisColor(Color_t color, Float_t alpha) { if (alpha<1.) fAxisColor = TColor::GetColorTransparent(color, alpha); else fAxisColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set color of labels. void TAttAxis::SetLabelColor(Color_t color, Float_t alpha) { if (alpha<1.) fLabelColor = TColor::GetColorTransparent(color, alpha); else fLabelColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set labels' font. void TAttAxis::SetLabelFont(Style_t font) { fLabelFont = font; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set distance between the axis and the labels. /// The distance is expressed in per cent of the pad width. void TAttAxis::SetLabelOffset(Float_t offset) { fLabelOffset = offset; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set size of axis labels. /// The size is expressed in per cent of the pad size. void TAttAxis::SetLabelSize(Float_t size) { fLabelSize = size; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the number of divisions for this axis. /// /// - if optim = kTRUE (default), the number of divisions will be /// optimized around the specified value. /// - if optim = kFALSE, or n < 0, the axis will be forced to use /// exactly n divisions. ///~~~ {.cpp} /// n = n1 + 100*n2 + 10000*n3 ///~~~ /// Where n1 is the number of primary divisions, /// n2 is the number of second order divisions and /// n3 is the number of third order divisions. /// /// e.g. 512 means 12 primary and 5 secondary divisions. /// /// If the number of divisions is "optimized" (see above) n1, n2, n3 are /// maximum values. void TAttAxis::SetNdivisions(Int_t n, Bool_t optim) { Int_t ndiv = (n%1000000); Bool_t isOptimized = optim && (ndiv>0); Int_t current_maxDigits = abs(fNdivisions)/1000000; fNdivisions = abs(ndiv) + current_maxDigits*1000000; if (!isOptimized) fNdivisions = -fNdivisions; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the number of divisions for this axis using one `int` per division level. void TAttAxis::SetNdivisions(Int_t n1, Int_t n2, Int_t n3, Bool_t optim) { SetNdivisions(n1+100*n2+10000*n3, optim); } //////////////////////////////////////////////////////////////////////////////// /// This function sets the maximum number of digits permitted for the axis labels /// above which the notation with 10^N is used. /// /// For example, to accept 6 digits number like 900000 on the X axis of the /// histogram `h` call: /// /// ~~~ {.cpp} /// h->GetXaxis()->SetMaxDigits(6); /// ~~~ /// /// The default value is 5. /// /// The default value for all axis can be set with the static function /// `TGaxis::SetMaxDigits`. void TAttAxis::SetMaxDigits(Int_t maxDigits) { Bool_t isOptimized = fNdivisions>0; Int_t absDiv = abs(fNdivisions); Int_t current_maxDigits = absDiv/1000000; Int_t current_Ndivisions = absDiv - (current_maxDigits*1000000); fNdivisions = (current_Ndivisions + (maxDigits*1000000)); if (!isOptimized) fNdivisions = -fNdivisions; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set tick mark length. /// The length is expressed in per cent of the pad width. void TAttAxis::SetTickLength(Float_t length) { fTickLength = length; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set distance between the axis and the axis title. /// Offset is a correction factor with respect to the "standard" value. /// - offset = 1 uses standard position that is computed in function /// of the label offset and size. /// - offset = 1.2 will add 20 per cent more to the standard offset. /// - offset = 0 automatic placement for the Y axis title (default). void TAttAxis::SetTitleOffset(Float_t offset) { fTitleOffset = offset; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set size of axis title. /// The size is expressed in per cent of the pad width void TAttAxis::SetTitleSize(Float_t size) { fTitleSize = size; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set color of axis title. void TAttAxis::SetTitleColor(Color_t color) { fTitleColor = color; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the title font. void TAttAxis::SetTitleFont(Style_t font) { fTitleFont = font; if (gPad) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TAttAxis. void TAttAxis::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 3) { R__b.ReadClassBuffer(TAttAxis::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution R__b >> fNdivisions; R__b >> fAxisColor; R__b >> fLabelColor; R__b >> fLabelFont; R__b >> fLabelOffset; R__b >> fLabelSize; R__b >> fTickLength; R__b >> fTitleOffset; if (R__v > 1 && R__b.GetVersionOwner() > 900) R__b >> fTitleSize; else fTitleSize = fLabelSize; if (R__v > 2) { R__b >> fTitleColor; R__b >> fTitleFont; } //====end of old versions } else { R__b.WriteClassBuffer(TAttAxis::Class(),this); } } <|endoftext|>
<commit_before>/* =============================================================================== FILE: compressor.hpp CONTENTS: Integer compressor PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com uday.karan@gmail.com - Hobu, Inc. COPYRIGHT: (c) 2007-2014, martin isenburg, rapidlasso - tools to catch reality (c) 2014, Uday Verma, Hobu, Inc. This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: =============================================================================== */ #ifndef __compressor_hpp__ #define __compressor_hpp__ #include "model.hpp" #include <cstdint> #include <limits> #include <vector> #include <cassert> namespace lazperf { namespace compressors { struct integer { public: integer(uint32_t bits = 16, uint32_t contexts = 1) : bits(bits), contexts(contexts) { if (bits && bits < 32) { corr_bits = bits; corr_range = 1u << bits; // the corrector must fall into this interval corr_min = -((int32_t)(corr_range/2)); corr_max = corr_min + corr_range - 1; } else { corr_bits = 32; corr_range = 0; // the corrector must fall into this interval corr_min = (std::numeric_limits<int32_t>::min)(); corr_max = (std::numeric_limits<int32_t>::max)(); } k = 0; } ~integer() { mBits.clear(); mCorrector.clear(); } // ABELL - Maybe this is separate so that the compressor can be reused? // If so, why not called from the ctor? void init() { using models::arithmetic; using models::arithmetic_bit; // maybe create the models if (mBits.empty()) { for (uint32_t i = 0; i < contexts; i++) mBits.push_back(arithmetic(corr_bits+1)); // mcorrector0 is already in init state for (uint32_t i = 1; i <= corr_bits; i++) { uint32_t v = i <= bits_high ? 1 << i : 1 << bits_high; mCorrector.push_back(arithmetic(v)); } } } unsigned int getK() const { return k; } template<typename TEncoder> void compress(TEncoder& enc, int32_t pred, int32_t real, uint32_t context) { // the corrector will be within the interval [ - (corr_range - 1) ... + (corr_range - 1) ] int32_t corr = real - pred; // we fold the corrector into the interval [ corr_min ... corr_max ] if (corr < corr_min) corr += corr_range; else if (corr > corr_max) corr -= corr_range; writeCorrector(enc, corr, mBits[context]); } template<typename TEncoder, typename TEntropyModel> void writeCorrector(TEncoder& enc, int c, TEntropyModel& mBits) { // find the tighest interval [ - (2^k - 1) ... + (2^k) ] that contains c // do this by checking the absolute value of c (adjusted for the case that c is 2^k) uint32_t c1 = (c <= 0 ? -c : c - 1); // Find the number of bits containing information (32 - # leading 0 bits) // Tried an intrinsic for this with worse outcome. for (k = 0; c1; k++) c1 = c1 >> 1; // the number k is between 0 and corr_bits and describes the interval // the corrector falls into we can compress the exact location of c // within this interval using k bits enc.encodeSymbol(mBits, k); if (k) // then c is either smaller than 0 or bigger than 1 { assert((c != 0) && (c != 1)); // translate the corrector c into the k-bit interval [ 0 ... 2^k - 1 ] if (c < 0) // then c is in the interval [ - (2^k - 1) ... - (2^(k-1)) ] { // so we translate c into the interval [ 0 ... + 2^(k-1) - 1 ] // by adding (2^k - 1) c += ((1<<k) - 1); } else // then c is in the interval [ 2^(k-1) + 1 ... 2^k ] { // so we translate c into the interval [ 2^(k-1) ... + 2^k - 1 ] // by subtracting 1 c -= 1; } if (k <= bits_high) // for small k we code the interval in one step { // compress c with the range coder enc.encodeSymbol(mCorrector[k-1], c); } else // for larger k we need to code the interval in two steps { // figure out how many lower bits there are int k1 = k - bits_high; // c1 represents the lowest k-bits_high+1 bits c1 = c & ((1 << k1) - 1); // c represents the highest bits_high bits c = c >> k1; // compress the higher bits using a context table enc.encodeSymbol(mCorrector[k-1], c); // store the lower k1 bits raw enc.writeBits(k1, c1); } } else // then c is 0 or 1 { assert((c == 0) || (c == 1)); enc.encodeBit(mCorrector0,c); } } uint32_t k; uint32_t bits; uint32_t contexts; const uint32_t bits_high {8}; uint32_t corr_bits; uint32_t corr_range; int32_t corr_min; int32_t corr_max; std::vector<models::arithmetic> mBits; models::arithmetic_bit mCorrector0; std::vector<models::arithmetic> mCorrector; }; } // namespace compressors } // namespace lazperf #endif // __compressor_hpp__ <commit_msg>Don't try to encode INT_MIN as its information is in 'k'. (#98)<commit_after>/* =============================================================================== FILE: compressor.hpp CONTENTS: Integer compressor PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com uday.karan@gmail.com - Hobu, Inc. COPYRIGHT: (c) 2007-2014, martin isenburg, rapidlasso - tools to catch reality (c) 2014, Uday Verma, Hobu, Inc. This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: =============================================================================== */ #ifndef __compressor_hpp__ #define __compressor_hpp__ #include "model.hpp" #include <cstdint> #include <limits> #include <vector> #include <cassert> namespace lazperf { namespace compressors { struct integer { public: integer(uint32_t bits = 16, uint32_t contexts = 1) : bits(bits), contexts(contexts) { if (bits && bits < 32) { corr_bits = bits; corr_range = 1u << bits; // the corrector must fall into this interval corr_min = -((int32_t)(corr_range/2)); corr_max = corr_min + corr_range - 1; } else { corr_bits = 32; corr_range = 0; // the corrector must fall into this interval corr_min = (std::numeric_limits<int32_t>::min)(); corr_max = (std::numeric_limits<int32_t>::max)(); } k = 0; } ~integer() { mBits.clear(); mCorrector.clear(); } // ABELL - Maybe this is separate so that the compressor can be reused? // If so, why not called from the ctor? void init() { using models::arithmetic; using models::arithmetic_bit; // maybe create the models if (mBits.empty()) { for (uint32_t i = 0; i < contexts; i++) mBits.push_back(arithmetic(corr_bits+1)); // mcorrector0 is already in init state for (uint32_t i = 1; i <= corr_bits; i++) { uint32_t v = i <= bits_high ? 1 << i : 1 << bits_high; mCorrector.push_back(arithmetic(v)); } } } unsigned int getK() const { return k; } template<typename TEncoder> void compress(TEncoder& enc, int32_t pred, int32_t real, uint32_t context) { // the corrector will be within the interval [ - (corr_range - 1) ... + (corr_range - 1) ] int32_t corr = real - pred; // we fold the corrector into the interval [ corr_min ... corr_max ] if (corr < corr_min) corr += corr_range; else if (corr > corr_max) corr -= corr_range; writeCorrector(enc, corr, mBits[context]); } template<typename TEncoder, typename TEntropyModel> void writeCorrector(TEncoder& enc, int c, TEntropyModel& mBits) { // find the tighest interval [ - (2^k - 1) ... + (2^k) ] that contains c // do this by checking the absolute value of c (adjusted for the case that c is 2^k) uint32_t c1 = (c <= 0 ? -c : c - 1); // Find the number of bits containing information (32 - # leading 0 bits) // Tried an intrinsic for this with worse outcome. for (k = 0; c1; k++) c1 = c1 >> 1; // the number k is between 0 and corr_bits and describes the interval // the corrector falls into we can compress the exact location of c // within this interval using k bits enc.encodeSymbol(mBits, k); if (k) // then c is either smaller than 0 or bigger than 1 { assert((c != 0) && (c != 1)); // If k == 32, then the high bit is set, which only happens when the // value we want to encode is INT_MIN and all the information is in k, // which has already been encoded above. if (k == 32) return; // translate the corrector c into the k-bit interval [ 0 ... 2^k - 1 ] if (c < 0) // then c is in the interval [ - (2^k - 1) ... - (2^(k-1)) ] { // so we translate c into the interval [ 0 ... + 2^(k-1) - 1 ] // by adding (2^k - 1) c += ((1<<k) - 1); } else // then c is in the interval [ 2^(k-1) + 1 ... 2^k ] { // so we translate c into the interval [ 2^(k-1) ... + 2^k - 1 ] // by subtracting 1 c -= 1; } if (k <= bits_high) // for small k we code the interval in one step { // compress c with the range coder enc.encodeSymbol(mCorrector[k-1], c); } else // for larger k we need to code the interval in two steps { // figure out how many lower bits there are int k1 = k - bits_high; // c1 represents the lowest k-bits_high+1 bits c1 = c & ((1 << k1) - 1); // c represents the highest bits_high bits c = c >> k1; // compress the higher bits using a context table enc.encodeSymbol(mCorrector[k-1], c); // store the lower k1 bits raw enc.writeBits(k1, c1); } } else // then c is 0 or 1 { assert((c == 0) || (c == 1)); enc.encodeBit(mCorrector0,c); } } uint32_t k; uint32_t bits; uint32_t contexts; const uint32_t bits_high {8}; uint32_t corr_bits; uint32_t corr_range; int32_t corr_min; int32_t corr_max; std::vector<models::arithmetic> mBits; models::arithmetic_bit mCorrector0; std::vector<models::arithmetic> mCorrector; }; } // namespace compressors } // namespace lazperf #endif // __compressor_hpp__ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchdlg.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:39:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_SRCHDLG_HXX #define _SVX_SRCHDLG_HXX // include --------------------------------------------------------------- #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SFX_CHILDWIN_HXX //autogen #include <sfx2/childwin.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #ifndef _SVEDIT_HXX //autogen #include <svtools/svmedit.hxx> #endif #ifndef _SFX_SRCHDEFS_HXX_ #include <sfx2/srchdefs.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // forward --------------------------------------------------------------- class SvxSearchItem; class MoreButton; class SfxStyleSheetBasePool; class SvxJSearchOptionsPage; class SvxSearchController; struct SearchDlg_Impl; #ifndef NO_SVX_SEARCH // struct SearchAttrItem ------------------------------------------------- struct SearchAttrItem { USHORT nSlot; SfxPoolItem* pItem; }; // class SearchAttrItemList ---------------------------------------------- SV_DECL_VARARR_VISIBILITY(SrchAttrItemList, SearchAttrItem, 8, 8, SVX_DLLPUBLIC); class SVX_DLLPUBLIC SearchAttrItemList : private SrchAttrItemList { public: SearchAttrItemList() {} SearchAttrItemList( const SearchAttrItemList& rList ); ~SearchAttrItemList(); void Put( const SfxItemSet& rSet ); SfxItemSet& Get( SfxItemSet& rSet ); void Clear(); USHORT Count() const { return SrchAttrItemList::Count(); } SearchAttrItem& operator[](USHORT nPos) const { return SrchAttrItemList::operator[]( nPos ); } SearchAttrItem& GetObject( USHORT nPos ) const { return SrchAttrItemList::GetObject( nPos ); } // der Pointer auf das Item wird nicht kopiert!!! (also nicht l"oschen) void Insert( const SearchAttrItem& rItem ) { SrchAttrItemList::Insert( rItem, SrchAttrItemList::Count() ); } // l"oscht die Pointer auf die Items void Remove( USHORT nPos, USHORT nLen = 1 ); }; #ifndef SV_NODIALOG // class SvxSearchDialogWrapper ------------------------------------------ class SVX_DLLPUBLIC SvxSearchDialogWrapper : public SfxChildWindow { public: SvxSearchDialogWrapper( Window*pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* pInfo ); SFX_DECL_CHILDWINDOW(SvxSearchDialogWrapper); }; // class SvxSearchDialog ------------------------------------------------- /* {k:\svx\prototyp\dialog\srchdlg.hxx} [Beschreibung] In diesem Modeless-Dialog werden die Attribute einer Suche eingestellt und damit eine Suche gestartet. Es sind mehrere Sucharten ( Suchen, Alle suchen, Ersetzen, Alle ersetzen ) m"oglich. [Items] <SvxSearchItem><SID_ATTR_SEARCH> */ class SvxSearchDialog : public SfxModelessDialog { friend class SvxSearchController; friend class SvxSearchDialogWrapper; friend class SvxJSearchOptionsDialog; public: SvxSearchDialog( Window* pParent, SfxBindings& rBind ); SvxSearchDialog( Window* pParent, SfxChildWindow* pChildWin, SfxBindings& rBind ); ~SvxSearchDialog(); virtual BOOL Close(); // Window virtual void Activate(); void GetSearchItems( SfxItemSet& rSet ); void GetReplaceItems( SfxItemSet& rSet ); const SearchAttrItemList* GetSearchItemList() const { return pSearchList; } const SearchAttrItemList* GetReplaceItemList() const { return pReplaceList; } inline BOOL HasSearchAttributes() const; inline BOOL HasReplaceAttributes() const; PushButton& GetReplaceBtn() { return aReplaceBtn; } INT32 GetTransliterationFlags() const; private: FixedText aSearchText; ComboBox aSearchLB; ListBox aSearchTmplLB; FixedInfo aSearchAttrText; FixedText aReplaceText; ComboBox aReplaceLB; ListBox aReplaceTmplLB; FixedInfo aReplaceAttrText; PushButton aSearchBtn; PushButton aSearchAllBtn; FixedLine aSearchCmdLine; PushButton aReplaceBtn; PushButton aReplaceAllBtn; CheckBox aMatchCaseCB; CheckBox aWordBtn; FixedLine aButtonsFL; MoreButton* pMoreBtn; HelpButton aHelpBtn; CancelButton aCloseBtn; FixedLine aOptionsFL; CheckBox aSelectionBtn; CheckBox aBackwardsBtn; CheckBox aRegExpBtn; CheckBox aSimilarityBox; PushButton aSimilarityBtn; CheckBox aLayoutBtn; CheckBox aJapMatchFullHalfWidthCB; CheckBox aJapOptionsCB; PushButton aJapOptionsBtn; PushButton aAttributeBtn; PushButton aFormatBtn; PushButton aNoFormatBtn; FixedLine aCalcFL; FixedText aCalcSearchInFT; ListBox aCalcSearchInLB; FixedText aCalcSearchDirFT; RadioButton aRowsBtn; RadioButton aColumnsBtn; CheckBox aAllSheetsCB; SfxBindings& rBindings; BOOL bWriter; BOOL bSearch; BOOL bFormat; USHORT nOptions; FASTBOOL bSet; FASTBOOL bReadOnly; FASTBOOL bConstruct; ULONG nModifyFlag; String aStylesStr; String aLayoutStr; String aCalcStr; SvStringsDtor aSearchStrings; SvStringsDtor aReplaceStrings; SearchDlg_Impl* pImpl; SearchAttrItemList* pSearchList; SearchAttrItemList* pReplaceList; SvxSearchItem* pSearchItem; SvxSearchController* pSearchController; SvxSearchController* pOptionsController; SvxSearchController* pFamilyController; SvxSearchController* pSearchSetController; SvxSearchController* pReplaceSetController; mutable INT32 nTransliterationFlags; #ifdef _SVX_SRCHDLG_CXX DECL_LINK( ModifyHdl_Impl, ComboBox* pEdit ); DECL_LINK( FlagHdl_Impl, Control* pCtrl ); DECL_LINK( CommandHdl_Impl, Button* pBtn ); DECL_LINK( TemplateHdl_Impl, Button* ); DECL_LINK( FocusHdl_Impl, Control* ); DECL_LINK( LoseFocusHdl_Impl, Control* ); DECL_LINK( FormatHdl_Impl, Button* ); DECL_LINK( NoFormatHdl_Impl, Button* ); DECL_LINK( AttributeHdl_Impl, Button* ); DECL_LINK( TimeoutHdl_Impl, Timer* ); void Construct_Impl(); void InitControls_Impl(); void CalculateDelta_Impl(); void Init_Impl( int bHasItemSet ); void InitAttrList_Impl( const SfxItemSet* pSSet, const SfxItemSet* pRSet ); void Remember_Impl( const String &rStr,BOOL bSearch ); void PaintAttrText_Impl(); String& BuildAttrText_Impl( String& rStr, BOOL bSrchFlag ) const; void TemplatesChanged_Impl( SfxStyleSheetBasePool& rPool ); void EnableControls_Impl( const USHORT nFlags ); void EnableControl_Impl( Control* pCtrl ); void SetItem_Impl( const SvxSearchItem* pItem ); void SetModifyFlag_Impl( const Control* pCtrl ); void SaveToModule_Impl(); void ApplyTransliterationFlags_Impl( INT32 nSettings ); #endif }; inline BOOL SvxSearchDialog::HasSearchAttributes() const { int bLen = aSearchAttrText.GetText().Len(); return ( aSearchAttrText.IsEnabled() && bLen ); } inline BOOL SvxSearchDialog::HasReplaceAttributes() const { int bLen = aReplaceAttrText.GetText().Len(); return ( aReplaceAttrText.IsEnabled() && bLen ); } ////////////////////////////////////////////////////////////////////// /* //CHINA001 class SvxJSearchOptionsDialog : public SfxSingleTabDialog { INT32 nInitialTlFlags; SvxJSearchOptionsPage *pPage; // disallow copy-constructor and assignment-operator for now SvxJSearchOptionsDialog( const SvxJSearchOptionsDialog & ); SvxJSearchOptionsDialog & operator == ( const SvxJSearchOptionsDialog & ); public: SvxJSearchOptionsDialog( Window *pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId, INT32 nInitialFlags ); virtual ~SvxJSearchOptionsDialog(); // Window virtual void Activate(); INT32 GetTransliterationFlags() const; void SetTransliterationFlags( INT32 nSettings ); }; */ //CHINA001 ////////////////////////////////////////////////////////////////////// #endif // SV_NODIALOG #endif // NO_SVX_SEARCH #endif <commit_msg>INTEGRATION: CWS c09v001 (1.14.204); FILE MERGED 2006/01/19 10:44:07 os 1.14.204.1: #130414# extend search dialog to support two external commands<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchdlg.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: rt $ $Date: 2006-02-10 08:55:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_SRCHDLG_HXX #define _SVX_SRCHDLG_HXX // include --------------------------------------------------------------- #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SFX_CHILDWIN_HXX //autogen #include <sfx2/childwin.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #ifndef _SVEDIT_HXX //autogen #include <svtools/svmedit.hxx> #endif #ifndef _SFX_SRCHDEFS_HXX_ #include <sfx2/srchdefs.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // forward --------------------------------------------------------------- class SvxSearchItem; class MoreButton; class SfxStyleSheetBasePool; class SvxJSearchOptionsPage; class SvxSearchController; struct SearchDlg_Impl; #ifndef NO_SVX_SEARCH // struct SearchAttrItem ------------------------------------------------- struct SearchAttrItem { USHORT nSlot; SfxPoolItem* pItem; }; // class SearchAttrItemList ---------------------------------------------- SV_DECL_VARARR_VISIBILITY(SrchAttrItemList, SearchAttrItem, 8, 8, SVX_DLLPUBLIC); class SVX_DLLPUBLIC SearchAttrItemList : private SrchAttrItemList { public: SearchAttrItemList() {} SearchAttrItemList( const SearchAttrItemList& rList ); ~SearchAttrItemList(); void Put( const SfxItemSet& rSet ); SfxItemSet& Get( SfxItemSet& rSet ); void Clear(); USHORT Count() const { return SrchAttrItemList::Count(); } SearchAttrItem& operator[](USHORT nPos) const { return SrchAttrItemList::operator[]( nPos ); } SearchAttrItem& GetObject( USHORT nPos ) const { return SrchAttrItemList::GetObject( nPos ); } // der Pointer auf das Item wird nicht kopiert!!! (also nicht l"oschen) void Insert( const SearchAttrItem& rItem ) { SrchAttrItemList::Insert( rItem, SrchAttrItemList::Count() ); } // l"oscht die Pointer auf die Items void Remove( USHORT nPos, USHORT nLen = 1 ); }; #ifndef SV_NODIALOG // class SvxSearchDialogWrapper ------------------------------------------ class SVX_DLLPUBLIC SvxSearchDialogWrapper : public SfxChildWindow { public: SvxSearchDialogWrapper( Window*pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* pInfo ); SFX_DECL_CHILDWINDOW(SvxSearchDialogWrapper); }; // class SvxSearchDialog ------------------------------------------------- /* {k:\svx\prototyp\dialog\srchdlg.hxx} [Beschreibung] In diesem Modeless-Dialog werden die Attribute einer Suche eingestellt und damit eine Suche gestartet. Es sind mehrere Sucharten ( Suchen, Alle suchen, Ersetzen, Alle ersetzen ) m"oglich. [Items] <SvxSearchItem><SID_ATTR_SEARCH> */ class SvxSearchDialog : public SfxModelessDialog { friend class SvxSearchController; friend class SvxSearchDialogWrapper; friend class SvxJSearchOptionsDialog; public: SvxSearchDialog( Window* pParent, SfxBindings& rBind ); SvxSearchDialog( Window* pParent, SfxChildWindow* pChildWin, SfxBindings& rBind ); ~SvxSearchDialog(); virtual BOOL Close(); // Window virtual void Activate(); void GetSearchItems( SfxItemSet& rSet ); void GetReplaceItems( SfxItemSet& rSet ); const SearchAttrItemList* GetSearchItemList() const { return pSearchList; } const SearchAttrItemList* GetReplaceItemList() const { return pReplaceList; } inline BOOL HasSearchAttributes() const; inline BOOL HasReplaceAttributes() const; PushButton& GetReplaceBtn() { return aReplaceBtn; } INT32 GetTransliterationFlags() const; private: FixedText aSearchText; ComboBox aSearchLB; ListBox aSearchTmplLB; FixedInfo aSearchAttrText; FixedText aReplaceText; ComboBox aReplaceLB; ListBox aReplaceTmplLB; FixedInfo aReplaceAttrText; PushButton aSearchBtn; PushButton aSearchAllBtn; FixedLine aSearchCmdLine; PushButton aReplaceBtn; PushButton aReplaceAllBtn; FixedLine aSearchComponentFL; PushButton aSearchComponent1PB; PushButton aSearchComponent2PB; CheckBox aMatchCaseCB; CheckBox aWordBtn; FixedLine aButtonsFL; MoreButton* pMoreBtn; HelpButton aHelpBtn; CancelButton aCloseBtn; FixedLine aOptionsFL; CheckBox aSelectionBtn; CheckBox aBackwardsBtn; CheckBox aRegExpBtn; CheckBox aSimilarityBox; PushButton aSimilarityBtn; CheckBox aLayoutBtn; CheckBox aJapMatchFullHalfWidthCB; CheckBox aJapOptionsCB; PushButton aJapOptionsBtn; PushButton aAttributeBtn; PushButton aFormatBtn; PushButton aNoFormatBtn; FixedLine aCalcFL; FixedText aCalcSearchInFT; ListBox aCalcSearchInLB; FixedText aCalcSearchDirFT; RadioButton aRowsBtn; RadioButton aColumnsBtn; CheckBox aAllSheetsCB; SfxBindings& rBindings; BOOL bWriter; BOOL bSearch; BOOL bFormat; USHORT nOptions; FASTBOOL bSet; FASTBOOL bReadOnly; FASTBOOL bConstruct; ULONG nModifyFlag; String aStylesStr; String aLayoutStr; String aCalcStr; SvStringsDtor aSearchStrings; SvStringsDtor aReplaceStrings; SearchDlg_Impl* pImpl; SearchAttrItemList* pSearchList; SearchAttrItemList* pReplaceList; SvxSearchItem* pSearchItem; SvxSearchController* pSearchController; SvxSearchController* pOptionsController; SvxSearchController* pFamilyController; SvxSearchController* pSearchSetController; SvxSearchController* pReplaceSetController; mutable INT32 nTransliterationFlags; #ifdef _SVX_SRCHDLG_CXX DECL_LINK( ModifyHdl_Impl, ComboBox* pEdit ); DECL_LINK( FlagHdl_Impl, Control* pCtrl ); DECL_LINK( CommandHdl_Impl, Button* pBtn ); DECL_LINK( TemplateHdl_Impl, Button* ); DECL_LINK( FocusHdl_Impl, Control* ); DECL_LINK( LoseFocusHdl_Impl, Control* ); DECL_LINK( FormatHdl_Impl, Button* ); DECL_LINK( NoFormatHdl_Impl, Button* ); DECL_LINK( AttributeHdl_Impl, Button* ); DECL_LINK( TimeoutHdl_Impl, Timer* ); void Construct_Impl(); void InitControls_Impl(); void CalculateDelta_Impl(); void Init_Impl( int bHasItemSet ); void InitAttrList_Impl( const SfxItemSet* pSSet, const SfxItemSet* pRSet ); void Remember_Impl( const String &rStr,BOOL bSearch ); void PaintAttrText_Impl(); String& BuildAttrText_Impl( String& rStr, BOOL bSrchFlag ) const; void TemplatesChanged_Impl( SfxStyleSheetBasePool& rPool ); void EnableControls_Impl( const USHORT nFlags ); void EnableControl_Impl( Control* pCtrl ); void SetItem_Impl( const SvxSearchItem* pItem ); void SetModifyFlag_Impl( const Control* pCtrl ); void SaveToModule_Impl(); void ApplyTransliterationFlags_Impl( INT32 nSettings ); #endif }; inline BOOL SvxSearchDialog::HasSearchAttributes() const { int bLen = aSearchAttrText.GetText().Len(); return ( aSearchAttrText.IsEnabled() && bLen ); } inline BOOL SvxSearchDialog::HasReplaceAttributes() const { int bLen = aReplaceAttrText.GetText().Len(); return ( aReplaceAttrText.IsEnabled() && bLen ); } ////////////////////////////////////////////////////////////////////// /* //CHINA001 class SvxJSearchOptionsDialog : public SfxSingleTabDialog { INT32 nInitialTlFlags; SvxJSearchOptionsPage *pPage; // disallow copy-constructor and assignment-operator for now SvxJSearchOptionsDialog( const SvxJSearchOptionsDialog & ); SvxJSearchOptionsDialog & operator == ( const SvxJSearchOptionsDialog & ); public: SvxJSearchOptionsDialog( Window *pParent, const SfxItemSet& rOptionsSet, USHORT nUniqueId, INT32 nInitialFlags ); virtual ~SvxJSearchOptionsDialog(); // Window virtual void Activate(); INT32 GetTransliterationFlags() const; void SetTransliterationFlags( INT32 nSettings ); }; */ //CHINA001 ////////////////////////////////////////////////////////////////////// #endif // SV_NODIALOG #endif // NO_SVX_SEARCH #endif <|endoftext|>
<commit_before>#include <cxxtest/TestSuite.h> #include <typeinfo> #include "dicek/vector.hpp" class VectorTest : public CxxTest::TestSuite { public: void testInstance( void ) { using namespace dicek::math; vector<3, double> v; } struct traits { }; void testInstanceTraits( void ) { using namespace dicek::math; vector<3, double, traits> v; } void testDIM( void ) { using namespace dicek::math; static_assert( vector<3, double>::DIM == 3, "vector<3,double>::DIM is not 3" ); TS_ASSERT_EQUALS( 3, ( vector<3, double>::DIM ) ); } void test_real_type( void ) { using namespace dicek::math; static_assert( std::is_same< vector<3, double>::real_type, double>::value, "vector<3, double>::real_type is not double" ); TS_ASSERT( typeid( vector<3, double>::real_type ) == typeid( double ) ); } }; <commit_msg>Use TSM_ macroes instead of TS_ macroes<commit_after>#include <cxxtest/TestSuite.h> #include <typeinfo> #include "dicek/vector.hpp" class VectorTest : public CxxTest::TestSuite { public: void testInstance( void ) { using namespace dicek::math; vector<3, double> v; } struct traits { }; void testInstanceTraits( void ) { using namespace dicek::math; vector<3, double, traits> v; } void testDIM( void ) { using namespace dicek::math; static_assert( vector<3, double>::DIM == 3, "vector<3,double>::DIM is not 3" ); TSM_ASSERT_EQUALS( "vector<3,double>::DIM is not 3", 3, ( vector<3, double>::DIM ) ); } void test_real_type( void ) { using namespace dicek::math; static_assert( std::is_same< vector<3, double>::real_type, double>::value, "vector<3, double>::real_type is not double" ); TSM_ASSERT( "vector<3, double>::real_type is not double", typeid( vector<3, double>::real_type ) == typeid( double ) ); } }; <|endoftext|>
<commit_before>#define CYBOZU_TEST_DISABLE_AUTO_RUN #include <cybozu/test.hpp> #include <cybozu/benchmark.hpp> #include <cybozu/option.hpp> #include <cybozu/xorshift.hpp> #include <mcl/bn384.hpp> #include <mcl/bn.hpp> #include <mcl/lagrange.hpp> using namespace mcl::bn384; mcl::fp::Mode g_mode; #include "bench.hpp" void testLagrange() { puts("testLagrange"); const int k = 7; Fr c[k], x[k], y[k]; for (size_t i = 0; i < k; i++) { c[i].setByCSPRNG(); x[i].setByCSPRNG(); } for (size_t i = 0; i < k; i++) { mcl::evaluatePolynomial(y[i], c, k, x[i]); } Fr s; mcl::LagrangeInterpolation(s, x, y, k); CYBOZU_TEST_EQUAL(s, c[0]); } void testCurve(const mcl::CurveParam& cp) { initPairing(cp, g_mode); G1 P; G2 Q; mapToG1(P, 1); mapToG2(Q, 1); GT e1, e2; pairing(e1, P, Q); cybozu::XorShift rg; mpz_class a, b; Fr r; r.setRand(rg); a = r.getMpz(); r.setRand(rg); b = r.getMpz(); G1 aP; G2 bQ; G1::mul(aP, P, a); G2::mul(bQ, Q, b); pairing(e2, aP, bQ); GT::pow(e1, e1, a * b); CYBOZU_TEST_EQUAL(e1, e2); testBench(P, Q); testLagrange(); } CYBOZU_TEST_AUTO(pairing) { // puts("BN160"); // testCurve(mcl::BN160); puts("BN254"); // support 256-bit pairing testCurve(mcl::BN254); puts("BN381_1"); testCurve(mcl::BN381_1); puts("BN381_2"); testCurve(mcl::BN381_2); puts("BLS12_381"); testCurve(mcl::BLS12_381); // Q is not on EcT, but bad order { const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50"; G2 Q; CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception); } } int main(int argc, char *argv[]) try { cybozu::Option opt; std::string mode; opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)"); if (!opt.parse(argc, argv)) { opt.usage(); return 1; } g_mode = mcl::fp::StrToMode(mode); return cybozu::test::autoRun.run(argc, argv); } catch (std::exception& e) { printf("ERR %s\n", e.what()); return 1; } <commit_msg>ONLY_BENCH for bn384_test<commit_after>#define CYBOZU_TEST_DISABLE_AUTO_RUN #include <cybozu/test.hpp> #include <cybozu/benchmark.hpp> #include <cybozu/option.hpp> #include <cybozu/xorshift.hpp> #include <mcl/bn384.hpp> #include <mcl/bn.hpp> #include <mcl/lagrange.hpp> using namespace mcl::bn384; mcl::fp::Mode g_mode; #include "bench.hpp" void testLagrange() { puts("testLagrange"); const int k = 7; Fr c[k], x[k], y[k]; for (size_t i = 0; i < k; i++) { c[i].setByCSPRNG(); x[i].setByCSPRNG(); } for (size_t i = 0; i < k; i++) { mcl::evaluatePolynomial(y[i], c, k, x[i]); } Fr s; mcl::LagrangeInterpolation(s, x, y, k); CYBOZU_TEST_EQUAL(s, c[0]); } void testCurve(const mcl::CurveParam& cp) { initPairing(cp, g_mode); G1 P; G2 Q; mapToG1(P, 1); mapToG2(Q, 1); GT e1, e2; #ifdef ONLY_BENCH cybozu::CpuClock clk; for (int i = 0; i < 10000; i++) { clk.begin(); pairing(e1, P, Q); clk.end(); } clk.put(); return; #endif pairing(e1, P, Q); cybozu::XorShift rg; mpz_class a, b; Fr r; r.setRand(rg); a = r.getMpz(); r.setRand(rg); b = r.getMpz(); G1 aP; G2 bQ; G1::mul(aP, P, a); G2::mul(bQ, Q, b); pairing(e2, aP, bQ); GT::pow(e1, e1, a * b); CYBOZU_TEST_EQUAL(e1, e2); testBench(P, Q); testLagrange(); } CYBOZU_TEST_AUTO(pairing) { // puts("BN160"); // testCurve(mcl::BN160); puts("BN254"); // support 256-bit pairing testCurve(mcl::BN254); puts("BN381_1"); testCurve(mcl::BN381_1); puts("BN381_2"); testCurve(mcl::BN381_2); puts("BLS12_381"); testCurve(mcl::BLS12_381); // Q is not on EcT, but bad order { const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50"; G2 Q; CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception); } } int main(int argc, char *argv[]) try { cybozu::Option opt; std::string mode; opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)"); if (!opt.parse(argc, argv)) { opt.usage(); return 1; } g_mode = mcl::fp::StrToMode(mode); return cybozu::test::autoRun.run(argc, argv); } catch (std::exception& e) { printf("ERR %s\n", e.what()); return 1; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Various sanity tests with exceptions: // - no memory leak when a custom scalar type trow an exceptions // - todo: complete the list of tests! #define EIGEN_STACK_ALLOCATION_LIMIT 100000000 #include "main.h" struct my_exception { my_exception() {} ~my_exception() {} }; class ScalarWithExceptions { public: ScalarWithExceptions() { init(); } ScalarWithExceptions(const float& _v) { init(); *v = _v; } ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); } ~ScalarWithExceptions() { delete v; instances--; } void init() { v = new float; instances++; } ScalarWithExceptions operator+(const ScalarWithExceptions& other) const { countdown--; if(countdown<=0) throw my_exception(); return ScalarWithExceptions(*v+*other.v); } ScalarWithExceptions operator-(const ScalarWithExceptions& other) const { return ScalarWithExceptions(*v-*other.v); } ScalarWithExceptions operator*(const ScalarWithExceptions& other) const { return ScalarWithExceptions((*v)*(*other.v)); } ScalarWithExceptions& operator+=(const ScalarWithExceptions& other) { *v+=*other.v; return *this; } ScalarWithExceptions& operator-=(const ScalarWithExceptions& other) { *v-=*other.v; return *this; } ScalarWithExceptions& operator=(const ScalarWithExceptions& other) { *v = *(other.v); return *this; } bool operator==(const ScalarWithExceptions& other) const { return *v==*other.v; } bool operator!=(const ScalarWithExceptions& other) const { return *v!=*other.v; } float* v; static int instances; static int countdown; }; int ScalarWithExceptions::instances = 0; int ScalarWithExceptions::countdown = 0; #define CHECK_MEMLEAK(OP) { \ ScalarWithExceptions::countdown = 100; \ int before = ScalarWithExceptions::instances; \ bool exception_thrown = false; \ try { OP; } \ catch (my_exception) { \ exception_thrown = true; \ VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \ } \ VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \ } void memoryleak() { typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType; typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType; { int n = 50; VectorType v0(n), v1(n); MatrixType m0(n,n), m1(n,n), m2(n,n); v0.setOnes(); v1.setOnes(); m0.setOnes(); m1.setOnes(); m2.setOnes(); CHECK_MEMLEAK(v0 = m0 * m1 * v1); CHECK_MEMLEAK(m2 = m0 * m1 * m2); CHECK_MEMLEAK((v0+v1).dot(v0+v1)); } VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \ } void test_exceptions() { CALL_SUBTEST( memoryleak() ); } <commit_msg>Add a few missing standard functions for ScalarWithExceptions type.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Various sanity tests with exceptions: // - no memory leak when a custom scalar type trow an exceptions // - todo: complete the list of tests! #define EIGEN_STACK_ALLOCATION_LIMIT 100000000 #include "main.h" struct my_exception { my_exception() {} ~my_exception() {} }; class ScalarWithExceptions { public: ScalarWithExceptions() { init(); } ScalarWithExceptions(const float& _v) { init(); *v = _v; } ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); } ~ScalarWithExceptions() { delete v; instances--; } void init() { v = new float; instances++; } ScalarWithExceptions operator+(const ScalarWithExceptions& other) const { countdown--; if(countdown<=0) throw my_exception(); return ScalarWithExceptions(*v+*other.v); } ScalarWithExceptions operator-(const ScalarWithExceptions& other) const { return ScalarWithExceptions(*v-*other.v); } ScalarWithExceptions operator*(const ScalarWithExceptions& other) const { return ScalarWithExceptions((*v)*(*other.v)); } ScalarWithExceptions& operator+=(const ScalarWithExceptions& other) { *v+=*other.v; return *this; } ScalarWithExceptions& operator-=(const ScalarWithExceptions& other) { *v-=*other.v; return *this; } ScalarWithExceptions& operator=(const ScalarWithExceptions& other) { *v = *(other.v); return *this; } bool operator==(const ScalarWithExceptions& other) const { return *v==*other.v; } bool operator!=(const ScalarWithExceptions& other) const { return *v!=*other.v; } float* v; static int instances; static int countdown; }; ScalarWithExceptions real(const ScalarWithExceptions &x) { return x; } ScalarWithExceptions imag(const ScalarWithExceptions & ) { return 0; } ScalarWithExceptions conj(const ScalarWithExceptions &x) { return x; } int ScalarWithExceptions::instances = 0; int ScalarWithExceptions::countdown = 0; #define CHECK_MEMLEAK(OP) { \ ScalarWithExceptions::countdown = 100; \ int before = ScalarWithExceptions::instances; \ bool exception_thrown = false; \ try { OP; } \ catch (my_exception) { \ exception_thrown = true; \ VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \ } \ VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \ } void memoryleak() { typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType; typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType; { int n = 50; VectorType v0(n), v1(n); MatrixType m0(n,n), m1(n,n), m2(n,n); v0.setOnes(); v1.setOnes(); m0.setOnes(); m1.setOnes(); m2.setOnes(); CHECK_MEMLEAK(v0 = m0 * m1 * v1); CHECK_MEMLEAK(m2 = m0 * m1 * m2); CHECK_MEMLEAK((v0+v1).dot(v0+v1)); } VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \ } void test_exceptions() { CALL_SUBTEST( memoryleak() ); } <|endoftext|>
<commit_before>#include "test.hh" #include <thread.hh> class Thread : public IThread { public: Thread(void (*exitHook)(), int (*fn)(void *), void *arg) { } MOCK_METHOD0(getRegs, void *()); }; #include "../src/thread.cc" <commit_msg>unit test: Add expectations on mock<commit_after>#include "test.hh" #include <thread.hh> class Thread : public IThread { public: Thread(void (*exitHook)(), int (*fn)(void *), void *arg) { EXPECT_CALL(*this, getRegs()) .Times(AtLeast(1)) .WillRepeatedly(Return((void *)m_regs)) ; } MOCK_METHOD0(getRegs, void *()); uint8_t m_regs[8]; }; #include "../src/thread.cc" <|endoftext|>
<commit_before>#include "testsettings.hpp" #ifdef TEST_ALLOC #include <string> #include <tightdb/util/unique_ptr.hpp> #include <tightdb/util/file.hpp> #include <tightdb/alloc_slab.hpp> #include "test.hpp" using namespace std; using namespace tightdb; using namespace tightdb::util; // Test independence and thread-safety // ----------------------------------- // // All tests must be thread safe and independent of each other. This // is required because it allows for both shuffling of the execution // order and for parallelized testing. // // In particular, avoid using std::rand() since it is not guaranteed // to be thread safe. Instead use the API offered in // `test/util/random.hpp`. // // All files created in tests must use the TEST_PATH macro (or one of // its friends) to obtain a suitable file system path. See // `test/util/test_path.hpp`. // // // Debugging and the ONLY() macro // ------------------------------ // // A simple way of disabling all tests except one called `Foo`, is to // replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the // test suite. Note that you can also use filtering by setting the // environment varible `UNITTEST_FILTER`. See `README.md` for more on // this. // // Another way to debug a particular test, is to copy that test into // `experiments/testcase.cpp` and then run `sh build.sh // check-testcase` (or one of its friends) from the command line. namespace { void set_capacity(char* header, size_t value) { typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[0] = uchar((value >> 16) & 0x000000FF); h[1] = uchar((value >> 8) & 0x000000FF); h[2] = uchar( value & 0x000000FF); } } // anonymous namespace TEST(Alloc_1) { SlabAlloc alloc; CHECK(!alloc.is_attached()); alloc.attach_empty(); CHECK(alloc.is_attached()); CHECK(!alloc.nonempty_attachment()); MemRef mr1 = alloc.alloc(8); MemRef mr2 = alloc.alloc(16); MemRef mr3 = alloc.alloc(256); // Set size in headers (needed for Alloc::free()) set_capacity(mr1.m_addr, 8); set_capacity(mr2.m_addr, 16); set_capacity(mr3.m_addr, 256); // Are pointers 64bit aligned CHECK_EQUAL(0, intptr_t(mr1.m_addr) & 0x7); CHECK_EQUAL(0, intptr_t(mr2.m_addr) & 0x7); CHECK_EQUAL(0, intptr_t(mr3.m_addr) & 0x7); // Do refs translate correctly CHECK_EQUAL(static_cast<void*>(mr1.m_addr), alloc.translate(mr1.m_ref)); CHECK_EQUAL(static_cast<void*>(mr2.m_addr), alloc.translate(mr2.m_ref)); CHECK_EQUAL(static_cast<void*>(mr3.m_addr), alloc.translate(mr3.m_ref)); alloc.free_(mr3.m_ref, mr3.m_addr); alloc.free_(mr2.m_ref, mr2.m_addr); alloc.free_(mr1.m_ref, mr1.m_addr); // SlabAlloc destructor will verify that all is free'd } TEST(Alloc_AttachFile) { GROUP_TEST_PATH(path); { SlabAlloc alloc; bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); CHECK(alloc.nonempty_attachment()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); read_only = true; no_create = true; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); } } TEST(Alloc_BadFile) { GROUP_TEST_PATH(path_1); GROUP_TEST_PATH(path_2); { File file(path_1, File::mode_Append); file.write("foo"); } { SlabAlloc alloc; bool is_shared = false; bool read_only = true; bool no_create = true; bool skip_validate = false; CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); read_only = false; no_create = false; CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); alloc.attach_file(path_2, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); } } TEST(Alloc_AttachBuffer) { GROUP_TEST_PATH(path); // Produce a valid buffer UniquePtr<char[]> buffer; size_t buffer_size; { File::try_remove(path); { SlabAlloc alloc; bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); } { File file(path); buffer_size = size_t(file.get_size()); buffer.reset(static_cast<char*>(malloc(buffer_size))); CHECK(bool(buffer)); file.read(buffer.get(), buffer_size); } File::remove(path); } { SlabAlloc alloc; alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); CHECK(alloc.nonempty_attachment()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); alloc.own_buffer(); buffer.release(); alloc.detach(); CHECK(!alloc.is_attached()); } } TEST(Alloc_BadBuffer) { GROUP_TEST_PATH(path); // Produce an invalid buffer char buffer[32]; for (size_t i=0; i<sizeof buffer; ++i) buffer[i] = char((i+192)%128); { SlabAlloc alloc; CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); } } #endif // TEST_ALLOC <commit_msg>ks-stl-based-slab-alloc: Added allocator unit test<commit_after>#include "testsettings.hpp" #ifdef TEST_ALLOC #include <string> #include <tightdb/util/unique_ptr.hpp> #include <tightdb/util/file.hpp> #include <tightdb/alloc_slab.hpp> #include "test.hpp" using namespace std; using namespace tightdb; using namespace tightdb::util; // Test independence and thread-safety // ----------------------------------- // // All tests must be thread safe and independent of each other. This // is required because it allows for both shuffling of the execution // order and for parallelized testing. // // In particular, avoid using std::rand() since it is not guaranteed // to be thread safe. Instead use the API offered in // `test/util/random.hpp`. // // All files created in tests must use the TEST_PATH macro (or one of // its friends) to obtain a suitable file system path. See // `test/util/test_path.hpp`. // // // Debugging and the ONLY() macro // ------------------------------ // // A simple way of disabling all tests except one called `Foo`, is to // replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the // test suite. Note that you can also use filtering by setting the // environment varible `UNITTEST_FILTER`. See `README.md` for more on // this. // // Another way to debug a particular test, is to copy that test into // `experiments/testcase.cpp` and then run `sh build.sh // check-testcase` (or one of its friends) from the command line. namespace { void set_capacity(char* header, size_t value) { typedef unsigned char uchar; uchar* h = reinterpret_cast<uchar*>(header); h[0] = uchar((value >> 16) & 0x000000FF); h[1] = uchar((value >> 8) & 0x000000FF); h[2] = uchar( value & 0x000000FF); } size_t get_capacity(const char* header) { typedef unsigned char uchar; const uchar* h = reinterpret_cast<const uchar*>(header); return (std::size_t(h[0]) << 16) + (std::size_t(h[1]) << 8) + h[2]; } } // anonymous namespace TEST(Alloc_1) { SlabAlloc alloc; CHECK(!alloc.is_attached()); alloc.attach_empty(); CHECK(alloc.is_attached()); CHECK(!alloc.nonempty_attachment()); MemRef mr1 = alloc.alloc(8); MemRef mr2 = alloc.alloc(16); MemRef mr3 = alloc.alloc(256); // Set size in headers (needed for Alloc::free()) set_capacity(mr1.m_addr, 8); set_capacity(mr2.m_addr, 16); set_capacity(mr3.m_addr, 256); // Are pointers 64bit aligned CHECK_EQUAL(0, intptr_t(mr1.m_addr) & 0x7); CHECK_EQUAL(0, intptr_t(mr2.m_addr) & 0x7); CHECK_EQUAL(0, intptr_t(mr3.m_addr) & 0x7); // Do refs translate correctly CHECK_EQUAL(static_cast<void*>(mr1.m_addr), alloc.translate(mr1.m_ref)); CHECK_EQUAL(static_cast<void*>(mr2.m_addr), alloc.translate(mr2.m_ref)); CHECK_EQUAL(static_cast<void*>(mr3.m_addr), alloc.translate(mr3.m_ref)); alloc.free_(mr3.m_ref, mr3.m_addr); alloc.free_(mr2.m_ref, mr2.m_addr); alloc.free_(mr1.m_ref, mr1.m_addr); // SlabAlloc destructor will verify that all is free'd } TEST(Alloc_AttachFile) { GROUP_TEST_PATH(path); { SlabAlloc alloc; bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); CHECK(alloc.nonempty_attachment()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); read_only = true; no_create = true; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); } } TEST(Alloc_BadFile) { GROUP_TEST_PATH(path_1); GROUP_TEST_PATH(path_2); { File file(path_1, File::mode_Append); file.write("foo"); } { SlabAlloc alloc; bool is_shared = false; bool read_only = true; bool no_create = true; bool skip_validate = false; CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); read_only = false; no_create = false; CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); CHECK(!alloc.is_attached()); alloc.attach_file(path_2, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_file(path_1, is_shared, read_only, no_create, skip_validate), InvalidDatabase); } } TEST(Alloc_AttachBuffer) { GROUP_TEST_PATH(path); // Produce a valid buffer UniquePtr<char[]> buffer; size_t buffer_size; { File::try_remove(path); { SlabAlloc alloc; bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); } { File file(path); buffer_size = size_t(file.get_size()); buffer.reset(static_cast<char*>(malloc(buffer_size))); CHECK(bool(buffer)); file.read(buffer.get(), buffer_size); } File::remove(path); } { SlabAlloc alloc; alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); CHECK(alloc.nonempty_attachment()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); alloc.attach_buffer(buffer.get(), buffer_size); CHECK(alloc.is_attached()); alloc.own_buffer(); buffer.release(); alloc.detach(); CHECK(!alloc.is_attached()); } } TEST(Alloc_BadBuffer) { GROUP_TEST_PATH(path); // Produce an invalid buffer char buffer[32]; for (size_t i=0; i<sizeof buffer; ++i) buffer[i] = char((i+192)%128); { SlabAlloc alloc; CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); bool is_shared = false; bool read_only = false; bool no_create = false; bool skip_validate = false; alloc.attach_file(path, is_shared, read_only, no_create, skip_validate); CHECK(alloc.is_attached()); alloc.detach(); CHECK(!alloc.is_attached()); CHECK_THROW(alloc.attach_buffer(buffer, sizeof buffer), InvalidDatabase); CHECK(!alloc.is_attached()); } } ONLY(Alloc_Fuzzy) { SlabAlloc alloc; vector<MemRef> refs; alloc.attach_empty(); const size_t iterations = 10000; for (size_t iter = 0; iter < iterations; iter++) { int action = rand() % 100; if (action > 45) { // allocate slightly more often than free so that we get a growing mem pool size_t siz = rand() % 10 + 1; siz *= 8; MemRef r = alloc.alloc(siz); refs.push_back(r); set_capacity(r.m_addr, siz); // write some data to the allcoated area so that we can verify it later memset(r.m_addr + 3, (char)r.m_addr, siz - 3); } else if(refs.size() > 0) { // free random entry size_t entry = rand() % refs.size(); alloc.free_(refs[entry].m_ref, refs[entry].m_addr); refs.erase(refs.begin() + entry); } if (iter + 1 == iterations || refs.size() > 10) { // free everything when we have 10 allocations, or when we exit, to not leak while(refs.size() > 0) { MemRef r = refs[0]; size_t siz = get_capacity(r.m_addr); // verify that all the data we wrote during allocation is intact for (size_t c = 3; c < siz; c++) { if (r.m_addr[c] != (char)r.m_addr) { // faster than using 'CHECK' for each character, which is slow CHECK(false); } } alloc.free_(r.m_ref, r.m_addr); refs.erase(refs.begin()); } } } } #endif // TEST_ALLOC <|endoftext|>
<commit_before>/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com) This file is part of the mp++ library. The mp++ library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or both in parallel, as here. The mp++ 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 General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the mp++ library. If not, see https://www.gnu.org/licenses/. */ #include <atomic> #include <cstddef> #include <gmp.h> #include <iostream> #include <limits> #include <random> #include <stdexcept> #include <thread> #include <tuple> #include <type_traits> #include <mp++.hpp> #include "test_utils.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" // TODO: // - assignment ops, copy/move ctors. // - fp ctors. // - string ctors / conversion. // - streaming. // - utility funcs. // - promote() in tests. // - need comprehensive testing for all the special cases for limbs (1 vs 1, 1 vs 2, 2 vs 1, 2 vs 2), // with all the corner cases around upper limits for limbs. static int ntries = 1000; using namespace mppp; using namespace mppp_test; using int_types = std::tuple<char, signed char, unsigned char, short, unsigned short, int, unsigned, long, unsigned long, long long, unsigned long long>; using sizes = std::tuple<std::integral_constant<std::size_t, 1>, std::integral_constant<std::size_t, 2>, std::integral_constant<std::size_t, 3>, std::integral_constant<std::size_t, 6>, std::integral_constant<std::size_t, 10>>; // A seed that will be used to init rngs in the multithreaded tests. Each time a batch of N threads // finishes, this value gets bumped up by N, so that the next time a multithreaded test which uses rng // is launched it will be inited with a different seed. static std::mt19937::result_type mt_rng_seed(0u); struct no_const { }; struct int_ctor_tester { template <typename S> struct runner { template <typename Int> void operator()(const Int &) const { using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, Int>::value)); REQUIRE(lex_cast(Int(0)) == lex_cast(integer{Int(0)})); auto constexpr min = std::numeric_limits<Int>::min(), max = std::numeric_limits<Int>::max(); REQUIRE(lex_cast(min) == lex_cast(integer{min})); REQUIRE(lex_cast(max) == lex_cast(integer{max})); std::atomic<bool> fail(false); auto f = [&fail](unsigned n) { std::uniform_int_distribution<Int> dist(min, max); std::mt19937 eng(static_cast<std::mt19937::result_type>(n + mt_rng_seed)); for (auto i = 0; i < ntries; ++i) { auto tmp = dist(eng); if (lex_cast(tmp) != lex_cast(integer{tmp})) { fail.store(false); } } }; std::thread t0(f, 0u), t1(f, 1u), t2(f, 2u), t3(f, 3u); t0.join(); t1.join(); t2.join(); t3.join(); REQUIRE(!fail.load()); // Update the rng seed so that it does not generate the same sequence // for the next integral type. mt_rng_seed += 4u; } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(int_types{}, runner<S>{}); // Some testing for bool. using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, bool>::value)); REQUIRE((lex_cast(integer{false}) == "0")); REQUIRE((lex_cast(integer{true}) == "1")); REQUIRE((!std::is_constructible<integer, wchar_t>::value)); REQUIRE((!std::is_constructible<integer, no_const>::value)); std::cout << "n static limbs: " << S::value << ", size: " << sizeof(integer) << '\n'; } }; TEST_CASE("integral constructors") { tuple_for_each(sizes{}, int_ctor_tester{}); } using fp_types = std::tuple<float, double #if defined(MPPP_WITH_LONG_DOUBLE) , long double #endif >; struct fp_ctor_tester { template <typename S> struct runner { template <typename Float> void operator()(const Float &) const { using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, Float>::value)); REQUIRE(lex_cast(Float(0)) == lex_cast(integer{Float(0)})); } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(fp_types{}, runner<S>{}); } }; TEST_CASE("floating-point constructors") { tuple_for_each(sizes{}, fp_ctor_tester{}); } struct string_ctor_tester { template <typename S> void operator()(const S &) const { using integer = mp_integer<S::value>; REQUIRE_THROWS_PREDICATE(integer{""}, std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"", 2}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '' is not a valid integer in base 2."; }); REQUIRE_THROWS_PREDICATE((integer{"--31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '--31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"-+31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '-+31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"-31a"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '-31a' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"+a31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '+a31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"+a31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '+a31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"1E45", 12}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '1E45' is not a valid integer in base 12."; }); REQUIRE(lex_cast(integer{"123"}) == "123"); REQUIRE(lex_cast(integer{"-123"}) == "-123"); REQUIRE(lex_cast(integer{"123"}) == "123"); REQUIRE(lex_cast(integer{"0b11", 0}) == "3"); REQUIRE(lex_cast(integer{"-0b11", 0}) == "-3"); REQUIRE(lex_cast(integer{"110", 2}) == "6"); REQUIRE(lex_cast(integer{"-110", 2}) == "-6"); } }; TEST_CASE("string constructor") { tuple_for_each(sizes{}, string_ctor_tester{}); } struct yes { }; struct no { }; template <typename From, typename To> static inline auto test_static_cast(int) -> decltype(void(static_cast<To>(std::declval<const From &>())), yes{}); template <typename From, typename To> static inline no test_static_cast(...); template <typename From, typename To> using is_convertible = std::integral_constant<bool, std::is_same<decltype(test_static_cast<From, To>(0)), yes>::value>; template <typename Integer, typename T> static inline bool roundtrip_conversion(const T &x) { return static_cast<T>(Integer{x}) == x; } struct no_conv { }; struct int_convert_tester { template <typename S> struct runner { template <typename Int> void operator()(const Int &) const { using integer = mp_integer<S::value>; REQUIRE((is_convertible<integer, Int>::value)); REQUIRE(roundtrip_conversion<integer>(0)); auto constexpr min = std::numeric_limits<Int>::min(), max = std::numeric_limits<Int>::max(); REQUIRE(roundtrip_conversion<integer>(min)); REQUIRE(roundtrip_conversion<integer>(max)); REQUIRE(roundtrip_conversion<integer>(min + Int(1))); REQUIRE(roundtrip_conversion<integer>(max - Int(1))); REQUIRE(roundtrip_conversion<integer>(min + Int(2))); REQUIRE(roundtrip_conversion<integer>(max - Int(2))); REQUIRE(roundtrip_conversion<integer>(min + Int(3))); REQUIRE(roundtrip_conversion<integer>(max - Int(3))); REQUIRE(roundtrip_conversion<integer>(min + Int(42))); REQUIRE(roundtrip_conversion<integer>(max - Int(42))); std::atomic<bool> fail(false); auto f = [&fail](unsigned n) { std::uniform_int_distribution<Int> dist(min, max); std::mt19937 eng(static_cast<std::mt19937::result_type>(n + mt_rng_seed)); for (auto i = 0; i < ntries; ++i) { if (!roundtrip_conversion<integer>(dist(eng))) { fail.store(false); } } }; std::thread t0(f, 0u), t1(f, 1u), t2(f, 2u), t3(f, 3u); t0.join(); t1.join(); t2.join(); t3.join(); REQUIRE(!fail.load()); mt_rng_seed += 4u; } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(int_types{}, runner<S>{}); // Some testing for bool. using integer = mp_integer<S::value>; REQUIRE((is_convertible<integer, bool>::value)); REQUIRE(roundtrip_conversion<integer>(true)); REQUIRE(roundtrip_conversion<integer>(false)); // Extra. REQUIRE((!is_convertible<integer, wchar_t>::value)); REQUIRE((!is_convertible<integer, no_conv>::value)); } }; TEST_CASE("integral conversions") { tuple_for_each(sizes{}, int_convert_tester{}); } <commit_msg>clang format.<commit_after>/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com) This file is part of the mp++ library. The mp++ library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or both in parallel, as here. The mp++ 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 General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the mp++ library. If not, see https://www.gnu.org/licenses/. */ #include <atomic> #include <cstddef> #include <gmp.h> #include <iostream> #include <limits> #include <random> #include <stdexcept> #include <thread> #include <tuple> #include <type_traits> #include <mp++.hpp> #include "test_utils.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" // TODO: // - assignment ops, copy/move ctors. // - fp ctors. // - string ctors / conversion. // - streaming. // - utility funcs. // - promote() in tests. // - need comprehensive testing for all the special cases for limbs (1 vs 1, 1 vs 2, 2 vs 1, 2 vs 2), // with all the corner cases around upper limits for limbs. static int ntries = 1000; using namespace mppp; using namespace mppp_test; using int_types = std::tuple<char, signed char, unsigned char, short, unsigned short, int, unsigned, long, unsigned long, long long, unsigned long long>; using sizes = std::tuple<std::integral_constant<std::size_t, 1>, std::integral_constant<std::size_t, 2>, std::integral_constant<std::size_t, 3>, std::integral_constant<std::size_t, 6>, std::integral_constant<std::size_t, 10>>; // A seed that will be used to init rngs in the multithreaded tests. Each time a batch of N threads // finishes, this value gets bumped up by N, so that the next time a multithreaded test which uses rng // is launched it will be inited with a different seed. static std::mt19937::result_type mt_rng_seed(0u); struct no_const { }; struct int_ctor_tester { template <typename S> struct runner { template <typename Int> void operator()(const Int &) const { using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, Int>::value)); REQUIRE(lex_cast(Int(0)) == lex_cast(integer{Int(0)})); auto constexpr min = std::numeric_limits<Int>::min(), max = std::numeric_limits<Int>::max(); REQUIRE(lex_cast(min) == lex_cast(integer{min})); REQUIRE(lex_cast(max) == lex_cast(integer{max})); std::atomic<bool> fail(false); auto f = [&fail](unsigned n) { std::uniform_int_distribution<Int> dist(min, max); std::mt19937 eng(static_cast<std::mt19937::result_type>(n + mt_rng_seed)); for (auto i = 0; i < ntries; ++i) { auto tmp = dist(eng); if (lex_cast(tmp) != lex_cast(integer{tmp})) { fail.store(false); } } }; std::thread t0(f, 0u), t1(f, 1u), t2(f, 2u), t3(f, 3u); t0.join(); t1.join(); t2.join(); t3.join(); REQUIRE(!fail.load()); // Update the rng seed so that it does not generate the same sequence // for the next integral type. mt_rng_seed += 4u; } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(int_types{}, runner<S>{}); // Some testing for bool. using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, bool>::value)); REQUIRE((lex_cast(integer{false}) == "0")); REQUIRE((lex_cast(integer{true}) == "1")); REQUIRE((!std::is_constructible<integer, wchar_t>::value)); REQUIRE((!std::is_constructible<integer, no_const>::value)); std::cout << "n static limbs: " << S::value << ", size: " << sizeof(integer) << '\n'; } }; TEST_CASE("integral constructors") { tuple_for_each(sizes{}, int_ctor_tester{}); } using fp_types = std::tuple<float, double #if defined(MPPP_WITH_LONG_DOUBLE) , long double #endif >; struct fp_ctor_tester { template <typename S> struct runner { template <typename Float> void operator()(const Float &) const { using integer = mp_integer<S::value>; REQUIRE((std::is_constructible<integer, Float>::value)); REQUIRE(lex_cast(Float(0)) == lex_cast(integer{Float(0)})); } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(fp_types{}, runner<S>{}); } }; TEST_CASE("floating-point constructors") { tuple_for_each(sizes{}, fp_ctor_tester{}); } struct string_ctor_tester { template <typename S> void operator()(const S &) const { using integer = mp_integer<S::value>; REQUIRE_THROWS_PREDICATE(integer{""}, std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"", 2}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '' is not a valid integer in base 2."; }); REQUIRE_THROWS_PREDICATE((integer{"--31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '--31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"-+31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '-+31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"-31a"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '-31a' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"+a31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '+a31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"+a31"}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '+a31' is not a valid integer in base 10."; }); REQUIRE_THROWS_PREDICATE((integer{"1E45", 12}), std::invalid_argument, [](const std::invalid_argument &ia) { return std::string(ia.what()) == "The string '1E45' is not a valid integer in base 12."; }); REQUIRE(lex_cast(integer{"123"}) == "123"); REQUIRE(lex_cast(integer{"-123"}) == "-123"); REQUIRE(lex_cast(integer{"123"}) == "123"); REQUIRE(lex_cast(integer{"0b11", 0}) == "3"); REQUIRE(lex_cast(integer{"-0b11", 0}) == "-3"); REQUIRE(lex_cast(integer{"110", 2}) == "6"); REQUIRE(lex_cast(integer{"-110", 2}) == "-6"); } }; TEST_CASE("string constructor") { tuple_for_each(sizes{}, string_ctor_tester{}); } struct yes { }; struct no { }; template <typename From, typename To> static inline auto test_static_cast(int) -> decltype(void(static_cast<To>(std::declval<const From &>())), yes{}); template <typename From, typename To> static inline no test_static_cast(...); template <typename From, typename To> using is_convertible = std::integral_constant<bool, std::is_same<decltype(test_static_cast<From, To>(0)), yes>::value>; template <typename Integer, typename T> static inline bool roundtrip_conversion(const T &x) { return static_cast<T>(Integer{x}) == x; } struct no_conv { }; struct int_convert_tester { template <typename S> struct runner { template <typename Int> void operator()(const Int &) const { using integer = mp_integer<S::value>; REQUIRE((is_convertible<integer, Int>::value)); REQUIRE(roundtrip_conversion<integer>(0)); auto constexpr min = std::numeric_limits<Int>::min(), max = std::numeric_limits<Int>::max(); REQUIRE(roundtrip_conversion<integer>(min)); REQUIRE(roundtrip_conversion<integer>(max)); REQUIRE(roundtrip_conversion<integer>(min + Int(1))); REQUIRE(roundtrip_conversion<integer>(max - Int(1))); REQUIRE(roundtrip_conversion<integer>(min + Int(2))); REQUIRE(roundtrip_conversion<integer>(max - Int(2))); REQUIRE(roundtrip_conversion<integer>(min + Int(3))); REQUIRE(roundtrip_conversion<integer>(max - Int(3))); REQUIRE(roundtrip_conversion<integer>(min + Int(42))); REQUIRE(roundtrip_conversion<integer>(max - Int(42))); std::atomic<bool> fail(false); auto f = [&fail](unsigned n) { std::uniform_int_distribution<Int> dist(min, max); std::mt19937 eng(static_cast<std::mt19937::result_type>(n + mt_rng_seed)); for (auto i = 0; i < ntries; ++i) { if (!roundtrip_conversion<integer>(dist(eng))) { fail.store(false); } } }; std::thread t0(f, 0u), t1(f, 1u), t2(f, 2u), t3(f, 3u); t0.join(); t1.join(); t2.join(); t3.join(); REQUIRE(!fail.load()); mt_rng_seed += 4u; } }; template <typename S> inline void operator()(const S &) const { tuple_for_each(int_types{}, runner<S>{}); // Some testing for bool. using integer = mp_integer<S::value>; REQUIRE((is_convertible<integer, bool>::value)); REQUIRE(roundtrip_conversion<integer>(true)); REQUIRE(roundtrip_conversion<integer>(false)); // Extra. REQUIRE((!is_convertible<integer, wchar_t>::value)); REQUIRE((!is_convertible<integer, no_conv>::value)); } }; TEST_CASE("integral conversions") { tuple_for_each(sizes{}, int_convert_tester{}); } <|endoftext|>
<commit_before>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); ses1.set_severity_level(alert::debug); ses2.set_severity_level(alert::debug); ses3.set_severity_level(alert::debug); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 25; ++i) { std::auto_ptr<alert> a; a = ses1.pop_alert(); if (a.get()) std::cerr << "ses1: " << a->msg() << "\n"; a = ses2.pop_alert(); if (a.get()) std::cerr << "ses2: " << a->msg() << "\n"; a = ses3.pop_alert(); if (a.get()) std::cerr << "ses3: " << a->msg() << "\n"; torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < 5000.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < 5000.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->msg() << std::endl; if (dynamic_cast<torrent_deleted_alert*>(a.get()) != 0) break; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); ptime start = time_now(); alert const* ret = ses1.wait_for_alert(seconds(2)); TEST_CHECK(ret == 0); if (ret != 0) std::cerr << ret->msg() << std::endl; TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start > seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1"); } catch (std::exception&) {} try { remove_all("./tmp2"); } catch (std::exception&) {} try { remove_all("./tmp3"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1/temporary")); TEST_CHECK(!exists("./tmp2/temporary")); TEST_CHECK(!exists("./tmp3/temporary")); remove_all("./tmp1"); remove_all("./tmp2"); remove_all("./tmp3"); return 0; } <commit_msg>updated test_swarm<commit_after>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); ses1.set_severity_level(alert::debug); ses2.set_severity_level(alert::debug); ses3.set_severity_level(alert::debug); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 26; ++i) { std::auto_ptr<alert> a; a = ses1.pop_alert(); if (a.get()) std::cerr << "ses1: " << a->msg() << "\n"; a = ses2.pop_alert(); if (a.get()) std::cerr << "ses2: " << a->msg() << "\n"; a = ses3.pop_alert(); if (a.get()) std::cerr << "ses3: " << a->msg() << "\n"; torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->msg() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now(); alert const* ret = ses1.wait_for_alert(seconds(2)); TEST_CHECK(ret == 0); if (ret != 0) std::cerr << ret->msg() << std::endl; TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start > seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1"); } catch (std::exception&) {} try { remove_all("./tmp2"); } catch (std::exception&) {} try { remove_all("./tmp3"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1/temporary")); TEST_CHECK(!exists("./tmp2/temporary")); TEST_CHECK(!exists("./tmp3/temporary")); remove_all("./tmp1"); remove_all("./tmp2"); remove_all("./tmp3"); return 0; } <|endoftext|>
<commit_before>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); ses1.set_severity_level(alert::debug); ses2.set_severity_level(alert::debug); ses3.set_severity_level(alert::debug); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm"); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 26; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->msg() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now(); alert const* ret = ses1.wait_for_alert(seconds(2)); TEST_CHECK(ret == 0); if (ret != 0) std::cerr << ret->msg() << std::endl; TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start > seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_swarm"); } catch (std::exception&) {} try { remove_all("./tmp2_swarm"); } catch (std::exception&) {} try { remove_all("./tmp3_swarm"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm"); remove_all("./tmp2_swarm"); remove_all("./tmp3_swarm"); return 0; } <commit_msg>made test swarm more likely to pass<commit_after>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); ses1.set_severity_level(alert::debug); ses2.set_severity_level(alert::debug); ses3.set_severity_level(alert::debug); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm"); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 27; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->msg() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now(); alert const* ret = ses1.wait_for_alert(seconds(2)); TEST_CHECK(ret == 0); if (ret != 0) std::cerr << ret->msg() << std::endl; TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start > seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_swarm"); } catch (std::exception&) {} try { remove_all("./tmp2_swarm"); } catch (std::exception&) {} try { remove_all("./tmp3_swarm"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm"); remove_all("./tmp2_swarm"); remove_all("./tmp3_swarm"); return 0; } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // Unit tests for src/core/SkPoint.cpp and its header #include "SkPoint.h" #include "Test.h" // Tests that SkPoint::length() and SkPoint::Length() both return // approximately expectedLength for this (x,y). static void test_length(skiatest::Reporter* reporter, SkScalar x, SkScalar y, SkScalar expectedLength) { SkPoint point; point.set(x, y); SkScalar s1 = point.length(); SkScalar s2 = SkPoint::Length(x, y); REPORTER_ASSERT(reporter, s1 == s2); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(s1, expectedLength)); } // Tests SkPoint::Normalize() for this (x,y) static void test_Normalize(skiatest::Reporter* reporter, SkScalar x, SkScalar y) { SkPoint point; point.set(x, y); SkScalar oldLength = point.length(); SkScalar returned = SkPoint::Normalize(&point); SkScalar newLength = point.length(); REPORTER_ASSERT(reporter, returned == oldLength); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(newLength, SK_Scalar1)); } static void PointTest(skiatest::Reporter* reporter) { test_length(reporter, SkIntToScalar(3), SkIntToScalar(4), SkIntToScalar(5)); test_length(reporter, SkFloatToScalar(0.6f), SkFloatToScalar(0.8f), SK_Scalar1); test_Normalize(reporter, SkIntToScalar(3), SkIntToScalar(4)); test_Normalize(reporter, SkFloatToScalar(0.6f), SkFloatToScalar(0.8f)); } #include "TestClassDef.h" DEFINE_TESTCLASS("Point", PointTestClass, PointTest) <commit_msg>Fix PointTest. https://codereview.appspot.com/6486062/<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // Unit tests for src/core/SkPoint.cpp and its header #include "SkPoint.h" #include "Test.h" // Tests that SkPoint::length() and SkPoint::Length() both return // approximately expectedLength for this (x,y). static void test_length(skiatest::Reporter* reporter, SkScalar x, SkScalar y, SkScalar expectedLength) { SkPoint point; point.set(x, y); SkScalar s1 = point.length(); SkScalar s2 = SkPoint::Length(x, y); //The following should be exactly the same, but need not be. //See http://code.google.com/p/skia/issues/detail?id=816 REPORTER_ASSERT(reporter, SkScalarNearlyEqual(s1, s2)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(s1, expectedLength)); } // Tests SkPoint::Normalize() for this (x,y) static void test_Normalize(skiatest::Reporter* reporter, SkScalar x, SkScalar y) { SkPoint point; point.set(x, y); SkScalar oldLength = point.length(); SkScalar returned = SkPoint::Normalize(&point); SkScalar newLength = point.length(); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(returned, oldLength)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(newLength, SK_Scalar1)); } static void PointTest(skiatest::Reporter* reporter) { test_length(reporter, SkIntToScalar(3), SkIntToScalar(4), SkIntToScalar(5)); test_length(reporter, SkFloatToScalar(0.6f), SkFloatToScalar(0.8f), SK_Scalar1); test_Normalize(reporter, SkIntToScalar(3), SkIntToScalar(4)); test_Normalize(reporter, SkFloatToScalar(0.6f), SkFloatToScalar(0.8f)); } #include "TestClassDef.h" DEFINE_TESTCLASS("Point", PointTestClass, PointTest) <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <plasp/utils/IO.h> #include <plasp/utils/Parser.h> #include <plasp/utils/ParserException.h> //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseSimple) { std::stringstream s("identifier 5 \n-51\t 0 1 expected unexpected"); plasp::utils::Parser p(s); ASSERT_EQ(p.parse<std::string>(), "identifier"); ASSERT_EQ(p.parse<size_t>(), 5u); ASSERT_EQ(p.parse<int>(), -51); ASSERT_EQ(p.parse<bool>(), false); ASSERT_EQ(p.parse<bool>(), true); ASSERT_NO_THROW(p.expect<std::string>("expected")); ASSERT_THROW(p.expect<std::string>("expected"), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseUnsignedNumbers) { std::stringstream s("100 200 -300 -400"); plasp::utils::Parser p(s); ASSERT_EQ(p.parse<int>(), 100); ASSERT_EQ(p.parse<size_t>(), 200u); ASSERT_EQ(p.parse<int>(), -300); ASSERT_THROW(p.parse<size_t>(), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseEndOfFile) { std::stringstream s1("test"); plasp::utils::Parser p1(s1); ASSERT_NO_THROW(p1.expect<std::string>("test")); ASSERT_THROW(p1.parse<std::string>(), plasp::utils::ParserException); std::stringstream s2("test1 test2 test3"); plasp::utils::Parser p2(s2); ASSERT_NO_THROW(p2.expect<std::string>("test1")); ASSERT_NO_THROW(p2.expect<std::string>("test2")); ASSERT_NO_THROW(p2.expect<std::string>("test3")); ASSERT_THROW(p2.parse<std::string>(), plasp::utils::ParserException); std::stringstream s3("-127"); plasp::utils::Parser p3(s3); p3.expect<int>(-127); ASSERT_THROW(p3.parse<int>(), plasp::utils::ParserException); std::stringstream s4("128 -1023 -4095"); plasp::utils::Parser p4(s4); ASSERT_NO_THROW(p4.expect<size_t>(128)); ASSERT_NO_THROW(p4.expect<int>(-1023)); ASSERT_NO_THROW(p4.expect<int>(-4095)); ASSERT_THROW(p4.parse<int>(), plasp::utils::ParserException); std::stringstream s5("0"); plasp::utils::Parser p5(s5); p5.expect<bool>(false); ASSERT_THROW(p5.parse<bool>(), plasp::utils::ParserException); std::stringstream s6("0 1 0"); plasp::utils::Parser p6(s6); ASSERT_NO_THROW(p6.expect<bool>(false)); ASSERT_NO_THROW(p6.expect<bool>(true)); ASSERT_NO_THROW(p6.expect<bool>(false)); ASSERT_THROW(p6.parse<bool>(), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, EscapeASP) { const std::string predicate = "action(stack_on(block-1, block-2, value@3, value@4))"; const auto escaped = plasp::utils::escapeASP(predicate); const auto unescaped = plasp::utils::unescapeASP(escaped); ASSERT_EQ(escaped.find("-"), std::string::npos); ASSERT_EQ(escaped.find("@"), std::string::npos); ASSERT_EQ(predicate, unescaped); } <commit_msg>Added test for Parser’s cursor position.<commit_after>#include <gtest/gtest.h> #include <plasp/utils/IO.h> #include <plasp/utils/Parser.h> #include <plasp/utils/ParserException.h> //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseSimple) { std::stringstream s("identifier 5 \n-51\t 0 1 expected unexpected"); plasp::utils::Parser p(s); ASSERT_EQ(p.parse<std::string>(), "identifier"); ASSERT_EQ(p.parse<size_t>(), 5u); ASSERT_EQ(p.parse<int>(), -51); ASSERT_EQ(p.parse<bool>(), false); ASSERT_EQ(p.parse<bool>(), true); ASSERT_NO_THROW(p.expect<std::string>("expected")); ASSERT_THROW(p.expect<std::string>("expected"), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseUnsignedNumbers) { std::stringstream s("100 200 -300 -400"); plasp::utils::Parser p(s); ASSERT_EQ(p.parse<int>(), 100); ASSERT_EQ(p.parse<size_t>(), 200u); ASSERT_EQ(p.parse<int>(), -300); ASSERT_THROW(p.parse<size_t>(), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParseEndOfFile) { std::stringstream s1("test"); plasp::utils::Parser p1(s1); ASSERT_NO_THROW(p1.expect<std::string>("test")); ASSERT_THROW(p1.parse<std::string>(), plasp::utils::ParserException); std::stringstream s2("test1 test2 test3"); plasp::utils::Parser p2(s2); ASSERT_NO_THROW(p2.expect<std::string>("test1")); ASSERT_NO_THROW(p2.expect<std::string>("test2")); ASSERT_NO_THROW(p2.expect<std::string>("test3")); ASSERT_THROW(p2.parse<std::string>(), plasp::utils::ParserException); std::stringstream s3("-127"); plasp::utils::Parser p3(s3); p3.expect<int>(-127); ASSERT_THROW(p3.parse<int>(), plasp::utils::ParserException); std::stringstream s4("128 -1023 -4095"); plasp::utils::Parser p4(s4); ASSERT_NO_THROW(p4.expect<size_t>(128)); ASSERT_NO_THROW(p4.expect<int>(-1023)); ASSERT_NO_THROW(p4.expect<int>(-4095)); ASSERT_THROW(p4.parse<int>(), plasp::utils::ParserException); std::stringstream s5("0"); plasp::utils::Parser p5(s5); p5.expect<bool>(false); ASSERT_THROW(p5.parse<bool>(), plasp::utils::ParserException); std::stringstream s6("0 1 0"); plasp::utils::Parser p6(s6); ASSERT_NO_THROW(p6.expect<bool>(false)); ASSERT_NO_THROW(p6.expect<bool>(true)); ASSERT_NO_THROW(p6.expect<bool>(false)); ASSERT_THROW(p6.parse<bool>(), plasp::utils::ParserException); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, ParserPosition) { std::stringstream s("123\n4\ntest1\n test2\ntest3 \n\n\n\n\n"); plasp::utils::Parser p(s); ASSERT_EQ(p.row(), 1u); ASSERT_EQ(p.column(), 1u); ASSERT_EQ(p.currentCharacter(), '1'); p.advance(); ASSERT_EQ(p.row(), 1u); ASSERT_EQ(p.column(), 2u); ASSERT_EQ(p.currentCharacter(), '2'); p.advance(); ASSERT_EQ(p.row(), 1u); ASSERT_EQ(p.column(), 3u); ASSERT_EQ(p.currentCharacter(), '3'); p.advance(); ASSERT_EQ(p.row(), 1u); ASSERT_EQ(p.column(), 4u); ASSERT_EQ(p.currentCharacter(), '\n'); p.advance(); ASSERT_EQ(p.row(), 2u); ASSERT_EQ(p.column(), 1u); ASSERT_EQ(p.currentCharacter(), '4'); p.advance(); p.expect<std::string>("test1"); ASSERT_EQ(p.row(), 3u); ASSERT_EQ(p.column(), 6u); p.expect<std::string>("test2"); ASSERT_EQ(p.row(), 4u); ASSERT_EQ(p.column(), 7u); p.expect<std::string>("test3"); ASSERT_EQ(p.row(), 5u); ASSERT_EQ(p.column(), 6u); p.skipWhiteSpace(); ASSERT_TRUE(p.atEndOfFile()); ASSERT_EQ(p.row(), 10u); ASSERT_EQ(p.column(), 1u); } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(UtilsTests, EscapeASP) { const std::string predicate = "action(stack_on(block-1, block-2, value@3, value@4))"; const auto escaped = plasp::utils::escapeASP(predicate); const auto unescaped = plasp::utils::unescapeASP(escaped); ASSERT_EQ(escaped.find("-"), std::string::npos); ASSERT_EQ(escaped.find("@"), std::string::npos); ASSERT_EQ(predicate, unescaped); } <|endoftext|>
<commit_before>#include "KAI/KAI.h" #include <iostream> #include <strstream> #include <stdarg.h> #include "KAI/Translator/Lexer.h" using namespace std; KAI_BEGIN Lexer::Lexer(const char *in) : input(in) { CreateLines(); AddKeywords(); Run(); } void Lexer::AddKeywords() { keyWords["if"] = Token::If; keyWords["else"] = Token::Else; keyWords["for"] = Token::For; keyWords["true"] = Token::True; keyWords["false"] = Token::False; keyWords["return"] = Token::Return; keyWords["self"] = Token::Self; keyWords["fun"] = Token::Fun; keyWords["yield"] = Token::Yield; keyWords["in"] = Token::In; keyWords["while"] = Token::While; keyWords["assert"] = Token::Assert; } bool Lexer::Run() { offset = 0; lineNumber = 0; while (!Failed && NextToken()) ; return Add(Token::None, 0); } void Lexer::Print() const { //std::copy(tokens.begin(), tokens.end(), ostream_iterator<Token>(std::cout, " ")); for (auto tok : tokens) std::cout << tok << " "; std::cout << std::endl; } Slice Lexer::Gather(int (*filt)(int)) { int start = offset; while (filt(Next())) ; return Slice(start, offset); } bool Lexer::Add(Token::Type type, Slice slice) { tokens.push_back(Token(type, *this, lineNumber, slice)); return true; } bool Lexer::Add(Token::Type type, int len) { Add(type, Slice(offset, offset + len)); while (len--) Next(); return true; } bool Lexer::LexAlpha() { Token tok(Token::Ident, *this, lineNumber, Gather(isalnum)); auto kw = keyWords.find(tok.Text()); if (kw != keyWords.end()) tok.type = kw->second; tokens.push_back(tok); return true; } int IsSpaceChar(int ch) { return ch == ' '; } bool Lexer::NextToken() { auto current = Current(); if (current == 0) return false; if (isalpha(current)) return LexAlpha(); if (isdigit(current)) return Add(Token::Int, Gather(isdigit)); switch (current) { case '\t': return Add(Token::Tab); case '\n': return Add(Token::NewLine); case ';': return Add(Token::Semi); case '{': return Add(Token::OpenBrace); case '}': return Add(Token::CloseBrace); case '(': return Add(Token::OpenParan); case ')': return Add(Token::CloseParan); case ':': return Add(Token::Colon); case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar)); case '@': return Add(Token::Lookup); case ',': return Add(Token::Comma); case '*': return Add(Token::Mul); case '[': return Add(Token::OpenSquareBracket); case ']': return Add(Token::CloseSquareBracket); case '=': return AddIfNext('=', Token::Equiv, Token::Assign); case '!': return AddIfNext('=', Token::NotEquiv, Token::Not); case '&': return AddIfNext('&', Token::And, Token::BitAnd); case '|': return AddIfNext('|', Token::Or, Token::BitOr); case '<': return AddIfNext('=', Token::LessEquiv, Token::Less); case '>': return AddIfNext('=', Token::GreaterEquiv, Token::Greater); case '"': return LexString(); case '\'': return LexAlpha(); case '-': if (Peek() == '-') return AddTwoCharOp(Token::Decrement); if (Peek() == '=') return AddTwoCharOp(Token::MinusAssign); return Add(Token::Minus); case '.': if (Peek() == '.') { Next(); if (Peek() == '.') { Next(); return Add(Token::Replace, 3); } return Fail("Two dots doesn't work"); } return Add(Token::Dot); case '+': if (Peek() == '+') return AddTwoCharOp(Token::Increment); if (Peek() == '=') return AddTwoCharOp(Token::PlusAssign); return Add(Token::Plus); case '/': if (Peek() == '/') { Next(); int start = offset; while (Next() != '\n') ; return Add(Token::Comment, offset - start); } return Add(Token::Divide); } LexError("Unrecognised %c"); return false; } bool Process::Fail(const std::string &err) { Failed = true; Error = err; return false; } bool Process::Fail(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buffer[1000]; vsprintf_s(buffer, fmt, ap); return Fail(std::string(buffer)); } char Lexer::Current() const { if (lineNumber == (int)lines.size()) return 0; return Line()[offset]; } const std::string &Lexer::Line() const { return lines[lineNumber]; } char Lexer::Next() { if (EndOfLine()) { offset = 0; ++lineNumber; } else ++offset; if (lineNumber == (int)lines.size()) return 0; return Line()[offset]; } char Lexer::Peek() const { if (EndOfLine()) return 0; return Line()[offset + 1]; } void Lexer::CreateLines() { // ensure we end with a newline. input.push_back('\n'); size_t lineStart = 0; for (size_t n = 0; n < input.size(); ++n) { if (input[n] == '\n') { lines.push_back(input.substr(lineStart, n - lineStart + 1)); lineStart = n + 1; } } } bool Lexer::EndOfLine() const { return offset == (int)Line().size() - 1; } bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType) { if (Peek() == ch) { Next(); return Add(thenType, 2); } return Add(elseType, 1); } bool Lexer::AddTwoCharOp(Token::Type ty) { Add(ty, 2); Next(); return true; } bool Lexer::LexString() { int start = offset; Next(); while (!Failed && Current() != '"') { if (Current() == '\\') { switch (Next()) { case '"': case 'n': case 't': break; default: LexError("Bad escape sequence %c"); return false; } } if (Peek() == 0) { Fail("Bad string literal"); return false; } Next(); } Next(); // the +1 and -1 to remove the start and end double quote characters tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start + 1, offset - 1))); return true; } void Lexer::LexError(const char *text) { Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current())); } std::string Lexer::CreateError(Token tok, const char *fmt, ...) { char buff0[2000]; va_list ap; va_start(ap, fmt); vsprintf_s(buff0, fmt, ap); const char *fmt1 = "%s(%d):[%d]: %s\n"; char buff[2000]; sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0); int beforeContext = 1; int afterContext = 0; const Lexer &lex = *tok.lexer; int start = std::max(0, tok.lineNumber - beforeContext); int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext); strstream err; err << buff << endl; for (int n = start; n <= end; ++n) { for (auto ch : lex.lines[n]) { if (ch == '\t') err << " "; else err << ch; } if (n == tok.lineNumber) { for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch) { if (lex.lines[tok.lineNumber][ch] == '\t') err << " "; else if (ch == tok.slice.Start) { err << '^'; break; } } err << endl; } } err << ends; return err.str(); } KAI_END <commit_msg>Re-ordered methods.<commit_after>#include "KAI/KAI.h" #include <iostream> #include <strstream> #include <stdarg.h> #include "KAI/Translator/Lexer.h" using namespace std; KAI_BEGIN Lexer::Lexer(const char *in) : input(in) { CreateLines(); AddKeywords(); Run(); } void Lexer::CreateLines() { if (input.back() != '\n') input.push_back('\n'); size_t lineStart = 0; for (size_t n = 0; n < input.size(); ++n) { if (input[n] == '\n') { lines.push_back(input.substr(lineStart, n - lineStart + 1)); lineStart = n + 1; } } } void Lexer::AddKeywords() { keyWords["if"] = Token::If; keyWords["else"] = Token::Else; keyWords["for"] = Token::For; keyWords["true"] = Token::True; keyWords["false"] = Token::False; keyWords["return"] = Token::Return; keyWords["self"] = Token::Self; keyWords["fun"] = Token::Fun; keyWords["yield"] = Token::Yield; keyWords["in"] = Token::In; keyWords["while"] = Token::While; keyWords["assert"] = Token::Assert; } bool Lexer::Run() { offset = 0; lineNumber = 0; while (!Failed && NextToken()) ; return Add(Token::None, 0); } bool Lexer::NextToken() { auto current = Current(); if (current == 0) return false; if (isalpha(current)) return LexAlpha(); if (isdigit(current)) return Add(Token::Int, Gather(isdigit)); switch (current) { case '\t': return Add(Token::Tab); case '\n': return Add(Token::NewLine); case ';': return Add(Token::Semi); case '{': return Add(Token::OpenBrace); case '}': return Add(Token::CloseBrace); case '(': return Add(Token::OpenParan); case ')': return Add(Token::CloseParan); case ':': return Add(Token::Colon); case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar)); case '@': return Add(Token::Lookup); case ',': return Add(Token::Comma); case '*': return Add(Token::Mul); case '[': return Add(Token::OpenSquareBracket); case ']': return Add(Token::CloseSquareBracket); case '=': return AddIfNext('=', Token::Equiv, Token::Assign); case '!': return AddIfNext('=', Token::NotEquiv, Token::Not); case '&': return AddIfNext('&', Token::And, Token::BitAnd); case '|': return AddIfNext('|', Token::Or, Token::BitOr); case '<': return AddIfNext('=', Token::LessEquiv, Token::Less); case '>': return AddIfNext('=', Token::GreaterEquiv, Token::Greater); case '"': return LexString(); case '\'': return LexAlpha(); case '-': if (Peek() == '-') return AddTwoCharOp(Token::Decrement); if (Peek() == '=') return AddTwoCharOp(Token::MinusAssign); return Add(Token::Minus); case '.': if (Peek() == '.') { Next(); if (Peek() == '.') { Next(); return Add(Token::Replace, 3); } return Fail("Two dots doesn't work"); } return Add(Token::Dot); case '+': if (Peek() == '+') return AddTwoCharOp(Token::Increment); if (Peek() == '=') return AddTwoCharOp(Token::PlusAssign); return Add(Token::Plus); case '/': if (Peek() == '/') { Next(); int start = offset; while (Next() != '\n') ; return Add(Token::Comment, offset - start); } return Add(Token::Divide); } LexError("Unrecognised %c"); return false; } Slice Lexer::Gather(int (*filt)(int)) { int start = offset; while (filt(Next())) ; return Slice(start, offset); } bool Lexer::Add(Token::Type type, Slice slice) { tokens.push_back(Token(type, *this, lineNumber, slice)); return true; } bool Lexer::Add(Token::Type type, int len) { Add(type, Slice(offset, offset + len)); while (len--) Next(); return true; } bool Lexer::LexAlpha() { Token tok(Token::Ident, *this, lineNumber, Gather(isalnum)); auto kw = keyWords.find(tok.Text()); if (kw != keyWords.end()) tok.type = kw->second; tokens.push_back(tok); return true; } int IsSpaceChar(int ch) { return ch == ' '; } bool Process::Fail(const std::string &err) { Failed = true; Error = err; return false; } bool Process::Fail(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buffer[1000]; vsprintf_s(buffer, fmt, ap); return Fail(std::string(buffer)); } char Lexer::Current() const { if (lineNumber == (int)lines.size()) return 0; return Line()[offset]; } const std::string &Lexer::Line() const { return lines[lineNumber]; } char Lexer::Next() { if (EndOfLine()) { offset = 0; ++lineNumber; } else ++offset; if (lineNumber == (int)lines.size()) return 0; return Line()[offset]; } char Lexer::Peek() const { if (EndOfLine()) return 0; return Line()[offset + 1]; } bool Lexer::EndOfLine() const { return offset == (int)Line().size() - 1; } bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType) { if (Peek() == ch) { Next(); return Add(thenType, 2); } return Add(elseType, 1); } bool Lexer::AddTwoCharOp(Token::Type ty) { Add(ty, 2); Next(); return true; } bool Lexer::LexString() { int start = offset; Next(); while (!Failed && Current() != '"') { if (Current() == '\\') { switch (Next()) { case '"': case 'n': case 't': break; default: LexError("Bad escape sequence %c"); return false; } } if (Peek() == 0) { Fail("Bad string literal"); return false; } Next(); } Next(); // the +1 and -1 to remove the start and end double quote characters tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start + 1, offset - 1))); return true; } void Lexer::LexError(const char *text) { Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current())); } std::string Lexer::CreateError(Token tok, const char *fmt, ...) { char buff0[2000]; va_list ap; va_start(ap, fmt); vsprintf_s(buff0, fmt, ap); const char *fmt1 = "%s(%d):[%d]: %s\n"; char buff[2000]; sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0); int beforeContext = 1; int afterContext = 0; const Lexer &lex = *tok.lexer; int start = std::max(0, tok.lineNumber - beforeContext); int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext); strstream err; err << buff << endl; for (int n = start; n <= end; ++n) { for (auto ch : lex.lines[n]) { if (ch == '\t') err << " "; else err << ch; } if (n == tok.lineNumber) { for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch) { if (lex.lines[tok.lineNumber][ch] == '\t') err << " "; else if (ch == tok.slice.Start) { err << '^'; break; } } err << endl; } } err << ends; return err.str(); } void Lexer::Print() const { for (auto tok : tokens) std::cout << tok << " "; std::cout << std::endl; } KAI_END <|endoftext|>
<commit_before>#include "libyaml_utils.h" #include "logger.h" // --------------------------------------------------------------------------------- // ------------------------------- libyaml test code ------------------------------- // --------------------------------------------------------------------------------- namespace { bool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode) { if (reference_character == mode_type::MAP_TYPE) { if (map_mode) { *add_to_me = mode_type::KEY_TYPE; } else { *add_to_me = mode_type::VALUE_TYPE; } return !map_mode; } else if (reference_character == mode_type::SEQUENCE_TYPE) { *add_to_me = mode_type::SEQUENCE_TYPE; } else { *add_to_me = mode_type::UNKNOWN_TYPE; } return map_mode; } void addTag(YAML::Node* current_node, yaml_char_t* tag) { if (tag) { std::string temp_tag_translator = ((char*)tag); current_node->SetTag(temp_tag_translator); } else if(current_node->Tag().empty()) { current_node->SetTag("?"); } } void addToNode (YAML::Node* addToMe, YAML::Node* add_me, std::stack<YAML::Node>* key_stack, const mode_type* tracking_current_type, yaml_char_t* tag) { addTag(add_me, tag); if (*tracking_current_type == mode_type::SEQUENCE_TYPE) { TEST_PPRINT("squ type\n") addToMe->push_back(*add_me); } else if (*tracking_current_type == mode_type::KEY_TYPE) { TEST_PPRINT("key type\n") key_stack->push(*add_me); (*addToMe)[*add_me]; } else if (*tracking_current_type == mode_type::VALUE_TYPE) { TEST_PPRINT("map type\n") if (!key_stack->empty()) { (*addToMe)[key_stack->top()] = *add_me; key_stack->pop(); } } else { TEST_PPRINT("? type\n") } } bool endEventAddition (std::vector<YAML::Node>* libyaml_local_output, std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack, bool map_mode, std::stack<YAML::Node>* key_stack) { if (libyaml_local_output->size() > 1) { mode_stack->pop(); if (mode_stack->top() == mode_type::MAP_TYPE) { map_mode = map_mode_stack->top(); map_mode_stack->pop(); } mode_type temp_position_info; positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode); YAML::Node temp_node = libyaml_local_output->back(); libyaml_local_output->pop_back(); addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr); } return map_mode; } void restartVariables (std::stack<YAML::Node>* key_stack, std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack, std::vector<YAML::Node>* libyaml_local_output, std::vector<YAML::Node>* libyaml_final_output, bool* map_mode, std::map<std::string, YAML::Node>* anchor_map) { while (!key_stack->empty()) { key_stack->pop(); } while (!mode_stack->empty()) { mode_stack->pop(); } mode_stack->push(mode_type::UNKNOWN_TYPE); while (!map_mode_stack->empty()) { map_mode_stack->pop(); } if (!libyaml_local_output->empty()) { libyaml_final_output->push_back(libyaml_local_output->back()); } libyaml_local_output->clear(); *map_mode = true; anchor_map->clear(); } } std::vector<YAML::Node>& libyaml_parsing::parseLibyaml (const uint8_t* input, size_t input_size, std::unique_ptr<std::string>* error_message_container) { yaml_parser_t parser; yaml_event_t event; std::vector<YAML::Node> libyaml_local_output; std::vector<YAML::Node>* libyaml_final_output = new std::vector<YAML::Node>; std::stack<YAML::Node> key_stack; std::stack<mode_type> mode_stack; mode_stack.push(mode_type::UNKNOWN_TYPE); std::stack<bool> map_mode_stack; bool map_mode = true; std::map<std::string, YAML::Node> anchor_map; if (!yaml_parser_initialize(&parser)) { TEST_PPRINT("ERROR: Failed to initialize\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } yaml_parser_set_input_string(&parser, input, input_size); while (true) { YAML::Node new_node; yaml_event_type_t type; mode_type tracking_current_type; if (!yaml_parser_parse(&parser, &event)) { yaml_event_delete(&event); yaml_parser_delete(&parser); TEST_PPRINT("ERROR: Bad parsing\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } type = event.type; switch (type) { case YAML_STREAM_END_EVENT: TEST_PPRINT("STR-\n"); break; case YAML_DOCUMENT_END_EVENT: TEST_PPRINT("DOC-\n"); restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output, libyaml_final_output, &map_mode, &anchor_map); break; case YAML_DOCUMENT_START_EVENT: TEST_PPRINT("DOC+\n"); restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output, libyaml_final_output, &map_mode, &anchor_map); break; case YAML_MAPPING_END_EVENT: TEST_PPRINT("MAP-\n"); map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack); break; case YAML_SEQUENCE_END_EVENT: TEST_PPRINT("SQU-\n"); map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack); break; case YAML_MAPPING_START_EVENT: TEST_PPRINT("MAP+\n"); libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map)); addTag(&libyaml_local_output.back(), event.data.sequence_start.tag); if (!mode_stack.empty()) { positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); } if (mode_stack.top() == mode_type::MAP_TYPE) { map_mode_stack.push(!map_mode); } mode_stack.push(mode_type::MAP_TYPE); map_mode = true; if (event.data.mapping_start.anchor) { TEST_PPRINT("ANCH-map+\n"); anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back(); } break; case YAML_SEQUENCE_START_EVENT: TEST_PPRINT("SQU+\n"); libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence)); addTag(&libyaml_local_output.back(), event.data.sequence_start.tag); if (mode_stack.top() == mode_type::MAP_TYPE) { map_mode_stack.push(!map_mode); } mode_stack.push(mode_type::SEQUENCE_TYPE); if (event.data.sequence_start.anchor) { TEST_PPRINT("ANCH-squ+\n"); anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back(); } break; case YAML_SCALAR_EVENT: { TEST_PPRINT("SCL\n"); YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length)); addTag(&add_me, event.data.scalar.tag); if (event.data.scalar.anchor) { TEST_PPRINT("ANCH-scl\n"); std::string temp_translator = ((char*)event.data.scalar.anchor); if (event.data.scalar.value) { TEST_PPRINT("value\n"); if(event.data.scalar.length != 0) { anchor_map[temp_translator] = add_me; map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); if (libyaml_local_output.empty()) { libyaml_local_output.push_back(add_me); } else { addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, event.data.scalar.tag); } } else { TEST_PPRINT("empty\n"); if (mode_stack.top() == mode_type::SEQUENCE_TYPE) { TEST_PPRINT("sequence\n"); add_me = YAML::Node(YAML::NodeType::Null); libyaml_local_output.back().push_back(add_me); break; } mode_stack.pop(); if (!mode_stack.empty()) { if (mode_stack.top() == mode_type::MAP_TYPE) { TEST_PPRINT("map\n"); map_mode = map_mode_stack.top(); map_mode_stack.pop(); } libyaml_local_output.pop_back(); } else { libyaml_local_output.push_back(YAML::Node()); } } } } else { TEST_PPRINT("normal\n"); map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); if (event.data.scalar.length <= 0 && !event.data.scalar.tag && event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE) { TEST_PPRINT("Begin from nothing\n"); add_me = YAML::Node(); } if (libyaml_local_output.empty()) { libyaml_local_output.push_back(add_me); } else { addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, event.data.scalar.tag); } } break; } case YAML_ALIAS_EVENT: { TEST_PPRINT("ALI\n"); std::string temp_translator = ((char*) event.data.alias.anchor); if(anchor_map.find(temp_translator) != anchor_map.end()) { map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], &key_stack, &tracking_current_type, nullptr); } else { yaml_event_delete(&event); yaml_parser_delete(&parser); TEST_PPRINT("ERROR: Missing anchor\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } break; } default: break; } yaml_event_delete(&event); if (type == YAML_STREAM_END_EVENT) { break; } } yaml_parser_delete(&parser); fflush(stdout); return *libyaml_final_output; }<commit_msg>More robust libyaml_utils<commit_after>#include "libyaml_utils.h" #include "logger.h" // --------------------------------------------------------------------------------- // ------------------------------- libyaml test code ------------------------------- // --------------------------------------------------------------------------------- namespace { bool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode) { if (add_to_me != nullptr) { if (reference_character == mode_type::MAP_TYPE) { if (map_mode) { *add_to_me = mode_type::KEY_TYPE; } else { *add_to_me = mode_type::VALUE_TYPE; } return !map_mode; } else if (reference_character == mode_type::SEQUENCE_TYPE) { *add_to_me = mode_type::SEQUENCE_TYPE; } else { *add_to_me = mode_type::UNKNOWN_TYPE; } } return map_mode; } void addTag(YAML::Node* current_node, yaml_char_t* tag) { if (current_node != nullptr) { if (tag) { std::string temp_tag_translator = ((char*)tag); current_node->SetTag(temp_tag_translator); } else if(current_node->Tag().empty()) { current_node->SetTag("?"); } } } void addToNode (YAML::Node* addToMe, YAML::Node* add_me, std::stack<YAML::Node>* key_stack, const mode_type* tracking_current_type, yaml_char_t* tag) { addTag(add_me, tag); if (tracking_current_type != nullptr && addToMe != nullptr) { if (*tracking_current_type == mode_type::SEQUENCE_TYPE) { TEST_PPRINT("squ type\n") addToMe->push_back(*add_me); } else if (*tracking_current_type == mode_type::KEY_TYPE) { TEST_PPRINT("key type\n") key_stack->push(*add_me); (*addToMe)[*add_me]; } else if (*tracking_current_type == mode_type::VALUE_TYPE) { TEST_PPRINT("map type\n") if (!key_stack->empty()) { (*addToMe)[key_stack->top()] = *add_me; key_stack->pop(); } } else { TEST_PPRINT("? type\n") } } } bool endEventAddition (std::vector<YAML::Node>* libyaml_local_output, std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack, bool map_mode, std::stack<YAML::Node>* key_stack) { if (libyaml_local_output->size() > 1 && !mode_stack->empty()) { mode_stack->pop(); if (mode_stack->top() == mode_type::MAP_TYPE && !map_mode_stack->empty()) { map_mode = map_mode_stack->top(); map_mode_stack->pop(); } mode_type temp_position_info; positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode); YAML::Node temp_node = libyaml_local_output->back(); libyaml_local_output->pop_back(); addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr); } return map_mode; } void restartVariables (std::stack<YAML::Node>* key_stack, std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack, std::vector<YAML::Node>* libyaml_local_output, std::vector<YAML::Node>* libyaml_final_output, bool* map_mode, std::map<std::string, YAML::Node>* anchor_map) { while (!key_stack->empty()) { key_stack->pop(); } while (!mode_stack->empty()) { mode_stack->pop(); } mode_stack->push(mode_type::UNKNOWN_TYPE); while (!map_mode_stack->empty()) { map_mode_stack->pop(); } if (!libyaml_local_output->empty()) { libyaml_final_output->push_back(libyaml_local_output->back()); } libyaml_local_output->clear(); *map_mode = true; anchor_map->clear(); } std::string parseLibyaml(const std::string name_of_file, std::string* error_message_container) { return name_of_file; } } std::vector<YAML::Node>& libyaml_parsing::parseLibyaml (const uint8_t* input, size_t input_size, std::unique_ptr<std::string>* error_message_container) { yaml_parser_t parser; yaml_event_t event; std::vector<YAML::Node> libyaml_local_output; std::vector<YAML::Node>* libyaml_final_output = new std::vector<YAML::Node>; std::stack<YAML::Node> key_stack; std::stack<mode_type> mode_stack; mode_stack.push(mode_type::UNKNOWN_TYPE); std::stack<bool> map_mode_stack; bool map_mode = true; std::map<std::string, YAML::Node> anchor_map; if (!yaml_parser_initialize(&parser)) { TEST_PPRINT("ERROR: Failed to initialize\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } yaml_parser_set_input_string(&parser, input, input_size); while (true) { YAML::Node new_node; yaml_event_type_t type; mode_type tracking_current_type; if (!yaml_parser_parse(&parser, &event)) { yaml_event_delete(&event); yaml_parser_delete(&parser); TEST_PPRINT("ERROR: Bad parsing\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } type = event.type; switch (type) { case YAML_STREAM_END_EVENT: TEST_PPRINT("STR-\n"); break; case YAML_DOCUMENT_END_EVENT: TEST_PPRINT("DOC-\n"); restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output, libyaml_final_output, &map_mode, &anchor_map); break; case YAML_DOCUMENT_START_EVENT: TEST_PPRINT("DOC+\n"); restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output, libyaml_final_output, &map_mode, &anchor_map); break; case YAML_MAPPING_END_EVENT: TEST_PPRINT("MAP-\n"); map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack); break; case YAML_SEQUENCE_END_EVENT: TEST_PPRINT("SQU-\n"); map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack); break; case YAML_MAPPING_START_EVENT: TEST_PPRINT("MAP+\n"); libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map)); addTag(&libyaml_local_output.back(), event.data.sequence_start.tag); if (!mode_stack.empty()) { positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); } if (mode_stack.top() == mode_type::MAP_TYPE) { map_mode_stack.push(!map_mode); } mode_stack.push(mode_type::MAP_TYPE); map_mode = true; if (event.data.mapping_start.anchor) { TEST_PPRINT("ANCH-map+\n"); anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back(); } break; case YAML_SEQUENCE_START_EVENT: TEST_PPRINT("SQU+\n"); libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence)); addTag(&libyaml_local_output.back(), event.data.sequence_start.tag); if (mode_stack.top() == mode_type::MAP_TYPE) { map_mode_stack.push(!map_mode); } mode_stack.push(mode_type::SEQUENCE_TYPE); if (event.data.sequence_start.anchor) { TEST_PPRINT("ANCH-squ+\n"); anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back(); } break; case YAML_SCALAR_EVENT: { TEST_PPRINT("SCL\n"); YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length)); addTag(&add_me, event.data.scalar.tag); if (event.data.scalar.anchor) { TEST_PPRINT("ANCH-scl\n"); std::string temp_translator = ((char*)event.data.scalar.anchor); if (event.data.scalar.value) { TEST_PPRINT("value\n"); if(event.data.scalar.length != 0) { anchor_map[temp_translator] = add_me; map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); if (libyaml_local_output.empty()) { libyaml_local_output.push_back(add_me); } else { addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, event.data.scalar.tag); } } else { TEST_PPRINT("empty\n"); if (mode_stack.top() == mode_type::SEQUENCE_TYPE) { TEST_PPRINT("sequence\n"); add_me = YAML::Node(YAML::NodeType::Null); libyaml_local_output.back().push_back(add_me); break; } mode_stack.pop(); if (!mode_stack.empty()) { if (mode_stack.top() == mode_type::MAP_TYPE) { TEST_PPRINT("map\n"); map_mode = map_mode_stack.top(); map_mode_stack.pop(); } libyaml_local_output.pop_back(); } else { libyaml_local_output.push_back(YAML::Node()); } } } } else { TEST_PPRINT("normal\n"); if (mode_stack.empty()) { break; } map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); if (event.data.scalar.length <= 0 && !event.data.scalar.tag && event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE) { TEST_PPRINT("Begin from nothing\n"); add_me = YAML::Node(); } if (libyaml_local_output.empty()) { libyaml_local_output.push_back(add_me); } else { addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, event.data.scalar.tag); } } break; } case YAML_ALIAS_EVENT: { TEST_PPRINT("ALI\n"); std::string temp_translator = ((char*) event.data.alias.anchor); if(anchor_map.find(temp_translator) != anchor_map.end()) { map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode); addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], &key_stack, &tracking_current_type, nullptr); } else { yaml_event_delete(&event); yaml_parser_delete(&parser); TEST_PPRINT("ERROR: Missing anchor\n"); *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR")); return *libyaml_final_output; } break; } default: break; } yaml_event_delete(&event); if (type == YAML_STREAM_END_EVENT) { break; } } yaml_parser_delete(&parser); fflush(stdout); return *libyaml_final_output; }<|endoftext|>
<commit_before>#include <SFML-Book/Piece.hpp> #include <SFML-Book/converter.hpp> #include <iostream> namespace book { const sf::Color Piece::Tetrimino_colors[Piece::Tetrimino_Types::SIZE]= { sf::Color::Blue, sf::Color::Red, sf::Color::Green, sf::Color::Cyan, sf::Color::Magenta, sf::Color::White, sf::Color(195,132,58) }; Piece::Piece(b2World& world,int pos_x,int pos_y,Tetrimino_Types type,float rotation) : _world(world) { b2BodyDef bodyDef; bodyDef.position.Set(book::converter::pixel_to_meters<double>(pos_x),book::converter::pixel_to_meters<double>(pos_y)); bodyDef.type = b2_dynamicBody; bodyDef.angle = converter::deg_to_rad(rotation); _body = world.CreateBody(&bodyDef); switch(type) { case Tetrimino_Types::O : { create_part(0,0,type); create_part(0,1,type); create_part(1,0,type); create_part(1,1,type); }break; case Tetrimino_Types::I : { create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); create_part(3,0,type); }break; case Tetrimino_Types::S : { create_part(0,1,type); create_part(1,1,type); create_part(1,0,type); create_part(2,0,type); }break; case Tetrimino_Types::Z : { create_part(0,0,type); create_part(1,0,type); create_part(1,1,type); create_part(2,1,type); }break; case Tetrimino_Types::L : { create_part(0,1,type); create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); }break; case Tetrimino_Types::J : { create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); create_part(2,1,type); }break; case Tetrimino_Types::T : { create_part(0,0,type); create_part(1,0,type); create_part(1,1,type); create_part(2,0,type); }break; default:break; } _body->SetUserData(this); update(); } Piece::~Piece() { //destroy shapes for(b2Fixture* fixture=_body->GetFixtureList();fixture!=nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); fixture->SetUserData(nullptr); delete shape; } _world.DestroyBody(_body); } b2Fixture* Piece::create_part(int pos_x,int pos_y,Tetrimino_Types type) { b2PolygonShape b2shape; b2shape.SetAsBox(converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2),converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2) ,b2Vec2(converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2+(pos_x*BOOK_BOX_SIZE)),converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2+(pos_y*BOOK_BOX_SIZE))),0); b2FixtureDef fixtureDef; fixtureDef.density = 1.0; fixtureDef.friction = 0.5; fixtureDef.restitution= 0.4; fixtureDef.shape = &b2shape; b2Fixture* fixture = _body->CreateFixture(&fixtureDef); sf::ConvexShape* shape = new sf::ConvexShape((unsigned int)b2shape.GetVertexCount()); shape->setFillColor(Tetrimino_colors[type]); shape->setOutlineThickness(1.0f); shape->setOutlineColor(sf::Color(128,128,128)); fixture->SetUserData(shape); return fixture; } void Piece::update() { const b2Transform& xf = _body->GetTransform(); for(b2Fixture* fixture = _body->GetFixtureList(); fixture != nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); const b2PolygonShape* b2shape = static_cast<b2PolygonShape*>(fixture->GetShape()); const uint32 count = b2shape->GetVertexCount(); for(uint32 i=0;i<count;++i) { b2Vec2 vertex = b2Mul(xf,b2shape->m_vertices[i]); shape->setPoint(i,sf::Vector2f(converter::meters_to_pixels(vertex.x), converter::meters_to_pixels(vertex.y))); } } } void Piece::rotate(float angle) { _body->ApplyTorque((float32)converter::deg_to_rad(angle),true); //_body->SetAngularVelocity((float32)converter::deg_to_rad(angle)); } void Piece::moveX(int direction) { _body->ApplyForceToCenter(b2Vec2(converter::pixel_to_meters(direction),0),true); } b2Body* Piece::getBody()const { return _body; } void Piece::draw(sf::RenderTarget& target, sf::RenderStates states) const { for(const b2Fixture* fixture=_body->GetFixtureList();fixture!=nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); if(shape) target.draw(*shape,states); } } } <commit_msg>fix Box2d version<commit_after>#include <SFML-Book/Piece.hpp> #include <SFML-Book/converter.hpp> #include <iostream> namespace book { const sf::Color Piece::Tetrimino_colors[Piece::Tetrimino_Types::SIZE]= { sf::Color::Blue, sf::Color::Red, sf::Color::Green, sf::Color::Cyan, sf::Color::Magenta, sf::Color::White, sf::Color(195,132,58) }; Piece::Piece(b2World& world,int pos_x,int pos_y,Tetrimino_Types type,float rotation) : _world(world) { b2BodyDef bodyDef; bodyDef.position.Set(book::converter::pixel_to_meters<double>(pos_x),book::converter::pixel_to_meters<double>(pos_y)); bodyDef.type = b2_dynamicBody; bodyDef.angle = converter::deg_to_rad(rotation); _body = world.CreateBody(&bodyDef); switch(type) { case Tetrimino_Types::O : { create_part(0,0,type); create_part(0,1,type); create_part(1,0,type); create_part(1,1,type); }break; case Tetrimino_Types::I : { create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); create_part(3,0,type); }break; case Tetrimino_Types::S : { create_part(0,1,type); create_part(1,1,type); create_part(1,0,type); create_part(2,0,type); }break; case Tetrimino_Types::Z : { create_part(0,0,type); create_part(1,0,type); create_part(1,1,type); create_part(2,1,type); }break; case Tetrimino_Types::L : { create_part(0,1,type); create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); }break; case Tetrimino_Types::J : { create_part(0,0,type); create_part(1,0,type); create_part(2,0,type); create_part(2,1,type); }break; case Tetrimino_Types::T : { create_part(0,0,type); create_part(1,0,type); create_part(1,1,type); create_part(2,0,type); }break; default:break; } _body->SetUserData(this); update(); } Piece::~Piece() { //destroy shapes for(b2Fixture* fixture=_body->GetFixtureList();fixture!=nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); fixture->SetUserData(nullptr); delete shape; } _world.DestroyBody(_body); } b2Fixture* Piece::create_part(int pos_x,int pos_y,Tetrimino_Types type) { b2PolygonShape b2shape; b2shape.SetAsBox(converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2),converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2) ,b2Vec2(converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2+(pos_x*BOOK_BOX_SIZE)),converter::pixel_to_meters<double>(BOOK_BOX_SIZE_2+(pos_y*BOOK_BOX_SIZE))),0); b2FixtureDef fixtureDef; fixtureDef.density = 1.0; fixtureDef.friction = 0.5; fixtureDef.restitution= 0.4; fixtureDef.shape = &b2shape; b2Fixture* fixture = _body->CreateFixture(&fixtureDef); sf::ConvexShape* shape = new sf::ConvexShape((unsigned int)b2shape.GetVertexCount()); shape->setFillColor(Tetrimino_colors[type]); shape->setOutlineThickness(1.0f); shape->setOutlineColor(sf::Color(128,128,128)); fixture->SetUserData(shape); return fixture; } void Piece::update() { const b2Transform& xf = _body->GetTransform(); for(b2Fixture* fixture = _body->GetFixtureList(); fixture != nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); const b2PolygonShape* b2shape = static_cast<b2PolygonShape*>(fixture->GetShape()); const uint32 count = b2shape->GetVertexCount(); for(uint32 i=0;i<count;++i) { b2Vec2 vertex = b2Mul(xf,b2shape->m_vertices[i]); shape->setPoint(i,sf::Vector2f(converter::meters_to_pixels(vertex.x), converter::meters_to_pixels(vertex.y))); } } } void Piece::rotate(float angle) { _body->ApplyTorque((float32)converter::deg_to_rad(angle)); //_body->SetAngularVelocity((float32)converter::deg_to_rad(angle)); } void Piece::moveX(int direction) { _body->ApplyForceToCenter(b2Vec2(converter::pixel_to_meters(direction),0)); } b2Body* Piece::getBody()const { return _body; } void Piece::draw(sf::RenderTarget& target, sf::RenderStates states) const { for(const b2Fixture* fixture=_body->GetFixtureList();fixture!=nullptr;fixture=fixture->GetNext()) { sf::ConvexShape* shape = static_cast<sf::ConvexShape*>(fixture->GetUserData()); if(shape) target.draw(*shape,states); } } } <|endoftext|>
<commit_before>// 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 __PROCESS_GRPC_HPP__ #define __PROCESS_GRPC_HPP__ #include <chrono> #include <memory> #include <string> #include <thread> #include <type_traits> #include <utility> #include <google/protobuf/message.h> #include <grpcpp/grpcpp.h> #include <process/check.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/pid.hpp> #include <process/process.hpp> #include <stout/duration.hpp> #include <stout/error.hpp> #include <stout/lambda.hpp> #include <stout/nothing.hpp> #include <stout/try.hpp> // This file provides libprocess "support" for using gRPC. In particular, it // defines two wrapper classes: `client::Connection` which represents a // connection to a gRPC server, and `client::Runtime` which integrates an event // loop waiting for gRPC responses and provides the `call` interface to create // an asynchronous gRPC call and return a `Future`. #define GRPC_CLIENT_METHOD(service, rpc) \ (&service::Stub::PrepareAsync##rpc) namespace process { namespace grpc { /** * Represents errors caused by non-OK gRPC statuses. See: * https://grpc.io/grpc/cpp/classgrpc_1_1_status.html */ class StatusError : public Error { public: StatusError(::grpc::Status _status) : Error(_status.error_message()), status(std::move(_status)) { CHECK(!status.ok()); } const ::grpc::Status status; }; namespace client { // Internal helper utilities. namespace internal { template <typename T> struct MethodTraits; // Undefined. template <typename Stub, typename Request, typename Response> struct MethodTraits< std::unique_ptr<::grpc::ClientAsyncResponseReader<Response>>(Stub::*)( ::grpc::ClientContext*, const Request&, ::grpc::CompletionQueue*)> { typedef Stub stub_type; typedef Request request_type; typedef Response response_type; }; } // namespace internal { /** * A copyable interface to manage a connection to a gRPC server. All * `Connection` copies share the same gRPC channel which is thread safe. Note * that the actual connection is established lazily by the gRPC library at the * time an RPC is made to the channel. */ class Connection { public: Connection( const std::string& uri, const std::shared_ptr<::grpc::ChannelCredentials>& credentials = ::grpc::InsecureChannelCredentials()) : channel(::grpc::CreateChannel(uri, credentials)) {} explicit Connection(std::shared_ptr<::grpc::Channel> _channel) : channel(std::move(_channel)) {} const std::shared_ptr<::grpc::Channel> channel; }; /** * Defines the gRPC options for each call. */ struct CallOptions { // Enable the gRPC wait-for-ready semantics by default so the call will be // retried if the connection is not ready. See: // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md bool wait_for_ready = true; // The timeout of the call. A `DEADLINE_EXCEEDED` status will be returned if // there is no response in the specified amount of time. This is required to // avoid the call from being pending forever. Duration timeout = Seconds(60); }; /** * A copyable interface to manage an internal runtime process for asynchronous * gRPC calls. A runtime process keeps a gRPC `CompletionQueue` to manage * outstanding requests, a looper thread to wait for any incoming responses from * the `CompletionQueue`, and handles the requests and responses. All `Runtime` * copies share the same runtime process. Usually we only need a single runtime * process to handle all gRPC calls, but multiple runtime processes can be * instantiated for better parallelism and isolation. * * NOTE: The caller must call `terminate` to drain the `CompletionQueue` before * finalizing libprocess to gracefully terminate the gRPC runtime. */ class Runtime { public: Runtime() : data(new Data()) {} /** * Sends an asynchronous gRPC call. * * This function returns a `Future` of a `Try` such that the response protobuf * is returned only if the gRPC call returns an OK status to ensure type * safety (see https://github.com/grpc/grpc/issues/12824). Note that the * future never fails; it will return a `StatusError` if a non-OK status is * returned for the call, so the caller can handle the error programmatically. * * @param connection A connection to a gRPC server. * @param method The asynchronous gRPC call to make. This should be obtained * by the `GRPC_CLIENT_METHOD(service, rpc)` macro. * @param request The request protobuf for the gRPC call. * @param options The gRPC options for the call. * @return a `Future` of `Try` waiting for a response protobuf or an error. */ template < typename Method, typename Request = typename internal::MethodTraits<Method>::request_type, typename Response = typename internal::MethodTraits<Method>::response_type, typename std::enable_if< std::is_convertible< typename std::decay<Request>::type*, google::protobuf::Message*>::value, int>::type = 0> Future<Try<Response, StatusError>> call( const Connection& connection, Method&& method, Request&& request, const CallOptions& options) { // Create a `Promise` that will be set upon receiving a response. // TODO(chhsiao): The `Promise` in the `shared_ptr` is not shared, but only // to be captured by the lambda below. Use a `unique_ptr` once we get C++14. std::shared_ptr<Promise<Try<Response, StatusError>>> promise( new Promise<Try<Response, StatusError>>); Future<Try<Response, StatusError>> future = promise->future(); // Send the request in the internal runtime process. // TODO(chhsiao): We use `std::bind` here to forward `request` to avoid an // extra copy. We should capture it by forwarding once we get C++14. dispatch(data->pid, &RuntimeProcess::send, std::bind( [connection, method, options, promise]( const Request& request, bool terminating, ::grpc::CompletionQueue* queue) { if (terminating) { promise->fail("Runtime has been terminated"); return; } // TODO(chhsiao): The `shared_ptr`s here aren't shared, but only to be // captured by the lambda below. Use `unique_ptr`s once we get C++14. std::shared_ptr<::grpc::ClientContext> context( new ::grpc::ClientContext()); context->set_wait_for_ready(options.wait_for_ready); context->set_deadline( std::chrono::system_clock::now() + std::chrono::nanoseconds(options.timeout.ns())); promise->future().onDiscard([=] { context->TryCancel(); }); std::shared_ptr<Response> response(new Response()); std::shared_ptr<::grpc::Status> status(new ::grpc::Status()); std::shared_ptr<::grpc::ClientAsyncResponseReader<Response>> reader = (typename internal::MethodTraits<Method>::stub_type( connection.channel).*method)(context.get(), request, queue); reader->StartCall(); // Create a `ReceiveCallback` as a tag in the `CompletionQueue` for // the current asynchronous gRPC call. The callback will set up the // above `Promise` upon receiving a response. // NOTE: `context` and `reader` need to be held on in order to get // updates for the ongoing RPC, and thus are captured here. The // callback itself will later be retrieved and managed in the // looper thread. void* tag = new ReceiveCallback( [context, reader, response, status, promise]() { CHECK_PENDING(promise->future()); if (promise->future().hasDiscard()) { promise->discard(); } else { promise->set(status->ok() ? std::move(*response) : Try<Response, StatusError>::error(std::move(*status))); } }); reader->Finish(response.get(), status.get(), tag); }, std::forward<Request>(request), lambda::_1, lambda::_2)); return future; } /** * Asks the internal runtime process to shut down the `CompletionQueue`, which * would asynchronously drain and fail all pending gRPC calls in the * `CompletionQueue`, then join the looper thread. */ void terminate(); /** * @return A `Future` waiting for all pending gRPC calls in the * `CompletionQueue` of the internal runtime process to be drained and the * looper thread to be joined. */ Future<Nothing> wait(); private: // Type of the callback functions that can get invoked when sending a request // or receiving a response. typedef lambda::CallableOnce< void(bool, ::grpc::CompletionQueue*)> SendCallback; typedef lambda::CallableOnce<void()> ReceiveCallback; class RuntimeProcess : public Process<RuntimeProcess> { public: RuntimeProcess(); ~RuntimeProcess() override; void send(SendCallback callback); void receive(ReceiveCallback callback); void terminate(); Future<Nothing> wait(); private: void initialize() override; void finalize() override; void loop(); ::grpc::CompletionQueue queue; std::unique_ptr<std::thread> looper; bool terminating; Promise<Nothing> terminated; }; struct Data { Data(); ~Data(); PID<RuntimeProcess> pid; Future<Nothing> terminated; }; std::shared_ptr<Data> data; }; } // namespace client { } // namespace grpc { } // namespace process { #endif // __PROCESS_GRPC_HPP__ <commit_msg>Fixed a linking issue with gRPC.<commit_after>// 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 __PROCESS_GRPC_HPP__ #define __PROCESS_GRPC_HPP__ #include <chrono> #include <memory> #include <string> #include <thread> #include <type_traits> #include <utility> #include <google/protobuf/message.h> #include <grpcpp/grpcpp.h> #include <process/check.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/pid.hpp> #include <process/process.hpp> #include <stout/duration.hpp> #include <stout/error.hpp> #include <stout/lambda.hpp> #include <stout/nothing.hpp> #include <stout/try.hpp> // This file provides libprocess "support" for using gRPC. In particular, it // defines two wrapper classes: `client::Connection` which represents a // connection to a gRPC server, and `client::Runtime` which integrates an event // loop waiting for gRPC responses and provides the `call` interface to create // an asynchronous gRPC call and return a `Future`. #define GRPC_CLIENT_METHOD(service, rpc) \ (&service::Stub::PrepareAsync##rpc) namespace process { namespace grpc { /** * Represents errors caused by non-OK gRPC statuses. See: * https://grpc.io/grpc/cpp/classgrpc_1_1_status.html */ class StatusError : public Error { public: StatusError(::grpc::Status _status) : Error(_status.error_message()), status(std::move(_status)) { CHECK(!status.ok()); } const ::grpc::Status status; }; namespace client { // Internal helper utilities. namespace internal { template <typename T> struct MethodTraits; // Undefined. template <typename Stub, typename Request, typename Response> struct MethodTraits< std::unique_ptr<::grpc::ClientAsyncResponseReader<Response>>(Stub::*)( ::grpc::ClientContext*, const Request&, ::grpc::CompletionQueue*)> { typedef Stub stub_type; typedef Request request_type; typedef Response response_type; }; } // namespace internal { /** * A copyable interface to manage a connection to a gRPC server. All * `Connection` copies share the same gRPC channel which is thread safe. Note * that the actual connection is established lazily by the gRPC library at the * time an RPC is made to the channel. */ class Connection { public: Connection( const std::string& uri, const std::shared_ptr<::grpc::ChannelCredentials>& credentials = ::grpc::InsecureChannelCredentials()) : channel(::grpc::CreateChannel(uri, credentials)) {} explicit Connection(std::shared_ptr<::grpc::Channel> _channel) : channel(std::move(_channel)) {} const std::shared_ptr<::grpc::Channel> channel; }; /** * Defines the gRPC options for each call. */ struct CallOptions { // Enable the gRPC wait-for-ready semantics by default so the call will be // retried if the connection is not ready. See: // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md bool wait_for_ready = true; // The timeout of the call. A `DEADLINE_EXCEEDED` status will be returned if // there is no response in the specified amount of time. This is required to // avoid the call from being pending forever. Duration timeout = Seconds(60); }; /** * A copyable interface to manage an internal runtime process for asynchronous * gRPC calls. A runtime process keeps a gRPC `CompletionQueue` to manage * outstanding requests, a looper thread to wait for any incoming responses from * the `CompletionQueue`, and handles the requests and responses. All `Runtime` * copies share the same runtime process. Usually we only need a single runtime * process to handle all gRPC calls, but multiple runtime processes can be * instantiated for better parallelism and isolation. * * NOTE: The caller must call `terminate` to drain the `CompletionQueue` before * finalizing libprocess to gracefully terminate the gRPC runtime. */ class Runtime { public: Runtime() : data(new Data()) {} /** * Sends an asynchronous gRPC call. * * This function returns a `Future` of a `Try` such that the response protobuf * is returned only if the gRPC call returns an OK status to ensure type * safety (see https://github.com/grpc/grpc/issues/12824). Note that the * future never fails; it will return a `StatusError` if a non-OK status is * returned for the call, so the caller can handle the error programmatically. * * @param connection A connection to a gRPC server. * @param method The asynchronous gRPC call to make. This should be obtained * by the `GRPC_CLIENT_METHOD(service, rpc)` macro. * @param request The request protobuf for the gRPC call. * @param options The gRPC options for the call. * @return a `Future` of `Try` waiting for a response protobuf or an error. */ template < typename Method, typename Request = typename internal::MethodTraits<Method>::request_type, typename Response = typename internal::MethodTraits<Method>::response_type, typename std::enable_if< std::is_convertible< typename std::decay<Request>::type*, google::protobuf::Message*>::value, int>::type = 0> Future<Try<Response, StatusError>> call( const Connection& connection, Method&& method, Request&& request, const CallOptions& options) { // Create a `Promise` that will be set upon receiving a response. // TODO(chhsiao): The `Promise` in the `shared_ptr` is not shared, but only // to be captured by the lambda below. Use a `unique_ptr` once we get C++14. std::shared_ptr<Promise<Try<Response, StatusError>>> promise( new Promise<Try<Response, StatusError>>); Future<Try<Response, StatusError>> future = promise->future(); // Send the request in the internal runtime process. // TODO(chhsiao): We use `std::bind` here to forward `request` to avoid an // extra copy. We should capture it by forwarding once we get C++14. dispatch(data->pid, &RuntimeProcess::send, std::bind( [connection, method, options, promise]( const Request& request, bool terminating, ::grpc::CompletionQueue* queue) { if (terminating) { promise->fail("Runtime has been terminated"); return; } // TODO(chhsiao): The `shared_ptr`s here aren't shared, but only to be // captured by the lambda below. Use `unique_ptr`s once we get C++14. std::shared_ptr<::grpc::ClientContext> context( new ::grpc::ClientContext()); context->set_wait_for_ready(options.wait_for_ready); // We need to ensure that we're using a // `std::chrono::system_clock::time_point` because `grpc::TimePoint` // provides a specialization only for this type and we cannot // guarantee that the operation below will always result in this type. auto time_point = std::chrono::time_point_cast<std::chrono::system_clock::duration>( std::chrono::system_clock::now() + std::chrono::nanoseconds(options.timeout.ns())); context->set_deadline(time_point); promise->future().onDiscard([=] { context->TryCancel(); }); std::shared_ptr<Response> response(new Response()); std::shared_ptr<::grpc::Status> status(new ::grpc::Status()); std::shared_ptr<::grpc::ClientAsyncResponseReader<Response>> reader = (typename internal::MethodTraits<Method>::stub_type( connection.channel).*method)(context.get(), request, queue); reader->StartCall(); // Create a `ReceiveCallback` as a tag in the `CompletionQueue` for // the current asynchronous gRPC call. The callback will set up the // above `Promise` upon receiving a response. // NOTE: `context` and `reader` need to be held on in order to get // updates for the ongoing RPC, and thus are captured here. The // callback itself will later be retrieved and managed in the // looper thread. void* tag = new ReceiveCallback( [context, reader, response, status, promise]() { CHECK_PENDING(promise->future()); if (promise->future().hasDiscard()) { promise->discard(); } else { promise->set(status->ok() ? std::move(*response) : Try<Response, StatusError>::error(std::move(*status))); } }); reader->Finish(response.get(), status.get(), tag); }, std::forward<Request>(request), lambda::_1, lambda::_2)); return future; } /** * Asks the internal runtime process to shut down the `CompletionQueue`, which * would asynchronously drain and fail all pending gRPC calls in the * `CompletionQueue`, then join the looper thread. */ void terminate(); /** * @return A `Future` waiting for all pending gRPC calls in the * `CompletionQueue` of the internal runtime process to be drained and the * looper thread to be joined. */ Future<Nothing> wait(); private: // Type of the callback functions that can get invoked when sending a request // or receiving a response. typedef lambda::CallableOnce< void(bool, ::grpc::CompletionQueue*)> SendCallback; typedef lambda::CallableOnce<void()> ReceiveCallback; class RuntimeProcess : public Process<RuntimeProcess> { public: RuntimeProcess(); ~RuntimeProcess() override; void send(SendCallback callback); void receive(ReceiveCallback callback); void terminate(); Future<Nothing> wait(); private: void initialize() override; void finalize() override; void loop(); ::grpc::CompletionQueue queue; std::unique_ptr<std::thread> looper; bool terminating; Promise<Nothing> terminated; }; struct Data { Data(); ~Data(); PID<RuntimeProcess> pid; Future<Nothing> terminated; }; std::shared_ptr<Data> data; }; } // namespace client { } // namespace grpc { } // namespace process { #endif // __PROCESS_GRPC_HPP__ <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/editing/VisibleSelection.h" #include "core/dom/Document.h" #include "core/dom/Range.h" #include "core/dom/Text.h" #include "core/html/HTMLElement.h" #include "core/testing/DummyPageHolder.h" #include <gtest/gtest.h> #define LOREM_IPSUM \ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor " \ "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud " \ "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure " \ "dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." \ "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt " \ "mollit anim id est laborum." namespace blink { class VisibleSelectionTest : public ::testing::Test { protected: virtual void SetUp() override; // Oilpan: wrapper object needed to be able to trace VisibleSelection. class VisibleSelectionWrapper : public NoBaseWillBeGarbageCollectedFinalized<VisibleSelectionWrapper> { public: DEFINE_INLINE_TRACE() { visitor->trace(m_selection); } VisibleSelection m_selection; }; Document& document() const { return m_dummyPageHolder->document(); } Text* textNode() const { return m_textNode.get(); } VisibleSelection& selection() { return m_wrap->m_selection; } // Helper function to set the VisibleSelection base/extent. void setSelection(int base) { setSelection(base, base); } // Helper function to set the VisibleSelection base/extent. void setSelection(int base, int extend) { m_wrap->m_selection.setBase(Position(textNode(), base)); m_wrap->m_selection.setExtent(Position(textNode(), extend)); } private: OwnPtr<DummyPageHolder> m_dummyPageHolder; RefPtrWillBePersistent<Text> m_textNode; OwnPtrWillBePersistent<VisibleSelectionWrapper> m_wrap; }; void blink::VisibleSelectionTest::SetUp() { m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600)); m_textNode = document().createTextNode(LOREM_IPSUM); m_wrap = adoptPtrWillBeNoop(new VisibleSelectionWrapper()); document().body()->appendChild(m_textNode.get()); } } // namespace blink namespace { using namespace blink; TEST_F(VisibleSelectionTest, Initialisation) { setSelection(0); EXPECT_FALSE(selection().isNone()); EXPECT_TRUE(selection().isCaret()); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(0, range->endOffset()); EXPECT_EQ("", range->text()); } TEST_F(VisibleSelectionTest, WordGranularity) { // Beginning of a word. { setSelection(0); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(5, range->endOffset()); EXPECT_EQ("Lorem", range->text()); } // Middle of a word. { setSelection(8); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(6, range->startOffset()); EXPECT_EQ(11, range->endOffset()); EXPECT_EQ("ipsum", range->text()); } // End of a word. // FIXME: that sounds buggy, we might want to select the word _before_ instead // of the space... { setSelection(5); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(5, range->startOffset()); EXPECT_EQ(6, range->endOffset()); EXPECT_EQ(" ", range->text()); } // Before comma. // FIXME: that sounds buggy, we might want to select the word _before_ instead // of the comma. { setSelection(26); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(26, range->startOffset()); EXPECT_EQ(27, range->endOffset()); EXPECT_EQ(",", range->text()); } // After comma. { setSelection(27); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(27, range->startOffset()); EXPECT_EQ(28, range->endOffset()); EXPECT_EQ(" ", range->text()); } // When selecting part of a word. { setSelection(0, 1); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(5, range->endOffset()); EXPECT_EQ("Lorem", range->text()); } // When selecting part of two words. { setSelection(2, 8); selection().expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection().firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(11, range->endOffset()); EXPECT_EQ("Lorem ipsum", range->text()); } } } // namespace blink <commit_msg>Re-factor VisibleSelectionTest for adding tests for composed tree version<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/editing/VisibleSelection.h" #include "core/dom/Document.h" #include "core/dom/Range.h" #include "core/dom/Text.h" #include "core/html/HTMLElement.h" #include "core/testing/DummyPageHolder.h" #include <gtest/gtest.h> #define LOREM_IPSUM \ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor " \ "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud " \ "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure " \ "dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." \ "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt " \ "mollit anim id est laborum." namespace blink { class VisibleSelectionTest : public ::testing::Test { protected: virtual void SetUp() override; Document& document() const { return m_dummyPageHolder->document(); } static PassRefPtrWillBeRawPtr<ShadowRoot> createShadowRootForElementWithIDAndSetInnerHTML(TreeScope&, const char* hostElementID, const char* shadowRootContent); void setBodyContent(const char*); PassRefPtrWillBeRawPtr<ShadowRoot> setShadowContent(const char*); // Helper function to set the VisibleSelection base/extent. void setSelection(VisibleSelection& selection, int base) { setSelection(selection, base, base); } // Helper function to set the VisibleSelection base/extent. void setSelection(VisibleSelection& selection, int base, int extend) { Node* node = document().body()->firstChild(); selection.setBase(Position(node, base, Position::PositionIsOffsetInAnchor)); selection.setExtent(Position(node, extend, Position::PositionIsOffsetInAnchor)); } private: OwnPtr<DummyPageHolder> m_dummyPageHolder; }; void VisibleSelectionTest::SetUp() { m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600)); } PassRefPtrWillBeRawPtr<ShadowRoot> VisibleSelectionTest::createShadowRootForElementWithIDAndSetInnerHTML(TreeScope& scope, const char* hostElementID, const char* shadowRootContent) { RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = scope.getElementById(AtomicString::fromUTF8(hostElementID))->createShadowRoot(ASSERT_NO_EXCEPTION); shadowRoot->setInnerHTML(String::fromUTF8(shadowRootContent), ASSERT_NO_EXCEPTION); return shadowRoot.release(); } void VisibleSelectionTest::setBodyContent(const char* bodyContent) { document().body()->setInnerHTML(String::fromUTF8(bodyContent), ASSERT_NO_EXCEPTION); } PassRefPtrWillBeRawPtr<ShadowRoot> VisibleSelectionTest::setShadowContent(const char* shadowContent) { return createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent); } TEST_F(VisibleSelectionTest, Initialisation) { setBodyContent(LOREM_IPSUM); VisibleSelection selection; setSelection(selection, 0); EXPECT_FALSE(selection.isNone()); EXPECT_TRUE(selection.isCaret()); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(0, range->endOffset()); EXPECT_EQ("", range->text()); } TEST_F(VisibleSelectionTest, ShadowCrossing) { const char* bodyContent = "<p id='host'>00<b id='one'>11</b><b id='two'>22</b>33</p>"; const char* shadowContent = "<a><span id='s4'>44</span><content select=#two></content><span id='s5'>55</span><content select=#one></content><span id='s6'>66</span></a>"; setBodyContent(bodyContent); RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = setShadowContent(shadowContent); RefPtrWillBeRawPtr<Element> body = document().body(); RefPtrWillBeRawPtr<Element> host = body->querySelector("#host", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> one = body->querySelector("#one", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> two = body->querySelector("#two", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> six = shadowRoot->querySelector("#s6", ASSERT_NO_EXCEPTION); VisibleSelection selection(Position::firstPositionInNode(one.get()), Position::lastPositionInNode(shadowRoot.get())); EXPECT_EQ(Position(host.get(), Position::PositionIsBeforeAnchor), selection.start()); EXPECT_EQ(Position(one->firstChild(), 0, Position::PositionIsOffsetInAnchor), selection.end()); } TEST_F(VisibleSelectionTest, ShadowDistributedNodes) { const char* bodyContent = "<p id='host'>00<b id='one'>11</b><b id='two'>22</b>33</p>"; const char* shadowContent = "<a><span id='s4'>44</span><content select=#two></content><span id='s5'>55</span><content select=#one></content><span id='s6'>66</span></a>"; setBodyContent(bodyContent); RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = setShadowContent(shadowContent); RefPtrWillBeRawPtr<Element> body = document().body(); RefPtrWillBeRawPtr<Element> host = body->querySelector("#host", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> one = body->querySelector("#one", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> two = body->querySelector("#two", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> five = shadowRoot->querySelector("#s5", ASSERT_NO_EXCEPTION); VisibleSelection selection(Position::firstPositionInNode(one.get()), Position::lastPositionInNode(two.get())); EXPECT_EQ(Position(one->firstChild(), 0, Position::PositionIsOffsetInAnchor), selection.start()); EXPECT_EQ(Position(two->firstChild(), 2, Position::PositionIsOffsetInAnchor), selection.end()); } TEST_F(VisibleSelectionTest, ShadowNested) { const char* bodyContent = "<p id='host'>00<b id='one'>11</b><b id='two'>22</b>33</p>"; const char* shadowContent = "<a><span id='s4'>44</span><content select=#two></content><span id='s5'>55</span><content select=#one></content><span id='s6'>66</span></a>"; const char* shadowContent2 = "<span id='s7'>77</span><content></content><span id='s8'>88</span>"; setBodyContent(bodyContent); RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = setShadowContent(shadowContent); RefPtrWillBeRawPtr<ShadowRoot> shadowRoot2 = createShadowRootForElementWithIDAndSetInnerHTML(*shadowRoot, "s5", shadowContent2); RefPtrWillBeRawPtr<Element> body = document().body(); RefPtrWillBeRawPtr<Element> host = body->querySelector("#host", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> one = body->querySelector("#one", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> two = body->querySelector("#two", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> host2 = shadowRoot->querySelector("#host2", ASSERT_NO_EXCEPTION); RefPtrWillBeRawPtr<Element> eight = shadowRoot2->querySelector("#s8", ASSERT_NO_EXCEPTION); VisibleSelection selection(Position::firstPositionInNode(one.get()), Position::lastPositionInNode(shadowRoot2.get())); EXPECT_EQ(Position(host.get(), Position::PositionIsBeforeAnchor), selection.start()); EXPECT_EQ(Position(one->firstChild(), 0, Position::PositionIsOffsetInAnchor), selection.end()); } TEST_F(VisibleSelectionTest, WordGranularity) { setBodyContent(LOREM_IPSUM); VisibleSelection selection; // Beginning of a word. { setSelection(selection, 0); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(5, range->endOffset()); EXPECT_EQ("Lorem", range->text()); } // Middle of a word. { setSelection(selection, 8); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(6, range->startOffset()); EXPECT_EQ(11, range->endOffset()); EXPECT_EQ("ipsum", range->text()); } // End of a word. // FIXME: that sounds buggy, we might want to select the word _before_ instead // of the space... { setSelection(selection, 5); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(5, range->startOffset()); EXPECT_EQ(6, range->endOffset()); EXPECT_EQ(" ", range->text()); } // Before comma. // FIXME: that sounds buggy, we might want to select the word _before_ instead // of the comma. { setSelection(selection, 26); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(26, range->startOffset()); EXPECT_EQ(27, range->endOffset()); EXPECT_EQ(",", range->text()); } // After comma. { setSelection(selection, 27); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(27, range->startOffset()); EXPECT_EQ(28, range->endOffset()); EXPECT_EQ(" ", range->text()); } // When selecting part of a word. { setSelection(selection, 0, 1); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(5, range->endOffset()); EXPECT_EQ("Lorem", range->text()); } // When selecting part of two words. { setSelection(selection, 2, 8); selection.expandUsingGranularity(WordGranularity); RefPtrWillBeRawPtr<Range> range = selection.firstRange(); EXPECT_EQ(0, range->startOffset()); EXPECT_EQ(11, range->endOffset()); EXPECT_EQ("Lorem ipsum", range->text()); } } } // namespace blink <|endoftext|>
<commit_before>//===- MemDepPrinter.cpp - Printer for MemoryDependenceAnalysis -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "llvm/Analysis/MemoryDependenceAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/InstIterator.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/ADT/SetVector.h" using namespace llvm; namespace { struct MemDepPrinter : public FunctionPass { const Function *F; typedef PointerIntPair<const Instruction *, 1> InstAndClobberFlag; typedef std::pair<InstAndClobberFlag, const BasicBlock *> Dep; typedef SmallSetVector<Dep, 4> DepSet; typedef DenseMap<const Instruction *, DepSet> DepSetMap; DepSetMap Deps; static char ID; // Pass identifcation, replacement for typeid MemDepPrinter() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F); void print(raw_ostream &OS, const Module * = 0) const; virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<MemoryDependenceAnalysis>(); AU.setPreservesAll(); } virtual void releaseMemory() { Deps.clear(); F = 0; } }; } char MemDepPrinter::ID = 0; INITIALIZE_PASS(MemDepPrinter, "print-memdeps", "Print MemDeps of function", false, true); FunctionPass *llvm::createMemDepPrinter() { return new MemDepPrinter(); } bool MemDepPrinter::runOnFunction(Function &F) { this->F = &F; MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>(); // All this code uses non-const interfaces because MemDep is not // const-friendly, though nothing is actually modified. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) { Instruction *Inst = &*I; if (!Inst->mayReadFromMemory() && !Inst->mayWriteToMemory()) continue; MemDepResult Res = MDA.getDependency(Inst); if (!Res.isNonLocal()) { assert(Res.isClobber() != Res.isDef() && "Local dep should be def or clobber!"); Deps[Inst].insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), static_cast<BasicBlock *>(0))); } else if (CallSite CS = cast<Value>(Inst)) { const MemoryDependenceAnalysis::NonLocalDepInfo &NLDI = MDA.getNonLocalCallDependency(CS); DepSet &InstDeps = Deps[Inst]; for (MemoryDependenceAnalysis::NonLocalDepInfo::const_iterator I = NLDI.begin(), E = NLDI.end(); I != E; ++I) { const MemDepResult &Res = I->getResult(); assert(Res.isClobber() != Res.isDef() && "Resolved non-local call dep should be def or clobber!"); InstDeps.insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), I->getBB())); } } else { SmallVector<NonLocalDepResult, 4> NLDI; if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { // FIXME: Volatile is not handled properly here. MDA.getNonLocalPointerDependency(LI->getPointerOperand(), !LI->isVolatile(), LI->getParent(), NLDI); } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { // FIXME: Volatile is not handled properly here. MDA.getNonLocalPointerDependency(SI->getPointerOperand(), false, SI->getParent(), NLDI); } else if (VAArgInst *VI = dyn_cast<VAArgInst>(Inst)) { MDA.getNonLocalPointerDependency(VI->getPointerOperand(), false, VI->getParent(), NLDI); } else { llvm_unreachable("Unknown memory instruction!"); } DepSet &InstDeps = Deps[Inst]; for (SmallVectorImpl<NonLocalDepResult>::const_iterator I = NLDI.begin(), E = NLDI.end(); I != E; ++I) { const MemDepResult &Res = I->getResult(); assert(Res.isClobber() != Res.isDef() && "Resolved non-local pointer dep should be def or clobber!"); InstDeps.insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), I->getBB())); } } } return false; } void MemDepPrinter::print(raw_ostream &OS, const Module *M) const { for (const_inst_iterator I = inst_begin(*F), E = inst_end(*F); I != E; ++I) { const Instruction *Inst = &*I; DepSetMap::const_iterator DI = Deps.find(Inst); if (DI == Deps.end()) continue; const DepSet &InstDeps = DI->second; for (DepSet::const_iterator I = InstDeps.begin(), E = InstDeps.end(); I != E; ++I) { const Instruction *DepInst = I->first.getPointer(); bool isClobber = I->first.getInt(); const BasicBlock *DepBB = I->second; OS << " " << (isClobber ? "Clobber" : " Def"); if (DepBB) { OS << " in block "; WriteAsOperand(OS, DepBB, /*PrintType=*/false, M); } OS << " from: "; DepInst->print(OS); OS << "\n"; } Inst->print(OS); OS << "\n\n"; } } <commit_msg>Add an #include of raw_ostream.h. Previously, this only compiled because it was using Twine.h's declaration of operator<<(const Twine &).<commit_after>//===- MemDepPrinter.cpp - Printer for MemoryDependenceAnalysis -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "llvm/Analysis/MemoryDependenceAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/InstIterator.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/SetVector.h" using namespace llvm; namespace { struct MemDepPrinter : public FunctionPass { const Function *F; typedef PointerIntPair<const Instruction *, 1> InstAndClobberFlag; typedef std::pair<InstAndClobberFlag, const BasicBlock *> Dep; typedef SmallSetVector<Dep, 4> DepSet; typedef DenseMap<const Instruction *, DepSet> DepSetMap; DepSetMap Deps; static char ID; // Pass identifcation, replacement for typeid MemDepPrinter() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F); void print(raw_ostream &OS, const Module * = 0) const; virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<MemoryDependenceAnalysis>(); AU.setPreservesAll(); } virtual void releaseMemory() { Deps.clear(); F = 0; } }; } char MemDepPrinter::ID = 0; INITIALIZE_PASS(MemDepPrinter, "print-memdeps", "Print MemDeps of function", false, true); FunctionPass *llvm::createMemDepPrinter() { return new MemDepPrinter(); } bool MemDepPrinter::runOnFunction(Function &F) { this->F = &F; MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>(); // All this code uses non-const interfaces because MemDep is not // const-friendly, though nothing is actually modified. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) { Instruction *Inst = &*I; if (!Inst->mayReadFromMemory() && !Inst->mayWriteToMemory()) continue; MemDepResult Res = MDA.getDependency(Inst); if (!Res.isNonLocal()) { assert(Res.isClobber() != Res.isDef() && "Local dep should be def or clobber!"); Deps[Inst].insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), static_cast<BasicBlock *>(0))); } else if (CallSite CS = cast<Value>(Inst)) { const MemoryDependenceAnalysis::NonLocalDepInfo &NLDI = MDA.getNonLocalCallDependency(CS); DepSet &InstDeps = Deps[Inst]; for (MemoryDependenceAnalysis::NonLocalDepInfo::const_iterator I = NLDI.begin(), E = NLDI.end(); I != E; ++I) { const MemDepResult &Res = I->getResult(); assert(Res.isClobber() != Res.isDef() && "Resolved non-local call dep should be def or clobber!"); InstDeps.insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), I->getBB())); } } else { SmallVector<NonLocalDepResult, 4> NLDI; if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { // FIXME: Volatile is not handled properly here. MDA.getNonLocalPointerDependency(LI->getPointerOperand(), !LI->isVolatile(), LI->getParent(), NLDI); } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { // FIXME: Volatile is not handled properly here. MDA.getNonLocalPointerDependency(SI->getPointerOperand(), false, SI->getParent(), NLDI); } else if (VAArgInst *VI = dyn_cast<VAArgInst>(Inst)) { MDA.getNonLocalPointerDependency(VI->getPointerOperand(), false, VI->getParent(), NLDI); } else { llvm_unreachable("Unknown memory instruction!"); } DepSet &InstDeps = Deps[Inst]; for (SmallVectorImpl<NonLocalDepResult>::const_iterator I = NLDI.begin(), E = NLDI.end(); I != E; ++I) { const MemDepResult &Res = I->getResult(); assert(Res.isClobber() != Res.isDef() && "Resolved non-local pointer dep should be def or clobber!"); InstDeps.insert(std::make_pair(InstAndClobberFlag(Res.getInst(), Res.isClobber()), I->getBB())); } } } return false; } void MemDepPrinter::print(raw_ostream &OS, const Module *M) const { for (const_inst_iterator I = inst_begin(*F), E = inst_end(*F); I != E; ++I) { const Instruction *Inst = &*I; DepSetMap::const_iterator DI = Deps.find(Inst); if (DI == Deps.end()) continue; const DepSet &InstDeps = DI->second; for (DepSet::const_iterator I = InstDeps.begin(), E = InstDeps.end(); I != E; ++I) { const Instruction *DepInst = I->first.getPointer(); bool isClobber = I->first.getInt(); const BasicBlock *DepBB = I->second; OS << " " << (isClobber ? "Clobber" : " Def"); if (DepBB) { OS << " in block "; WriteAsOperand(OS, DepBB, /*PrintType=*/false, M); } OS << " from: "; DepInst->print(OS); OS << "\n"; } Inst->print(OS); OS << "\n\n"; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../typedefs.h" #include "../algorithms/tiny_components.hpp" #include "../data_structures/static_graph.hpp" #include "../data_structures/coordinate_calculation.hpp" #include "../util/fingerprint.hpp" #include "../util/graph_loader.hpp" #include "../util/make_unique.hpp" #include "../util/osrm_exception.hpp" #include "../util/simple_logger.hpp" #include <boost/filesystem.hpp> #if defined(__APPLE__) || defined(_WIN32) #include <gdal.h> #include <ogrsf_frmts.h> #else #include <gdal/gdal.h> #include <gdal/ogrsf_frmts.h> #endif #include <osrm/coordinate.hpp> #include <fstream> #include <memory> #include <string> #include <vector> namespace { struct TarjanEdgeData { TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {} TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {} unsigned distance; unsigned name_id; }; using TarjanGraph = StaticGraph<TarjanEdgeData>; using TarjanEdge = TarjanGraph::InputEdge; void DeleteFileIfExists(const std::string &file_name) { if (boost::filesystem::exists(file_name)) { boost::filesystem::remove(file_name); } } } int main(int argc, char *argv[]) { std::vector<QueryNode> coordinate_list; std::vector<TurnRestriction> restriction_list; std::vector<NodeID> bollard_node_list; std::vector<NodeID> traffic_lights_list; LogPolicy::GetInstance().Unmute(); try { // enable logging if (argc < 3) { SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " <osrm> <osrm.restrictions>"; return -1; } SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restriction_ifstream(argv[2], std::ios::binary); const FingerPrint fingerprint_orig; FingerPrint fingerprint_loaded; restriction_ifstream.read(reinterpret_cast<char *>(&fingerprint_loaded), sizeof(FingerPrint)); // check fingerprint and warn if necessary if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig)) { SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. " "Reprocess to get rid of this warning."; } if (!restriction_ifstream.good()) { throw osrm::exception("Could not access <osrm-restrictions> files"); } uint32_t usable_restrictions = 0; restriction_ifstream.read(reinterpret_cast<char *>(&usable_restrictions), sizeof(uint32_t)); restriction_list.resize(usable_restrictions); // load restrictions if (usable_restrictions > 0) { restriction_ifstream.read(reinterpret_cast<char *>(&restriction_list[0]), usable_restrictions * sizeof(TurnRestriction)); } restriction_ifstream.close(); std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary); if (!input_stream.is_open()) { throw osrm::exception("Cannot open osrm file"); } // load graph data std::vector<ImportEdge> edge_list; const NodeID number_of_nodes = readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list, traffic_lights_list, &coordinate_list, restriction_list); input_stream.close(); BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions, "size of restriction_list changed"); SimpleLogger().Write() << restriction_list.size() << " restrictions, " << bollard_node_list.size() << " bollard nodes, " << traffic_lights_list.size() << " traffic lights"; traffic_lights_list.clear(); traffic_lights_list.shrink_to_fit(); // Building an node-based graph std::vector<TarjanEdge> graph_edge_list; for (const auto &input_edge : edge_list) { if (input_edge.source == input_edge.target) { continue; } if (input_edge.forward) { graph_edge_list.emplace_back(input_edge.source, input_edge.target, (std::max)(input_edge.weight, 1), input_edge.name_id); } if (input_edge.backward) { graph_edge_list.emplace_back(input_edge.target, input_edge.source, (std::max)(input_edge.weight, 1), input_edge.name_id); } } edge_list.clear(); edge_list.shrink_to_fit(); BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(), "input edge vector not properly deallocated"); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); auto graph = std::make_shared<TarjanGraph>(number_of_nodes, graph_edge_list); graph_edge_list.clear(); graph_edge_list.shrink_to_fit(); SimpleLogger().Write() << "Starting SCC graph traversal"; RestrictionMap restriction_map(restriction_list); auto tarjan = osrm::make_unique<TarjanSCC<TarjanGraph>>(graph, restriction_map, bollard_node_list); tarjan->run(); SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() << " many components"; SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; // output TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist DeleteFileIfExists("component.dbf"); DeleteFileIfExists("component.shx"); DeleteFileIfExists("component.shp"); Percent percentage(graph->GetNumberOfNodes()); OGRRegisterAll(); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if (nullptr == poDriver) { throw osrm::exception("ESRI Shapefile driver not available"); } OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr); if (nullptr == poDS) { throw osrm::exception("Creation of output file failed"); } OGRSpatialReference *poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(4326); OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr); if (nullptr == poLayer) { throw osrm::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; uint64_t total_network_length = 0; percentage.reinit(graph->GetNumberOfNodes()); TIMER_START(SCC_OUTPUT); for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes())) { percentage.printIncrement(); for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { const TarjanGraph::NodeIterator target = graph->GetTarget(current_edge); if (source < target || graph->EndEdges(target) == graph->FindEdge(target, source)) { total_network_length += 100 * coordinate_calculation::euclidean_distance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); BOOST_ASSERT(current_edge != SPECIAL_EDGEID); BOOST_ASSERT(source != SPECIAL_NODEID); BOOST_ASSERT(target != SPECIAL_NODEID); const unsigned size_of_containing_component = std::min( tarjan->get_component_size(source), tarjan->get_component_size(target)); // edges that end on bollard nodes may actually be in two distinct components if (size_of_containing_component < 1000) { OGRLineString lineString; lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, coordinate_list[source].lat / COORDINATE_PRECISION); lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, coordinate_list[target].lat / COORDINATE_PRECISION); OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); poFeature->SetGeometry(&lineString); if (OGRERR_NONE != poLayer->CreateFeature(poFeature)) { throw osrm::exception("Failed to create feature in shapefile."); } OGRFeature::DestroyFeature(poFeature); } } } } OGRSpatialReference::DestroySpatialReference(poSRS); OGRDataSource::DestroyDataSource(poDS); TIMER_STOP(SCC_OUTPUT); SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; SimpleLogger().Write() << "total network distance: " << static_cast<uint64_t>(total_network_length / 100 / 1000.) << " km"; SimpleLogger().Write() << "finished component analysis"; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } <commit_msg>fix comparison to recognize small components in a static graph<commit_after>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../typedefs.h" #include "../algorithms/tiny_components.hpp" #include "../data_structures/coordinate_calculation.hpp" #include "../data_structures/dynamic_graph.hpp" #include "../data_structures/static_graph.hpp" #include "../util/fingerprint.hpp" #include "../util/graph_loader.hpp" #include "../util/make_unique.hpp" #include "../util/osrm_exception.hpp" #include "../util/simple_logger.hpp" #include <boost/filesystem.hpp> #if defined(__APPLE__) || defined(_WIN32) #include <gdal.h> #include <ogrsf_frmts.h> #else #include <gdal/gdal.h> #include <gdal/ogrsf_frmts.h> #endif #include <osrm/coordinate.hpp> #include <fstream> #include <memory> #include <string> #include <vector> namespace { struct TarjanEdgeData { TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {} TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {} unsigned distance; unsigned name_id; }; using TarjanDynamicGraph = StaticGraph<TarjanEdgeData>; using TarjanEdge = TarjanDynamicGraph::InputEdge; void DeleteFileIfExists(const std::string &file_name) { if (boost::filesystem::exists(file_name)) { boost::filesystem::remove(file_name); } } } int main(int argc, char *argv[]) { std::vector<QueryNode> coordinate_list; std::vector<TurnRestriction> restriction_list; std::vector<NodeID> bollard_node_list; std::vector<NodeID> traffic_lights_list; LogPolicy::GetInstance().Unmute(); try { // enable logging if (argc < 3) { SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " <osrm> <osrm.restrictions>"; return -1; } SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restriction_ifstream(argv[2], std::ios::binary); const FingerPrint fingerprint_orig; FingerPrint fingerprint_loaded; restriction_ifstream.read(reinterpret_cast<char *>(&fingerprint_loaded), sizeof(FingerPrint)); // check fingerprint and warn if necessary if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig)) { SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. " "Reprocess to get rid of this warning."; } if (!restriction_ifstream.good()) { throw osrm::exception("Could not access <osrm-restrictions> files"); } uint32_t usable_restrictions = 0; restriction_ifstream.read(reinterpret_cast<char *>(&usable_restrictions), sizeof(uint32_t)); restriction_list.resize(usable_restrictions); // load restrictions if (usable_restrictions > 0) { restriction_ifstream.read(reinterpret_cast<char *>(&restriction_list[0]), usable_restrictions * sizeof(TurnRestriction)); } restriction_ifstream.close(); std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary); if (!input_stream.is_open()) { throw osrm::exception("Cannot open osrm file"); } // load graph data std::vector<ImportEdge> edge_list; const NodeID number_of_nodes = readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list, traffic_lights_list, &coordinate_list, restriction_list); input_stream.close(); BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions, "size of restriction_list changed"); SimpleLogger().Write() << restriction_list.size() << " restrictions, " << bollard_node_list.size() << " bollard nodes, " << traffic_lights_list.size() << " traffic lights"; traffic_lights_list.clear(); traffic_lights_list.shrink_to_fit(); // Building an node-based graph std::vector<TarjanEdge> graph_edge_list; // DeallocatingVector<TarjanEdge> graph_edge_list; for (const auto &input_edge : edge_list) { if (input_edge.source == input_edge.target) { continue; } if (input_edge.forward) { graph_edge_list.emplace_back(input_edge.source, input_edge.target, (std::max)(input_edge.weight, 1), input_edge.name_id); } if (input_edge.backward) { graph_edge_list.emplace_back(input_edge.target, input_edge.source, (std::max)(input_edge.weight, 1), input_edge.name_id); } } edge_list.clear(); edge_list.shrink_to_fit(); BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(), "input edge vector not properly deallocated"); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); const auto graph = std::make_shared<TarjanDynamicGraph>(number_of_nodes, graph_edge_list); graph_edge_list.clear(); graph_edge_list.shrink_to_fit(); SimpleLogger().Write() << "Starting SCC graph traversal"; RestrictionMap restriction_map(restriction_list); auto tarjan = osrm::make_unique<TarjanSCC<TarjanDynamicGraph>>(graph, restriction_map, bollard_node_list); tarjan->run(); SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() << " many components"; SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; // output TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist DeleteFileIfExists("component.dbf"); DeleteFileIfExists("component.shx"); DeleteFileIfExists("component.shp"); Percent percentage(graph->GetNumberOfNodes()); OGRRegisterAll(); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if (nullptr == poDriver) { throw osrm::exception("ESRI Shapefile driver not available"); } OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr); if (nullptr == poDS) { throw osrm::exception("Creation of output file failed"); } OGRSpatialReference *poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(4326); OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr); if (nullptr == poLayer) { throw osrm::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; uint64_t total_network_length = 0; percentage.reinit(graph->GetNumberOfNodes()); TIMER_START(SCC_OUTPUT); for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes())) { percentage.printIncrement(); for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { const TarjanDynamicGraph::NodeIterator target = graph->GetTarget(current_edge); if (source < target || graph->EndEdges(target) >= graph->FindEdge(target, source)) { total_network_length += 100 * coordinate_calculation::euclidean_distance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); BOOST_ASSERT(current_edge != SPECIAL_EDGEID); BOOST_ASSERT(source != SPECIAL_NODEID); BOOST_ASSERT(target != SPECIAL_NODEID); const unsigned size_of_containing_component = std::min( tarjan->get_component_size(source), tarjan->get_component_size(target)); // edges that end on bollard nodes may actually be in two distinct components if (size_of_containing_component < 1000) { OGRLineString lineString; lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, coordinate_list[source].lat / COORDINATE_PRECISION); lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, coordinate_list[target].lat / COORDINATE_PRECISION); OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); poFeature->SetGeometry(&lineString); if (OGRERR_NONE != poLayer->CreateFeature(poFeature)) { throw osrm::exception("Failed to create feature in shapefile."); } OGRFeature::DestroyFeature(poFeature); } } } } OGRSpatialReference::DestroySpatialReference(poSRS); OGRDataSource::DestroyDataSource(poDS); TIMER_STOP(SCC_OUTPUT); SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; SimpleLogger().Write() << "total network distance: " << static_cast<uint64_t>(total_network_length / 100 / 1000.) << " km"; SimpleLogger().Write() << "finished component analysis"; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } <|endoftext|>
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Aggressive Dead Code Elimination pass. This pass // optimistically assumes that all instructions are dead until proven otherwise, // allowing it to eliminate dead computations that other DCE passes do not // catch, particularly involving loop computations. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "adce" STATISTIC(NumRemoved, "Number of instructions removed"); namespace { struct ADCE : public FunctionPass { static char ID; // Pass identification, replacement for typeid ADCE() : FunctionPass(ID) { initializeADCEPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function& F) override; void getAnalysisUsage(AnalysisUsage& AU) const override { AU.setPreservesCFG(); } }; } char ADCE::ID = 0; INITIALIZE_PASS(ADCE, "adce", "Aggressive Dead Code Elimination", false, false) bool ADCE::runOnFunction(Function& F) { if (skipOptnoneFunction(F)) return false; SmallPtrSet<Instruction*, 128> Alive; SmallVector<Instruction*, 128> Worklist; // Collect the set of "root" instructions that are known live. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) if (isa<TerminatorInst>(I.getInstructionIterator()) || isa<DbgInfoIntrinsic>(I.getInstructionIterator()) || isa<LandingPadInst>(I.getInstructionIterator()) || I->mayHaveSideEffects()) { Alive.insert(I.getInstructionIterator()); Worklist.push_back(I.getInstructionIterator()); } // Propagate liveness backwards to operands. while (!Worklist.empty()) { Instruction *Curr = Worklist.pop_back_val(); for (Instruction::op_iterator OI = Curr->op_begin(), OE = Curr->op_end(); OI != OE; ++OI) if (Instruction *Inst = dyn_cast<Instruction>(OI)) if (Alive.insert(Inst).second) Worklist.push_back(Inst); } // The inverse of the live set is the dead set. These are those instructions // which have no side effects and do not influence the control flow or return // value of the function, and may therefore be deleted safely. // NOTE: We reuse the Worklist vector here for memory efficiency. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) if (!Alive.count(I.getInstructionIterator())) { Worklist.push_back(I.getInstructionIterator()); I->dropAllReferences(); } for (SmallVectorImpl<Instruction *>::iterator I = Worklist.begin(), E = Worklist.end(); I != E; ++I) { ++NumRemoved; (*I)->eraseFromParent(); } return !Worklist.empty(); } FunctionPass *llvm::createAggressiveDCEPass() { return new ADCE(); } <commit_msg>[ADCE] Use inst_range and range-based fors<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Aggressive Dead Code Elimination pass. This pass // optimistically assumes that all instructions are dead until proven otherwise, // allowing it to eliminate dead computations that other DCE passes do not // catch, particularly involving loop computations. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "adce" STATISTIC(NumRemoved, "Number of instructions removed"); namespace { struct ADCE : public FunctionPass { static char ID; // Pass identification, replacement for typeid ADCE() : FunctionPass(ID) { initializeADCEPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function& F) override; void getAnalysisUsage(AnalysisUsage& AU) const override { AU.setPreservesCFG(); } }; } char ADCE::ID = 0; INITIALIZE_PASS(ADCE, "adce", "Aggressive Dead Code Elimination", false, false) bool ADCE::runOnFunction(Function& F) { if (skipOptnoneFunction(F)) return false; SmallPtrSet<Instruction*, 128> Alive; SmallVector<Instruction*, 128> Worklist; // Collect the set of "root" instructions that are known live. for (Instruction &I : inst_range(F)) { if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) || isa<LandingPadInst>(I) || I.mayHaveSideEffects()) { Alive.insert(&I); Worklist.push_back(&I); } } // Propagate liveness backwards to operands. while (!Worklist.empty()) { Instruction *Curr = Worklist.pop_back_val(); for (Instruction::op_iterator OI = Curr->op_begin(), OE = Curr->op_end(); OI != OE; ++OI) if (Instruction *Inst = dyn_cast<Instruction>(OI)) if (Alive.insert(Inst).second) Worklist.push_back(Inst); } // The inverse of the live set is the dead set. These are those instructions // which have no side effects and do not influence the control flow or return // value of the function, and may therefore be deleted safely. // NOTE: We reuse the Worklist vector here for memory efficiency. for (Instruction &I : inst_range(F)) { if (!Alive.count(&I)) { Worklist.push_back(&I); I.dropAllReferences(); } } for (Instruction *&I : Worklist) { ++NumRemoved; I->eraseFromParent(); } return !Worklist.empty(); } FunctionPass *llvm::createAggressiveDCEPass() { return new ADCE(); } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <exception> #include <stdlib.h> #include <string> #include <sstream> using std::cout; using std::endl; using std::string; static void Error(const char* msg){ cout << "ERROR: " << msg << endl; exit(EXIT_FAILURE); } static void Warn(const char* msg){ cout << "WARNING: " << msg << endl; } namespace mocc { class Exception: public std::exception { public: Exception( const char* file, int line, const char* func, const char* msg ): file_( file ), line_( line ), func_( func ), message_( msg ) { return; } const char* what() const noexcept { std::stringstream ret; ret << file_ << ":" << line_ << " in " << func_ << endl; ret << message_ << endl; std::cout << ret.str(); return ret.str().c_str(); } private: std::string file_; int line_; std::string func_; std::string message_; }; static void Fail( mocc::Exception e ) { cout << e.what(); exit(EXIT_FAILURE); } #define EXCEPT(msg) Exception(__FILE__, __LINE__, __func__, msg); } <commit_msg>Remove redundant message in exception printing<commit_after>#pragma once #include <iostream> #include <exception> #include <stdlib.h> #include <string> #include <sstream> using std::cout; using std::endl; using std::string; static void Error(const char* msg){ cout << "ERROR: " << msg << endl; exit(EXIT_FAILURE); } static void Warn(const char* msg){ cout << "WARNING: " << msg << endl; } namespace mocc { class Exception: public std::exception { public: Exception( const char* file, int line, const char* func, const char* msg ): file_( file ), line_( line ), func_( func ), message_( msg ) { return; } const char* what() const noexcept { std::stringstream ret; ret << file_ << ":" << line_ << " in " << func_ << endl; ret << message_ << endl; return ret.str().c_str(); } private: std::string file_; int line_; std::string func_; std::string message_; }; static void Fail( mocc::Exception e ) { cout << e.what(); exit(EXIT_FAILURE); } #define EXCEPT(msg) Exception(__FILE__, __LINE__, __func__, msg); } <|endoftext|>
<commit_before>//===-- asan_win_dll_thunk.cc ---------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // This file defines a family of thunks that should be statically linked into // the DLLs that have ASan instrumentation in order to delegate the calls to the // shared runtime that lives in the main binary. // See https://github.com/google/sanitizers/issues/209 for the details. //===----------------------------------------------------------------------===// #ifdef SANITIZER_DLL_THUNK #include "asan_init_version.h" #include "interception/interception.h" #include "sanitizer_common/sanitizer_win_defs.h" #include "sanitizer_common/sanitizer_win_dll_thunk.h" #include "sanitizer_common/sanitizer_platform_interceptors.h" // ASan own interface functions. #define INTERFACE_FUNCTION(Name) INTERCEPT_SANITIZER_FUNCTION(Name) #define INTERFACE_WEAK_FUNCTION(Name) INTERCEPT_SANITIZER_WEAK_FUNCTION(Name) #include "asan_interface.inc" // Memory allocation functions. INTERCEPT_WRAP_V_W(free) INTERCEPT_WRAP_V_W(_free_base) INTERCEPT_WRAP_V_WW(_free_dbg) INTERCEPT_WRAP_W_W(malloc) INTERCEPT_WRAP_W_W(_malloc_base) INTERCEPT_WRAP_W_WWWW(_malloc_dbg) INTERCEPT_WRAP_W_WW(calloc) INTERCEPT_WRAP_W_WW(_calloc_base) INTERCEPT_WRAP_W_WWWWW(_calloc_dbg) INTERCEPT_WRAP_W_WWW(_calloc_impl) INTERCEPT_WRAP_W_WW(realloc) INTERCEPT_WRAP_W_WW(_realloc_base) INTERCEPT_WRAP_W_WWW(_realloc_dbg) INTERCEPT_WRAP_W_WWW(_recalloc) INTERCEPT_WRAP_W_WWW(_recalloc_base) INTERCEPT_WRAP_W_W(_msize) INTERCEPT_WRAP_W_W(_expand) INTERCEPT_WRAP_W_W(_expand_dbg) // TODO(timurrrr): Might want to add support for _aligned_* allocation // functions to detect a bit more bugs. Those functions seem to wrap malloc(). // TODO(timurrrr): Do we need to add _Crt* stuff here? (see asan_malloc_win.cc). INTERCEPT_LIBRARY_FUNCTION(atoi); INTERCEPT_LIBRARY_FUNCTION(atol); INTERCEPT_LIBRARY_FUNCTION(frexp); INTERCEPT_LIBRARY_FUNCTION(longjmp); #if SANITIZER_INTERCEPT_MEMCHR INTERCEPT_LIBRARY_FUNCTION(memchr); #endif INTERCEPT_LIBRARY_FUNCTION(memcmp); INTERCEPT_LIBRARY_FUNCTION(memcpy); INTERCEPT_LIBRARY_FUNCTION(memmove); INTERCEPT_LIBRARY_FUNCTION(memset); INTERCEPT_LIBRARY_FUNCTION(strcat); // NOLINT INTERCEPT_LIBRARY_FUNCTION(strchr); INTERCEPT_LIBRARY_FUNCTION(strcmp); INTERCEPT_LIBRARY_FUNCTION(strcpy); // NOLINT INTERCEPT_LIBRARY_FUNCTION(strcspn); INTERCEPT_LIBRARY_FUNCTION(strdup); INTERCEPT_LIBRARY_FUNCTION(strlen); INTERCEPT_LIBRARY_FUNCTION(strncat); INTERCEPT_LIBRARY_FUNCTION(strncmp); INTERCEPT_LIBRARY_FUNCTION(strncpy); INTERCEPT_LIBRARY_FUNCTION(strnlen); INTERCEPT_LIBRARY_FUNCTION(strpbrk); INTERCEPT_LIBRARY_FUNCTION(strrchr); INTERCEPT_LIBRARY_FUNCTION(strspn); INTERCEPT_LIBRARY_FUNCTION(strstr); INTERCEPT_LIBRARY_FUNCTION(strtol); INTERCEPT_LIBRARY_FUNCTION(wcslen); #ifdef _WIN64 INTERCEPT_LIBRARY_FUNCTION(__C_specific_handler); #else INTERCEPT_LIBRARY_FUNCTION(_except_handler3); // _except_handler4 checks -GS cookie which is different for each module, so we // can't use INTERCEPT_LIBRARY_FUNCTION(_except_handler4). INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) { __asan_handle_no_return(); return REAL(_except_handler4)(a, b, c, d); } #endif // Window specific functions not included in asan_interface.inc. INTERCEPT_WRAP_W_V(__asan_should_detect_stack_use_after_return) INTERCEPT_WRAP_W_V(__asan_get_shadow_memory_dynamic_address) INTERCEPT_WRAP_W_W(__asan_unhandled_exception_filter) using namespace __sanitizer; extern "C" { int __asan_option_detect_stack_use_after_return; uptr __asan_shadow_memory_dynamic_address; } // extern "C" static int asan_dll_thunk_init() { typedef void (*fntype)(); static fntype fn = 0; // asan_dll_thunk_init is expected to be called by only one thread. if (fn) return 0; // Ensure all interception was executed. __dll_thunk_init(); fn = (fntype) dllThunkGetRealAddrOrDie("__asan_init"); fn(); __asan_option_detect_stack_use_after_return = (__asan_should_detect_stack_use_after_return() != 0); __asan_shadow_memory_dynamic_address = (uptr)__asan_get_shadow_memory_dynamic_address(); #ifndef _WIN64 INTERCEPT_FUNCTION(_except_handler4); #endif // In DLLs, the callbacks are expected to return 0, // otherwise CRT initialization fails. return 0; } #pragma section(".CRT$XIB", long, read) // NOLINT __declspec(allocate(".CRT$XIB")) int (*__asan_preinit)() = asan_dll_thunk_init; static void WINAPI asan_thread_init(void *mod, unsigned long reason, void *reserved) { if (reason == /*DLL_PROCESS_ATTACH=*/1) asan_dll_thunk_init(); } #pragma section(".CRT$XLAB", long, read) // NOLINT __declspec(allocate(".CRT$XLAB")) void (WINAPI *__asan_tls_init)(void *, unsigned long, void *) = asan_thread_init; WIN_FORCE_LINK(__asan_dso_reg_hook) #endif // SANITIZER_DLL_THUNK <commit_msg>Add strtok interceptor for ASAN for Windows.<commit_after>//===-- asan_win_dll_thunk.cc ---------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // This file defines a family of thunks that should be statically linked into // the DLLs that have ASan instrumentation in order to delegate the calls to the // shared runtime that lives in the main binary. // See https://github.com/google/sanitizers/issues/209 for the details. //===----------------------------------------------------------------------===// #ifdef SANITIZER_DLL_THUNK #include "asan_init_version.h" #include "interception/interception.h" #include "sanitizer_common/sanitizer_win_defs.h" #include "sanitizer_common/sanitizer_win_dll_thunk.h" #include "sanitizer_common/sanitizer_platform_interceptors.h" // ASan own interface functions. #define INTERFACE_FUNCTION(Name) INTERCEPT_SANITIZER_FUNCTION(Name) #define INTERFACE_WEAK_FUNCTION(Name) INTERCEPT_SANITIZER_WEAK_FUNCTION(Name) #include "asan_interface.inc" // Memory allocation functions. INTERCEPT_WRAP_V_W(free) INTERCEPT_WRAP_V_W(_free_base) INTERCEPT_WRAP_V_WW(_free_dbg) INTERCEPT_WRAP_W_W(malloc) INTERCEPT_WRAP_W_W(_malloc_base) INTERCEPT_WRAP_W_WWWW(_malloc_dbg) INTERCEPT_WRAP_W_WW(calloc) INTERCEPT_WRAP_W_WW(_calloc_base) INTERCEPT_WRAP_W_WWWWW(_calloc_dbg) INTERCEPT_WRAP_W_WWW(_calloc_impl) INTERCEPT_WRAP_W_WW(realloc) INTERCEPT_WRAP_W_WW(_realloc_base) INTERCEPT_WRAP_W_WWW(_realloc_dbg) INTERCEPT_WRAP_W_WWW(_recalloc) INTERCEPT_WRAP_W_WWW(_recalloc_base) INTERCEPT_WRAP_W_W(_msize) INTERCEPT_WRAP_W_W(_expand) INTERCEPT_WRAP_W_W(_expand_dbg) // TODO(timurrrr): Might want to add support for _aligned_* allocation // functions to detect a bit more bugs. Those functions seem to wrap malloc(). // TODO(timurrrr): Do we need to add _Crt* stuff here? (see asan_malloc_win.cc). INTERCEPT_LIBRARY_FUNCTION(atoi); INTERCEPT_LIBRARY_FUNCTION(atol); INTERCEPT_LIBRARY_FUNCTION(frexp); INTERCEPT_LIBRARY_FUNCTION(longjmp); #if SANITIZER_INTERCEPT_MEMCHR INTERCEPT_LIBRARY_FUNCTION(memchr); #endif INTERCEPT_LIBRARY_FUNCTION(memcmp); INTERCEPT_LIBRARY_FUNCTION(memcpy); INTERCEPT_LIBRARY_FUNCTION(memmove); INTERCEPT_LIBRARY_FUNCTION(memset); INTERCEPT_LIBRARY_FUNCTION(strcat); // NOLINT INTERCEPT_LIBRARY_FUNCTION(strchr); INTERCEPT_LIBRARY_FUNCTION(strcmp); INTERCEPT_LIBRARY_FUNCTION(strcpy); // NOLINT INTERCEPT_LIBRARY_FUNCTION(strcspn); INTERCEPT_LIBRARY_FUNCTION(strdup); INTERCEPT_LIBRARY_FUNCTION(strlen); INTERCEPT_LIBRARY_FUNCTION(strncat); INTERCEPT_LIBRARY_FUNCTION(strncmp); INTERCEPT_LIBRARY_FUNCTION(strncpy); INTERCEPT_LIBRARY_FUNCTION(strnlen); INTERCEPT_LIBRARY_FUNCTION(strpbrk); INTERCEPT_LIBRARY_FUNCTION(strrchr); INTERCEPT_LIBRARY_FUNCTION(strspn); INTERCEPT_LIBRARY_FUNCTION(strstr); INTERCEPT_LIBRARY_FUNCTION(strtok); INTERCEPT_LIBRARY_FUNCTION(strtol); INTERCEPT_LIBRARY_FUNCTION(wcslen); #ifdef _WIN64 INTERCEPT_LIBRARY_FUNCTION(__C_specific_handler); #else INTERCEPT_LIBRARY_FUNCTION(_except_handler3); // _except_handler4 checks -GS cookie which is different for each module, so we // can't use INTERCEPT_LIBRARY_FUNCTION(_except_handler4). INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) { __asan_handle_no_return(); return REAL(_except_handler4)(a, b, c, d); } #endif // Window specific functions not included in asan_interface.inc. INTERCEPT_WRAP_W_V(__asan_should_detect_stack_use_after_return) INTERCEPT_WRAP_W_V(__asan_get_shadow_memory_dynamic_address) INTERCEPT_WRAP_W_W(__asan_unhandled_exception_filter) using namespace __sanitizer; extern "C" { int __asan_option_detect_stack_use_after_return; uptr __asan_shadow_memory_dynamic_address; } // extern "C" static int asan_dll_thunk_init() { typedef void (*fntype)(); static fntype fn = 0; // asan_dll_thunk_init is expected to be called by only one thread. if (fn) return 0; // Ensure all interception was executed. __dll_thunk_init(); fn = (fntype) dllThunkGetRealAddrOrDie("__asan_init"); fn(); __asan_option_detect_stack_use_after_return = (__asan_should_detect_stack_use_after_return() != 0); __asan_shadow_memory_dynamic_address = (uptr)__asan_get_shadow_memory_dynamic_address(); #ifndef _WIN64 INTERCEPT_FUNCTION(_except_handler4); #endif // In DLLs, the callbacks are expected to return 0, // otherwise CRT initialization fails. return 0; } #pragma section(".CRT$XIB", long, read) // NOLINT __declspec(allocate(".CRT$XIB")) int (*__asan_preinit)() = asan_dll_thunk_init; static void WINAPI asan_thread_init(void *mod, unsigned long reason, void *reserved) { if (reason == /*DLL_PROCESS_ATTACH=*/1) asan_dll_thunk_init(); } #pragma section(".CRT$XLAB", long, read) // NOLINT __declspec(allocate(".CRT$XLAB")) void (WINAPI *__asan_tls_init)(void *, unsigned long, void *) = asan_thread_init; WIN_FORCE_LINK(__asan_dso_reg_hook) #endif // SANITIZER_DLL_THUNK <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkCellInterfaceTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkMesh.h" #include "itkVertexCell.h" #include "itkLineCell.h" #include "itkTriangleCell.h" #include "itkHexahedronCell.h" #include "itkTetrahedronCell.h" #include "itkQuadraticEdgeCell.h" #include "itkQuadraticTriangleCell.h" #include "itkQuadrilateralCell.h" /** * Define a mesh type that stores a PixelType of "int". Use the defaults * for the other template parameters. */ typedef itk::Mesh<int> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< int, CellTraits > CellInterfaceType; /** * Typedef the generic cell type for the mesh. It is an abstract class, * so we can only use information from it, like get its pointer type. */ typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Test the cell interface template<class TCell> int TestCellInterface(std::string name, TCell *aCell) { CellAutoPointer cell(aCell,true); std::cout << name << std::endl; std::cout << " Dimension: " << cell->GetDimension() << std::endl; std::cout << " NumberOfPoints: " << cell->GetNumberOfPoints() << std::endl; std::cout << " NumberOfBoundaryFeatures:" << std::endl; for (unsigned int i = 0; i < cell->GetDimension(); i++) { std::cout << " " << i << ": " << cell->GetNumberOfBoundaryFeatures(i) << std::endl; for (unsigned int j = 0; j < cell->GetNumberOfBoundaryFeatures(i); j++) { CellAutoPointer feature; cell->GetBoundaryFeature(i, j, feature); } } std::cout << " Iterator test: PointIds for empty cell: "; typename TCell::PointIdIterator pointId = cell->PointIdsBegin(); typename TCell::PointIdIterator endId = cell->PointIdsEnd(); while (pointId != endId) { std::cout << *pointId << ", "; pointId++; } std::cout << std::endl; std::cout << " ConstIterator test: PointIds for empty cell: "; typename TCell::PointIdConstIterator cpointId = cell->PointIdsBegin(); typename TCell::PointIdConstIterator cendId = cell->PointIdsEnd(); while (cpointId != cendId) { std::cout << *cpointId << ", "; cpointId++; } std::cout << std::endl; // Add point ids std::cout << " SetPointIds" << std::endl; unsigned long *pointIds = new unsigned long[cell->GetNumberOfPoints() * 2]; for (unsigned int i = 0; i < cell->GetNumberOfPoints() * 2; i++) { pointIds[i] = i; } cell->SetPointIds(pointIds); cell->SetPointId(0, 100); std::cout << " ConstIterator test: PointIds for populated cell: "; typename TCell::PointIdConstIterator ppointId = cell->PointIdsBegin(); typename TCell::PointIdConstIterator pendId = cell->PointIdsEnd(); while (ppointId != pendId) { std::cout << *ppointId << ", "; ppointId++; } std::cout << std::endl; cell->SetPointIds(&pointIds[cell->GetNumberOfPoints()], &pointIds[cell->GetNumberOfPoints() * 2]); std::cout << " Iterator test: PointIds for populated cell: "; typename TCell::PointIdIterator pxpointId = cell->PointIdsBegin(); typename TCell::PointIdIterator pxendId = cell->PointIdsEnd(); while (pxpointId != pxendId) { std::cout << *pxpointId << ", "; pxpointId++; } std::cout << std::endl; // Make a copy CellAutoPointer copyOfCell; cell->MakeCopy(copyOfCell); std::cout << " PointIds for copied cell: "; typename TCell::PointIdConstIterator xpointId = copyOfCell->PointIdsBegin(); typename TCell::PointIdConstIterator xendId = copyOfCell->PointIdsEnd(); while (xpointId != xendId) { std::cout << *xpointId << ", "; xpointId++; } std::cout << std::endl; delete []pointIds; return EXIT_SUCCESS; } int itkCellInterfaceTest(int, char* [] ) { int status; typedef itk::VertexCell<CellInterfaceType> VertexCellType; status = TestCellInterface("Vertex", new VertexCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::LineCell<CellInterfaceType> LineCellType; status = TestCellInterface("Line", new LineCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::TriangleCell<CellInterfaceType> TriangleCellType; status = TestCellInterface("Triangle", new TriangleCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::HexahedronCell<CellInterfaceType> HexahedronCellType; status = TestCellInterface("HexahedronCell", new HexahedronCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::TetrahedronCell<CellInterfaceType> TetrahedronCellType; status = TestCellInterface("TetrahedronCell", new TetrahedronCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadraticEdgeCell<CellInterfaceType> QuadraticEdgeCellType; status = TestCellInterface("QuadraticEdgeCell", new QuadraticEdgeCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadraticTriangleCell<CellInterfaceType> QuadraticTriangleCellType; status = TestCellInterface("QuadraticTriangleCell", new QuadraticTriangleCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadrilateralCell<CellInterfaceType> QuadrilateralCellType; status = TestCellInterface("QuadrilateralCell", new QuadrilateralCellType); if (status != 0) { return EXIT_FAILURE; } return status; } <commit_msg>ENH: Added PolygonCell to test.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkCellInterfaceTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkMesh.h" #include "itkVertexCell.h" #include "itkLineCell.h" #include "itkTriangleCell.h" #include "itkHexahedronCell.h" #include "itkTetrahedronCell.h" #include "itkQuadraticEdgeCell.h" #include "itkQuadraticTriangleCell.h" #include "itkQuadrilateralCell.h" #include "itkPolygonCell.h" /** * Define a mesh type that stores a PixelType of "int". Use the defaults * for the other template parameters. */ typedef itk::Mesh<int> MeshType; typedef MeshType::CellTraits CellTraits; typedef itk::CellInterface< int, CellTraits > CellInterfaceType; /** * Typedef the generic cell type for the mesh. It is an abstract class, * so we can only use information from it, like get its pointer type. */ typedef MeshType::CellType CellType; typedef CellType::CellAutoPointer CellAutoPointer; // Test the cell interface template<class TCell> int TestCellInterface(std::string name, TCell *aCell) { CellAutoPointer cell(aCell,true); std::cout << name << std::endl; std::cout << " Dimension: " << cell->GetDimension() << std::endl; std::cout << " NumberOfPoints: " << cell->GetNumberOfPoints() << std::endl; std::cout << " NumberOfBoundaryFeatures:" << std::endl; for (unsigned int i = 0; i < cell->GetDimension(); i++) { std::cout << " " << i << ": " << cell->GetNumberOfBoundaryFeatures(i) << std::endl; for (unsigned int j = 0; j < cell->GetNumberOfBoundaryFeatures(i); j++) { CellAutoPointer feature; cell->GetBoundaryFeature(i, j, feature); } } std::cout << " Iterator test: PointIds for empty cell: "; typename TCell::PointIdIterator pointId = cell->PointIdsBegin(); typename TCell::PointIdIterator endId = cell->PointIdsEnd(); while (pointId != endId) { std::cout << *pointId << ", "; pointId++; } std::cout << std::endl; std::cout << " ConstIterator test: PointIds for empty cell: "; typename TCell::PointIdConstIterator cpointId = cell->PointIdsBegin(); typename TCell::PointIdConstIterator cendId = cell->PointIdsEnd(); while (cpointId != cendId) { std::cout << *cpointId << ", "; cpointId++; } std::cout << std::endl; // Add point ids std::cout << " SetPointIds" << std::endl; unsigned long *pointIds = new unsigned long[cell->GetNumberOfPoints() * 2]; for (unsigned int i = 0; i < cell->GetNumberOfPoints() * 2; i++) { pointIds[i] = i; } cell->SetPointIds(pointIds); cell->SetPointId(0, 100); std::cout << " ConstIterator test: PointIds for populated cell: "; typename TCell::PointIdConstIterator ppointId = cell->PointIdsBegin(); typename TCell::PointIdConstIterator pendId = cell->PointIdsEnd(); while (ppointId != pendId) { std::cout << *ppointId << ", "; ppointId++; } std::cout << std::endl; cell->SetPointIds(&pointIds[cell->GetNumberOfPoints()], &pointIds[cell->GetNumberOfPoints() * 2]); std::cout << " Iterator test: PointIds for populated cell: "; typename TCell::PointIdIterator pxpointId = cell->PointIdsBegin(); typename TCell::PointIdIterator pxendId = cell->PointIdsEnd(); while (pxpointId != pxendId) { std::cout << *pxpointId << ", "; pxpointId++; } std::cout << std::endl; // Make a copy CellAutoPointer copyOfCell; cell->MakeCopy(copyOfCell); std::cout << " PointIds for copied cell: "; typename TCell::PointIdConstIterator xpointId = copyOfCell->PointIdsBegin(); typename TCell::PointIdConstIterator xendId = copyOfCell->PointIdsEnd(); while (xpointId != xendId) { std::cout << *xpointId << ", "; xpointId++; } std::cout << std::endl; delete []pointIds; return EXIT_SUCCESS; } int itkCellInterfaceTest(int, char* [] ) { int status; typedef itk::VertexCell<CellInterfaceType> VertexCellType; status = TestCellInterface("Vertex", new VertexCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::LineCell<CellInterfaceType> LineCellType; status = TestCellInterface("Line", new LineCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::TriangleCell<CellInterfaceType> TriangleCellType; status = TestCellInterface("Triangle", new TriangleCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::HexahedronCell<CellInterfaceType> HexahedronCellType; status = TestCellInterface("HexahedronCell", new HexahedronCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::TetrahedronCell<CellInterfaceType> TetrahedronCellType; status = TestCellInterface("TetrahedronCell", new TetrahedronCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadraticEdgeCell<CellInterfaceType> QuadraticEdgeCellType; status = TestCellInterface("QuadraticEdgeCell", new QuadraticEdgeCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadraticTriangleCell<CellInterfaceType> QuadraticTriangleCellType; status = TestCellInterface("QuadraticTriangleCell", new QuadraticTriangleCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::QuadrilateralCell<CellInterfaceType> QuadrilateralCellType; status = TestCellInterface("QuadrilateralCell", new QuadrilateralCellType); if (status != 0) { return EXIT_FAILURE; } typedef itk::PolygonCell<CellInterfaceType> PolygonCellType; status = TestCellInterface("PolygonCell", new PolygonCellType(5)); if (status != 0) { return EXIT_FAILURE; } return status; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSliceIteratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "itkImage.h" #include "itkNeighborhood.h" #include "itkSliceIterator.h" #include "itkImageRegionIterator.h" #include "itkSmartRegionNeighborhoodIterator.h" #include <iostream> template< class T, unsigned int N > void FillRegionSequential(itk::SmartPointer< itk::Image<T, N> > I) { unsigned int iDim, ArrayLength, i; itk::Size<N> Index; unsigned long int Location[N]; unsigned int mult; T value; itk::ImageRegionIterator<itk::Image<T, N> > data(I, I->GetRequestedRegion()); Index = (I->GetRequestedRegion()).GetSize(); data.Begin(); for (ArrayLength=1, iDim = 0; iDim<N; ++iDim) { Location[iDim] =0; ArrayLength*=Index[iDim]; } for (i=0; i<ArrayLength; ++i, ++data) { for (iDim=0, mult=1, value=0; iDim<N; ++iDim, mult*=10) { value += mult * Location[N-iDim-1]; } data.Set( value ); iDim = N-1; bool done=false; while(!done) { ++Location[iDim]; if(Location[iDim] == Index[(N-1)-iDim]) { Location[iDim] = 0; } else { done = true; } if(iDim == 0) { done = true; } else { --iDim; } } } } template< class T, unsigned int VDimension > void PrintRegion(itk::SmartPointer< itk::Image<T, VDimension> > I) { unsigned int iDim; long rsz[VDimension]; long Location[VDimension]; memcpy(rsz, I->GetRequestedRegion().GetSize().m_Size, sizeof(unsigned long) * VDimension); memset(Location, 0, sizeof(unsigned long) * VDimension); for (iDim = 0; iDim < VDimension; ++iDim) { std::cout << "iDim = " << iDim << std::endl; std::cout << "\tRegionSize = " << I->GetRequestedRegion().GetSize().m_Size[iDim] << std::endl; std::cout << "\tRegionStartIndex = " << I->GetRequestedRegion().GetIndex()[iDim] << std::endl; } itk::ImageRegionIterator<itk::Image<T, VDimension> > iter( I, I->GetRequestedRegion()); for (iter.Begin(); ! iter.IsAtEnd(); ++iter) { std::cout << iter.Get() << " "; iDim=VDimension-1; bool done=false; while(!done) { ++Location[iDim]; if(Location[iDim]==rsz[(VDimension-1)-iDim]) { std::cout << std::endl; Location[iDim]=0; } else { done = true; } if(iDim == 0) { done = true; } else { --iDim; } } } } template <class TContainer> void PrintSlice(TContainer s) { std::cout << "[" ; for (s=s.Begin(); s < s.End(); s++) { std::cout << *s << " "; } std::cout << "]" << std::endl; } int main() { try { itk::ImageRegion<2> reg; itk::Size<2> hoodRadius; itk::Size<2> imgSize; itk::Index<2> zeroIndex; zeroIndex[0]=zeroIndex[1]=0; imgSize[0]=imgSize[1]=20; hoodRadius[0]=hoodRadius[1]=2; reg.SetIndex(zeroIndex); reg.SetSize(imgSize); std::slice hslice(10, 5, 1); // slice through the horizontal center std::slice vslice(2, 5, 5); // slice through the vertical center itk::Neighborhood<int, 2> temp; itk::SliceIterator<int, itk::Neighborhood<int,2> > hnsi(&temp, hslice); itk::SliceIterator<int, itk::Neighborhood<int,2> > vnsi(&temp, vslice); itk::Neighborhood<int, 2> op; op.SetRadius(hoodRadius); itk::Index<2> idx; idx[0]=idx[1]=0; itk::Image<int, 2>::Pointer ip = itk::Image<int,2>::New(); ip->SetRequestedRegion(reg); ip->SetBufferedRegion(reg); ip->SetLargestPossibleRegion(reg); ip->Allocate(); FillRegionSequential<int, 2>(ip); PrintRegion<int,2>(ip); itk::SmartRegionNeighborhoodIterator<itk::Image<int,2> > it(hoodRadius, ip, reg); for (it = it.Begin(); !it.IsAtEnd(); ++it) { temp = it.GetNeighborhood(); temp.Print(std::cout); PrintSlice(hnsi); PrintSlice(vnsi); } } catch (itk::ExceptionObject &err) { (&err)->Print(std::cerr); return 2; } return EXIT_SUCCESS; } <commit_msg>FIX: Fix for modified iterator api<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSliceIteratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "itkImage.h" #include "itkNeighborhood.h" #include "itkSliceIterator.h" #include "itkImageRegionIterator.h" #include "itkSmartNeighborhoodIterator.h" #include <iostream> template< class T, unsigned int N > void FillRegionSequential(itk::SmartPointer< itk::Image<T, N> > I) { unsigned int iDim, ArrayLength, i; itk::Size<N> Index; unsigned long int Location[N]; unsigned int mult; T value; itk::ImageRegionIterator<itk::Image<T, N> > data(I, I->GetRequestedRegion()); Index = (I->GetRequestedRegion()).GetSize(); data.Begin(); for (ArrayLength=1, iDim = 0; iDim<N; ++iDim) { Location[iDim] =0; ArrayLength*=Index[iDim]; } for (i=0; i<ArrayLength; ++i, ++data) { for (iDim=0, mult=1, value=0; iDim<N; ++iDim, mult*=10) { value += mult * Location[N-iDim-1]; } data.Set( value ); iDim = N-1; bool done=false; while(!done) { ++Location[iDim]; if(Location[iDim] == Index[(N-1)-iDim]) { Location[iDim] = 0; } else { done = true; } if(iDim == 0) { done = true; } else { --iDim; } } } } template< class T, unsigned int VDimension > void PrintRegion(itk::SmartPointer< itk::Image<T, VDimension> > I) { unsigned int iDim; long rsz[VDimension]; long Location[VDimension]; memcpy(rsz, I->GetRequestedRegion().GetSize().m_Size, sizeof(unsigned long) * VDimension); memset(Location, 0, sizeof(unsigned long) * VDimension); for (iDim = 0; iDim < VDimension; ++iDim) { std::cout << "iDim = " << iDim << std::endl; std::cout << "\tRegionSize = " << I->GetRequestedRegion().GetSize().m_Size[iDim] << std::endl; std::cout << "\tRegionStartIndex = " << I->GetRequestedRegion().GetIndex()[iDim] << std::endl; } itk::ImageRegionIterator<itk::Image<T, VDimension> > iter( I, I->GetRequestedRegion()); for (iter.Begin(); ! iter.IsAtEnd(); ++iter) { std::cout << iter.Get() << " "; iDim=VDimension-1; bool done=false; while(!done) { ++Location[iDim]; if(Location[iDim]==rsz[(VDimension-1)-iDim]) { std::cout << std::endl; Location[iDim]=0; } else { done = true; } if(iDim == 0) { done = true; } else { --iDim; } } } } template <class TContainer> void PrintSlice(TContainer s) { std::cout << "[" ; for (s=s.Begin(); s < s.End(); s++) { std::cout << *s << " "; } std::cout << "]" << std::endl; } int main() { try { itk::ImageRegion<2> reg; itk::Size<2> hoodRadius; itk::Size<2> imgSize; itk::Index<2> zeroIndex; zeroIndex[0]=zeroIndex[1]=0; imgSize[0]=imgSize[1]=20; hoodRadius[0]=hoodRadius[1]=2; reg.SetIndex(zeroIndex); reg.SetSize(imgSize); std::slice hslice(10, 5, 1); // slice through the horizontal center std::slice vslice(2, 5, 5); // slice through the vertical center itk::Neighborhood<int, 2> temp; itk::SliceIterator<int, itk::Neighborhood<int,2> > hnsi(&temp, hslice); itk::SliceIterator<int, itk::Neighborhood<int,2> > vnsi(&temp, vslice); itk::Neighborhood<int, 2> op; op.SetRadius(hoodRadius); itk::Index<2> idx; idx[0]=idx[1]=0; itk::Image<int, 2>::Pointer ip = itk::Image<int,2>::New(); ip->SetRequestedRegion(reg); ip->SetBufferedRegion(reg); ip->SetLargestPossibleRegion(reg); ip->Allocate(); FillRegionSequential<int, 2>(ip); PrintRegion<int,2>(ip); itk::SmartNeighborhoodIterator<itk::Image<int,2> > it(hoodRadius, ip, reg); for (it.GoToBegin(); !it.IsAtEnd(); ++it) { temp = it.GetNeighborhood(); temp.Print(std::cout); PrintSlice(hnsi); PrintSlice(vnsi); } } catch (itk::ExceptionObject &err) { (&err)->Print(std::cerr); return 2; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <Poco/Buffer.h> #include <Poco/Logger.h> #include <Poco/SharedPtr.h> #include <Poco/JSON/Object.h> #include <Poco/Net/WebSocket.h> #include "gwmessage/GWGatewayRegister.h" #include "gwmessage/GWGatewayAccepted.h" #include "gws/WebSocketRequestHandler.h" #include "util/Sanitize.h" using namespace std; using namespace Poco; using namespace Poco::Net; using namespace BeeeOn; void WebSocketRequestHandler::handleRequest( HTTPServerRequest &request, HTTPServerResponse &response) { try { Thread::current()->setName("ws"); WebSocket ws(request, response); Poco::Buffer<char> buffer(m_maxMessageSize); int flags; int ret = ws.receiveFrame(buffer.begin(), buffer.size(), flags); if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE)) { if (logger().debug()) logger().debug(ws.peerAddress().toString() + " connection closed"); return; } string data(buffer.begin(), ret); if (logger().trace()) logger().trace(data); GWMessage::Ptr msg = GWMessage::fromJSON(data); GWGatewayRegister::Ptr registerMsg = msg.cast<GWGatewayRegister>(); if (registerMsg.isNull()) { logger().warning("invalid message from " + ws.peerAddress().toString() + ":\n" + msg->toString()); return; } Gateway gateway(registerMsg->gatewayID()); Thread::current()->setName("ws-" + gateway); GatewayStatus status; status.setVersion(Sanitize::common(registerMsg->version())); status.setIPAddress(registerMsg->ipAddress()); if (!m_gatewayService->registerGateway(status, gateway)) { logger().error("failed to register gateway " + gateway, __FILE__, __LINE__); return; } data = GWGatewayAccepted().toString(); ws.sendFrame(data.c_str(), data.length()); m_gatewayCommunicator->addGateway(gateway.id(), ws); } catch (const Exception &e) { logger().log(e, __FILE__, __LINE__); } catch (const exception &e) { logger().critical(e.what(), __FILE__, __LINE__); } catch (...) { logger().critical("unknown error, cought '...'", __FILE__, __LINE__); } } <commit_msg>WebSocketRequestHandler: logging: fix missing __FILE__, __LINE__<commit_after>#include <Poco/Buffer.h> #include <Poco/Logger.h> #include <Poco/SharedPtr.h> #include <Poco/JSON/Object.h> #include <Poco/Net/WebSocket.h> #include "gwmessage/GWGatewayRegister.h" #include "gwmessage/GWGatewayAccepted.h" #include "gws/WebSocketRequestHandler.h" #include "util/Sanitize.h" using namespace std; using namespace Poco; using namespace Poco::Net; using namespace BeeeOn; void WebSocketRequestHandler::handleRequest( HTTPServerRequest &request, HTTPServerResponse &response) { try { Thread::current()->setName("ws"); WebSocket ws(request, response); Poco::Buffer<char> buffer(m_maxMessageSize); int flags; int ret = ws.receiveFrame(buffer.begin(), buffer.size(), flags); if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE)) { if (logger().debug()) { logger().debug(ws.peerAddress().toString() + " connection closed", __FILE__, __LINE__); } return; } string data(buffer.begin(), ret); if (logger().trace()) logger().trace(data); GWMessage::Ptr msg = GWMessage::fromJSON(data); GWGatewayRegister::Ptr registerMsg = msg.cast<GWGatewayRegister>(); if (registerMsg.isNull()) { logger().warning("invalid message from " + ws.peerAddress().toString() + ":\n" + msg->toString(), __FILE__, __LINE__); return; } Gateway gateway(registerMsg->gatewayID()); Thread::current()->setName("ws-" + gateway); GatewayStatus status; status.setVersion(Sanitize::common(registerMsg->version())); status.setIPAddress(registerMsg->ipAddress()); if (!m_gatewayService->registerGateway(status, gateway)) { logger().error("failed to register gateway " + gateway, __FILE__, __LINE__); return; } data = GWGatewayAccepted().toString(); ws.sendFrame(data.c_str(), data.length()); m_gatewayCommunicator->addGateway(gateway.id(), ws); } catch (const Exception &e) { logger().log(e, __FILE__, __LINE__); } catch (const exception &e) { logger().critical(e.what(), __FILE__, __LINE__); } catch (...) { logger().critical("unknown error, cought '...'", __FILE__, __LINE__); } } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright (c) 2016 James Chapman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ********************************************************************************/ #pragma once #ifndef SINGLELOG_HPP #define SINGLELOG_HPP #include <atomic> #include <codecvt> #include <locale> #include <deque> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <mutex> #include <ctime> #ifdef __MINGW64__ #include "mingw.thread.h" #else #include <thread> #endif #ifdef _WIN32 #include <Windows.h> #endif namespace Uplinkzero { namespace Logging { /** * Wrapper class to handle locking on various platforms because * Critical Sections are preferable on Windows */ class ScopedLogLock { public: #ifdef _WIN32 ScopedLogLock(CRITICAL_SECTION * _cs) { m_lock = _cs; EnterCriticalSection(m_lock); } ~ScopedLogLock() { LeaveCriticalSection(m_lock); m_lock = nullptr; } #else ScopedLogLock(std::mutex * _mtx) { m_lock = _mtx; m_lock->lock(); } ~ScopedLogLock() { m_lock->unlock(); m_lock = nullptr; } #endif private: #ifdef _WIN32 CRITICAL_SECTION * m_lock; #else std::mutex * m_lock; #endif }; /** * Levels of logging available */ typedef enum _LogLevel { L_TRACE = 100, L_DEBUG = 200, L_INFO = 300, L_NOTICE = 400, L_WARNING = 500, L_ERROR = 600, L_CRITICAL = 700, L_OFF = 1000 } LogLevel; /** * string <--> wstring converter * C++11 */ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> g_converter; /** * Get current date/time, format is YYYY-MM-DD HH:mm:ss * ref: http://en.cppreference.com/w/cpp/chrono/c/wcsftime */ inline static std::string currentDateTime() { std::stringstream ss; std::time_t t = std::time(nullptr); ss << std::put_time(std::localtime(&t), "%F %T"); return ss.str(); } /** * Get current date/time, format is YYYY-MM-DD HH:mm:ss * ref: http://en.cppreference.com/w/cpp/chrono/c/wcsftime */ inline static std::wstring currentDateTimeW() { std::string dateTimeSz = currentDateTime(); return g_converter.from_bytes(dateTimeSz); } /** * Logger class */ class SingleLog { public: /** * Return a reference to the instance of this class * C++11 handles thread safety and removes the need for manual locking * http://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11 * http://stackoverflow.com/questions/33114896/reentrancy-in-static-method-with-static-variable */ static SingleLog * getInstance() { static SingleLog instance; return &instance; } /** * Destructor */ ~SingleLog() { if (!m_exit.load()) { m_exit.store(true); m_consoleWriter.join(); m_fstreamWriter.join(); } if (m_fileOut.is_open()) { m_fileOut << "\n\n"; m_fileOut.close(); } #ifdef _WIN32 DeleteCriticalSection(&m_consoleLogDequeLock); DeleteCriticalSection(&m_fstreamLogDequeLock); DeleteCriticalSection(&m_fstreamLock); #endif } /** * Set the minimum log level for the console * L_TRACE, L_DEBUG, L_INFO, L_NOTICE, L_WARNING, ERROR, L_CRITICAL, L_OFF */ void setConsoleLogLevel(LogLevel _logLevel) { m_consoleLogLevel = _logLevel; } /** * Set the minimum log level for the log file * L_TRACE, L_DEBUG, L_INFO, L_NOTICE, L_WARNING, ERROR, L_CRITICAL, L_OFF */ void setFileLogLevel(LogLevel _logLevel) { m_fileLogLevel = _logLevel; } /** * Set the path to the log file */ void setLogFilePath(std::string _filePath) { m_filePath = _filePath; m_fileOut.open(m_filePath, std::ios_base::out | std::ios_base::out); } /** * Set the path to the log file */ void setLogFilePath(std::wstring _filePath) { setLogFilePath(m_convU8.to_bytes(_filePath)); } /** * Log TRACE level messages */ #ifdef _DEBUG void trace(std::string _mod, std::string _msg) { std::string level = "TRACE"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_TRACE) { consoleLog(line); } if ((m_fileLogLevel <= L_TRACE) && (m_fileOut.is_open())) { fileLog(line); } } #else void trace(std::string _mod, std::string _msg) {} #endif /** * Log TRACE level messages */ void trace(std::wstring _mod, std::wstring _msg) { trace(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log DEBUG level messages */ void debug(std::string _mod, std::string _msg) { std::string level = "DEBUG"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_DEBUG) { consoleLog(line); } if ((m_fileLogLevel <= L_DEBUG) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log DEBUG level messages */ void debug(std::wstring _mod, std::wstring _msg) { debug(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log INFO level messages */ void info(std::string _mod, std::string _msg) { std::string level = "INFO"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_INFO) { consoleLog(line); } if ((m_fileLogLevel <= L_INFO) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log INFO level messages */ void info(std::wstring _mod, std::wstring _msg) { info(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log NOTICE level messages */ void notice(std::string _mod, std::string _msg) { std::string level = "NOTICE"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_NOTICE) { consoleLog(line); } if ((m_fileLogLevel <= L_NOTICE) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log NOTICE level messages */ void notice(std::wstring _mod, std::wstring _msg) { notice(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log WARNING level messages */ void warning(std::string _mod, std::string _msg) { std::string level = "WARNING"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_WARNING) { consoleLog(line); } if ((m_fileLogLevel <= L_WARNING) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log WARNING level messages */ void warning(std::wstring _mod, std::wstring _msg) { warning(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log ERROR level messages */ void error(std::string _mod, std::string _msg) { std::string level = "ERROR"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_ERROR) { consoleLog(line); } if ((m_fileLogLevel <= L_ERROR) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log ERROR level messages */ void error(std::wstring _mod, std::wstring _msg) { error(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } /** * Log CRITICAL level messages */ void critical(std::string _mod, std::string _msg) { std::string level = "CRITICAL"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_CRITICAL) { consoleLog(line); } if ((m_fileLogLevel <= L_CRITICAL) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log CRITICAL level messages */ void critical(std::wstring _mod, std::wstring _msg) { critical(m_convU8.to_bytes(_mod), m_convU8.to_bytes(_msg)); } private: /** * Private Constructor */ SingleLog() { #ifdef _WIN32 InitializeCriticalSection(&m_consoleLogDequeLock); InitializeCriticalSection(&m_fstreamLogDequeLock); InitializeCriticalSection(&m_fstreamLock); #endif m_consoleLogLevel = L_TRACE; m_fileLogLevel = L_TRACE; m_filePath = ""; m_exit = false; m_consoleWriter = std::thread(&SingleLog::consoleWriter, this); m_fstreamWriter = std::thread(&SingleLog::fstreamWriter, this); } /** * Copy constructor, we don't want it since this is a Singleton */ SingleLog(SingleLog const& copy) = delete; SingleLog& operator=(SingleLog const& copy) = delete; /** * string <--> wstring converter * C++11 */ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> m_winConverter; std::wstring_convert<std::codecvt_utf8<wchar_t>> m_convU8; std::wstring_convert<std::codecvt_utf16<wchar_t>> m_convU16; /** * Create a common format log line * Note: There might be a better way to produce UTF8 from ANSI text? This is "expensive". */ inline std::string makeLogLine(std::string _level, std::string _module, std::string _message) { std::stringstream ss; ss << "" << currentDateTime() << " <" << _level << "> " + _module + ": " << _message << std::endl; std::string ansi_s = ss.str(); #ifdef _WIN32 std::wstring utf16_s = m_winConverter.from_bytes(ansi_s); std::string utf8_s = m_winConverter.to_bytes(utf16_s); #else std::wstring utf16_s = m_convU16.from_bytes(ansi_s); std::string utf8_s = m_convU8.to_bytes(utf16_s); #endif return utf8_s; // return UTF-8 } /** * Log message to console deque */ inline void consoleLog(std::string _s) { ScopedLogLock lock(&m_consoleLogDequeLock); m_consoleLogDeque.push_back(_s); } /** * Log message to file deque */ inline void fileLog(std::string _s) { ScopedLogLock lock(&m_fstreamLogDequeLock); m_fstreamLogDeque.push_back(_s); } /** * Write messages to the console. */ void consoleWriter() { // while (1) { bool consoleLogEmpty = m_consoleLogDeque.empty(); if (!consoleLogEmpty) { ScopedLogLock lock(&m_consoleLogDequeLock); std::string s = m_consoleLogDeque.front(); m_consoleLogDeque.pop_front(); std::cout << s; } if ((m_exit.load()) && (consoleLogEmpty)) { break; } // Sleep, otherwise this loop just eats CPU cycles for breakfast std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } /** * Write messages to the log file. */ void fstreamWriter() { // while (1) { bool fstreamLogEmpty = m_fstreamLogDeque.empty(); if (!fstreamLogEmpty) { std::string s; { ScopedLogLock lock(&m_fstreamLogDequeLock); s = m_fstreamLogDeque.front(); m_fstreamLogDeque.pop_front(); } { ScopedLogLock lock(&m_fstreamLock); m_fileOut.flush(); m_fileOut << s; } } if ((m_exit.load()) && (fstreamLogEmpty)) { break; } // Sleep, otherwise this loop just eats CPU cycles for breakfast std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } LogLevel m_consoleLogLevel; // Min level for console logs LogLevel m_fileLogLevel; // Min level for file logs std::ofstream m_fileOut; // File output stream std::string m_filePath; // Log file path #ifdef _WIN32 CRITICAL_SECTION m_consoleLogDequeLock; CRITICAL_SECTION m_fstreamLogDequeLock; CRITICAL_SECTION m_fstreamLock; #else std::mutex m_consoleLogDequeLock; std::mutex m_fstreamLogDequeLock; std::mutex m_fstreamLock; #endif std::deque<std::string> m_consoleLogDeque; std::deque<std::string> m_fstreamLogDeque; std::atomic_bool m_exit; std::thread m_consoleWriter; std::thread m_fstreamWriter; }; }; // namespace Logging }; // namespace Uplinkzero #endif // SINGLELOG_HPP <commit_msg>Updates to improve logger quality<commit_after>/******************************************************************************* * Copyright (c) 2014 James Chapman * * * 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: * * 1. The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ********************************************************************************/ #pragma once #ifndef SINGLELOG_HPP #define SINGLELOG_HPP #include <atomic> #include <codecvt> #include <deque> #include <fstream> #include <iostream> #include <string> #include <sstream> #include <thread> #ifdef _WIN32 #include <Windows.h> #else #include <mutex> #endif namespace FourtyTwo { /** * string <--> wstring converter * C++11 */ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; /** * Levels of logging available */ typedef enum _LogLevel { L_TRACE = 100, L_DEBUG = 200, L_INFO = 300, L_NOTICE = 400, L_WARNING = 500, L_ERROR = 600, L_CRITICAL = 700, L_OFF = 1000 } LogLevel; /** * Get current date/time, format is YYYY-MM-DD HH:mm:ss * ref: http://en.cppreference.com/w/cpp/chrono/c/wcsftime */ inline static std::string currentDateTime() { time_t now = time(0); struct tm tstruct = { 0 }; char buf[30] = { 0 }; localtime_s(&tstruct, &now); asctime_s(buf, &tstruct); strftime(buf, sizeof(buf), "%F %T", &tstruct); // equivalent to "%Y-%m-%d %H:%M:%S" return buf; } /** * Get current date/time, format is YYYY-MM-DD HH:mm:ss * ref: http://en.cppreference.com/w/cpp/chrono/c/wcsftime */ inline static std::wstring currentDateTimeW() { time_t now = time(0); struct tm tstruct = { 0 }; wchar_t buf[30] = { 0 }; localtime_s(&tstruct, &now); _wasctime_s(buf, &tstruct); wcsftime(buf, sizeof(buf), L"%F %T", &tstruct); // equivalent to "%Y-%m-%d %H:%M:%S" return buf; } /** * Wrapper class to handle locking on various platforms because * Critical Sections are preferable on Windows */ class ScopedLogLock { public: #ifdef _WIN32 explicit ScopedLogLock(CRITICAL_SECTION * _cs) { m_lock = _cs; EnterCriticalSection(m_lock); } ~ScopedLogLock() { LeaveCriticalSection(m_lock); m_lock = nullptr; } #else ScopedLogLock(std::mutex * _mtx) { m_lock = _mtx; m_lock->lock(); } ~ScopedLogLock() { m_lock->unlock(); m_lock = nullptr; } #endif private: #ifdef _WIN32 CRITICAL_SECTION * m_lock; #else std::mutex * m_lock; #endif }; /** * Logger class */ class SingletonLogger { public: /** * Return a reference to the instance of this class * C++11 handles thread safety and removes the need for manual locking * http://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11 * http://stackoverflow.com/questions/33114896/reentrancy-in-static-method-with-static-variable */ static SingletonLogger * getInstance() { static SingletonLogger instance; return &instance; } /** * Destructor */ ~SingletonLogger() { if (!m_exit.load()) { m_exit.store(true); m_consoleWriter.join(); m_fstreamWriter.join(); } if (m_fileOut.is_open()) { m_fileOut << "\n\n"; m_fileOut.close(); } #ifdef _WIN32 DeleteCriticalSection(&m_consoleLogDequeLock); DeleteCriticalSection(&m_fstreamLogDequeLock); DeleteCriticalSection(&m_fstreamLock); #endif } /** * Set the minimum log level for the console * L_TRACE, L_DEBUG, L_INFO, L_NOTICE, L_WARNING, ERROR, L_CRITICAL, L_OFF */ void setConsoleLogLevel(LogLevel _logLevel) { m_consoleLogLevel = _logLevel; } /** * Set the minimum log level for the log file * L_TRACE, L_DEBUG, L_INFO, L_NOTICE, L_WARNING, ERROR, L_CRITICAL, L_OFF */ void setFileLogLevel(LogLevel _logLevel) { m_fileLogLevel = _logLevel; } /** * Set the path to the log file */ void setLogFilePath(const std::string& _filePath) { m_filePath = _filePath; m_fileOut.open(m_filePath, std::ios_base::out); } /** * Set the path to the log file */ void setLogFilePath(const std::wstring& _filePath) { setLogFilePath(converter.to_bytes(_filePath)); } /** * Log TRACE level messages */ #ifdef _DEBUG void trace(const std::string& _mod, const std::string& _msg) { std::string level = "TRACE"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_TRACE) { consoleLog(line); } if ((m_fileLogLevel <= L_TRACE) && (m_fileOut.is_open())) { fileLog(line); } } #else void trace(std::string _mod, std::string _msg) {} #endif /** * Log TRACE level messages */ void trace(const std::wstring& _mod, const std::wstring& _msg) { trace(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log DEBUG level messages */ void debug(const std::string& _mod, const std::string& _msg) { std::string level = "DEBUG"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_DEBUG) { consoleLog(line); } if ((m_fileLogLevel <= L_DEBUG) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log DEBUG level messages */ void debug(const std::wstring& _mod, const std::wstring& _msg) { debug(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log INFO level messages */ void info(const std::string& _mod, const std::string& _msg) { std::string level = "INFO"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_INFO) { consoleLog(line); } if ((m_fileLogLevel <= L_INFO) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log INFO level messages */ void info(const std::wstring& _mod, const std::wstring& _msg) { info(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log NOTICE level messages */ void notice(const std::string& _mod, const std::string& _msg) { std::string level = "NOTICE"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_NOTICE) { consoleLog(line); } if ((m_fileLogLevel <= L_NOTICE) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log NOTICE level messages */ void notice(const std::wstring& _mod, const std::wstring& _msg) { notice(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log WARNING level messages */ void warning(const std::string& _mod, const std::string& _msg) { std::string level = "WARNING"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_WARNING) { consoleLog(line); } if ((m_fileLogLevel <= L_WARNING) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log WARNING level messages */ void warning(const std::wstring& _mod, const std::wstring& _msg) { warning(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log ERROR level messages */ void error(const std::string& _mod, const std::string& _msg) { std::string level = "ERROR"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_ERROR) { consoleLog(line); } if ((m_fileLogLevel <= L_ERROR) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log ERROR level messages */ void error(const std::wstring& _mod, const std::wstring& _msg) { error(converter.to_bytes(_mod), converter.to_bytes(_msg)); } /** * Log CRITICAL level messages */ void critical(const std::string& _mod, const std::string& _msg) { std::string level = "CRITICAL"; std::string line = makeLogLine(level, _mod, _msg); if (m_consoleLogLevel <= L_CRITICAL) { consoleLog(line); } if ((m_fileLogLevel <= L_CRITICAL) && (m_fileOut.is_open())) { fileLog(line); } } /** * Log CRITICAL level messages */ void critical(const std::wstring& _mod, const std::wstring& _msg) { critical(converter.to_bytes(_mod), converter.to_bytes(_msg)); } private: /** * Private Constructor */ SingletonLogger() { #ifdef _WIN32 InitializeCriticalSection(&m_consoleLogDequeLock); InitializeCriticalSection(&m_fstreamLogDequeLock); InitializeCriticalSection(&m_fstreamLock); #endif m_consoleLogLevel = L_TRACE; m_fileLogLevel = L_TRACE; m_filePath = ""; m_exit = false; m_consoleWriter = std::thread(&SingletonLogger::consoleWriter, this); m_fstreamWriter = std::thread(&SingletonLogger::fstreamWriter, this); } /** * Copy constructor, we don't want it since this is a Singleton */ SingletonLogger(SingletonLogger const& copy) = delete; SingletonLogger& operator=(SingletonLogger const& copy) = delete; /** * Create a common format log line * Note: There might be a better way to produce UTF8 from ANSI text? This is "expensive". */ static inline std::string makeLogLine(const std::string& _level, const std::string& _module, const std::string& _message) { std::stringstream ss; ss << "" << currentDateTime() << " <" << _level << "> " + _module + ": " << _message << "\n"; std::string ansi_s = ss.str(); std::wstring utf16_s = converter.from_bytes(ansi_s); return converter.to_bytes(utf16_s); // return UTF-8 } /** * Log message to console deque */ inline void consoleLog(std::string _s) { ScopedLogLock lock(&m_consoleLogDequeLock); m_consoleLogDeque.push_back(_s); } /** * Log message to file deque */ inline void fileLog(std::string _s) { ScopedLogLock lock(&m_fstreamLogDequeLock); m_fstreamLogDeque.push_back(_s); } /** * Write messages to the console. */ void consoleWriter() { while (1) { bool consoleLogEmpty = m_consoleLogDeque.empty(); if (!consoleLogEmpty) { ScopedLogLock lock(&m_consoleLogDequeLock); std::string s = m_consoleLogDeque.front(); m_consoleLogDeque.pop_front(); std::cout << s; } if ((m_exit.load()) && (consoleLogEmpty)) { break; } // Sleep, otherwise this loop just eats CPU cycles for breakfast std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } /** * Write messages to the log file. */ void fstreamWriter() { while (1) { bool fstreamLogEmpty = m_fstreamLogDeque.empty(); if (!fstreamLogEmpty) { std::string s; { ScopedLogLock lock(&m_fstreamLogDequeLock); s = m_fstreamLogDeque.front(); m_fstreamLogDeque.pop_front(); } { ScopedLogLock lock(&m_fstreamLock); m_fileOut.flush(); m_fileOut << s; } } if ((m_exit.load()) && (fstreamLogEmpty)) { break; } // Sleep, otherwise this loop just eats CPU cycles for breakfast std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } LogLevel m_consoleLogLevel; // Min level for console logs LogLevel m_fileLogLevel; // Min level for file logs std::ofstream m_fileOut; // File output stream std::string m_filePath; // Log file path #ifdef _WIN32 CRITICAL_SECTION m_consoleLogDequeLock; CRITICAL_SECTION m_fstreamLogDequeLock; CRITICAL_SECTION m_fstreamLock; #else std::mutex m_consoleLogDequeLock; std::mutex m_fstreamLogDequeLock; std::mutex m_fstreamLock; #endif std::deque<std::string> m_consoleLogDeque; std::deque<std::string> m_fstreamLogDeque; std::atomic_bool m_exit; std::thread m_consoleWriter; std::thread m_fstreamWriter; }; }; #endif // SINGLELOG_HPP <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "browser/web_ui_controller_factory.h" #include "browser/browser_context.h" #include "browser/devtools_ui.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/url_constants.h" namespace brightray { namespace { const char kChromeUIDevToolsBundledHost[] = "devtools"; } WebUIControllerFactory::WebUIControllerFactory(BrowserContext* browser_context) : browser_context_(browser_context) { DCHECK(browser_context_); } WebUIControllerFactory::~WebUIControllerFactory() { } content::WebUI::TypeID WebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) const { if (url.host() == kChromeUIDevToolsBundledHost) { return const_cast<WebUIControllerFactory*>(this); } return content::WebUI::kNoWebUI; } bool WebUIControllerFactory::UseWebUIForURL( content::BrowserContext* browser_context, const GURL& url) const { return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI; } bool WebUIControllerFactory::UseWebUIBindingsForURL( content::BrowserContext* browser_context, const GURL& url) const { return UseWebUIForURL(browser_context, url); } content::WebUIController* WebUIControllerFactory::CreateWebUIControllerForURL( content::WebUI* web_ui, const GURL& url) const { DCHECK(browser_context_); if (url.host() == kChromeUIDevToolsBundledHost) return new DevToolsUI(browser_context_, web_ui); return NULL; } } <commit_msg>Fix cpplint errors in web_ui_controller_factory.cc<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "browser/web_ui_controller_factory.h" #include "browser/browser_context.h" #include "browser/devtools_ui.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/url_constants.h" namespace brightray { namespace { const char kChromeUIDevToolsBundledHost[] = "devtools"; } WebUIControllerFactory::WebUIControllerFactory(BrowserContext* browser_context) : browser_context_(browser_context) { DCHECK(browser_context_); } WebUIControllerFactory::~WebUIControllerFactory() { } content::WebUI::TypeID WebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) const { if (url.host() == kChromeUIDevToolsBundledHost) { return const_cast<WebUIControllerFactory*>(this); } return content::WebUI::kNoWebUI; } bool WebUIControllerFactory::UseWebUIForURL( content::BrowserContext* browser_context, const GURL& url) const { return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI; } bool WebUIControllerFactory::UseWebUIBindingsForURL( content::BrowserContext* browser_context, const GURL& url) const { return UseWebUIForURL(browser_context, url); } content::WebUIController* WebUIControllerFactory::CreateWebUIControllerForURL( content::WebUI* web_ui, const GURL& url) const { DCHECK(browser_context_); if (url.host() == kChromeUIDevToolsBundledHost) return new DevToolsUI(browser_context_, web_ui); return NULL; } } // namespace brightray <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/appcache/appcache_host.h" #include "base/logging.h" #include "webkit/appcache/appcache_request_handler.h" namespace appcache { AppCacheHost::AppCacheHost(int host_id, AppCacheFrontend* frontend, AppCacheService* service) : host_id_(host_id), pending_selected_cache_id_(kNoCacheId), frontend_(frontend), service_(service), pending_get_status_callback_(NULL), pending_start_update_callback_(NULL), pending_swap_cache_callback_(NULL), pending_callback_param_(NULL) { } AppCacheHost::~AppCacheHost() { FOR_EACH_OBSERVER(Observer, observers_, OnDestructionImminent(this)); if (associated_cache_.get()) associated_cache_->UnassociateHost(this); if (group_being_updated_.get()) group_being_updated_->RemoveUpdateObserver(this); service_->storage()->CancelDelegateCallbacks(this); } void AppCacheHost::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void AppCacheHost::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void AppCacheHost::SelectCache(const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); // First we handle an unusual case of SelectCache being called a second // time. Generally this shouldn't happen, but with bad content I think // this can occur... <html manifest=foo> <html manifest=bar></html></html> // We handle this by killing whatever loading we have initiated, and by // unassociating any hosts we currently have associated... and starting // anew with the inputs to this SelectCache call. // TODO(michaeln): at some point determine what behavior the algorithms // described in the HTML5 draft produce and have our impl produce those // results (or suggest changes to the algorihtms described in the spec // if the resulting behavior is just too insane). if (is_selection_pending()) { service_->storage()->CancelDelegateCallbacks(this); pending_selected_manifest_url_ = GURL::EmptyGURL(); pending_selected_cache_id_ = kNoCacheId; } else if (associated_cache()) { AssociateCache(NULL); } new_master_entry_url_ = GURL::EmptyGURL(); // 6.9.6 The application cache selection algorithm. // The algorithm is started here and continues in FinishCacheSelection, // after cache or group loading is complete. // Note: Foreign entries are detected on the client side and // MarkAsForeignEntry is called in that case, so that detection // step is skipped here. See WebApplicationCacheHostImpl.cc if (cache_document_was_loaded_from != kNoCacheId) { LoadSelectedCache(cache_document_was_loaded_from); return; } if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { // Note: The client detects if the document was not loaded using HTTP GET // and invokes SelectCache without a manifest url, so that detection step // is also skipped here. See WebApplicationCacheHostImpl.cc new_master_entry_url_ = document_url; LoadOrCreateGroup(manifest_url); return; } // TODO(michaeln): If there was a manifest URL, the user agent may report // to the user that it was ignored, to aid in application development. FinishCacheSelection(NULL, NULL); } // TODO(michaeln): change method name to MarkEntryAsForeign for consistency void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { service_->storage()->MarkEntryAsForeign( document_url, cache_document_was_loaded_from); SelectCache(document_url, kNoCacheId, GURL::EmptyGURL()); } void AppCacheHost::GetStatusWithCallback(GetStatusCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_get_status_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingGetStatus(); } void AppCacheHost::DoPendingGetStatus() { DCHECK(pending_get_status_callback_); pending_get_status_callback_->Run( GetStatus(), pending_callback_param_); pending_get_status_callback_ = NULL; pending_callback_param_ = NULL; } void AppCacheHost::StartUpdateWithCallback(StartUpdateCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_start_update_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingStartUpdate(); } void AppCacheHost::DoPendingStartUpdate() { DCHECK(pending_start_update_callback_); // TODO(michaeln): start an update if appropiate to do so pending_start_update_callback_->Run( false, pending_callback_param_); pending_start_update_callback_ = NULL; pending_callback_param_ = NULL; } void AppCacheHost::SwapCacheWithCallback(SwapCacheCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_swap_cache_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingSwapCache(); } void AppCacheHost::DoPendingSwapCache() { DCHECK(pending_swap_cache_callback_); // TODO(michaeln): swap if we have a cache that can be swapped. pending_swap_cache_callback_->Run( false, pending_callback_param_); pending_swap_cache_callback_ = NULL; pending_callback_param_ = NULL; } AppCacheRequestHandler* AppCacheHost::CreateRequestHandler( URLRequest* request, bool is_main_request) { if (is_main_request) return new AppCacheRequestHandler(this, true); if ((associated_cache() && associated_cache()->is_complete()) || is_selection_pending()) { return new AppCacheRequestHandler(this, false); } return NULL; } Status AppCacheHost::GetStatus() { // TODO(michaeln): determine a real status value Status status = associated_cache() ? IDLE : UNCACHED; return status; } void AppCacheHost::LoadOrCreateGroup(const GURL& manifest_url) { DCHECK(manifest_url.is_valid()); pending_selected_manifest_url_ = manifest_url; service_->storage()->LoadOrCreateGroup(manifest_url, this); } void AppCacheHost::OnGroupLoaded(AppCacheGroup* group, const GURL& manifest_url) { DCHECK(manifest_url == pending_selected_manifest_url_); pending_selected_manifest_url_ = GURL::EmptyGURL(); FinishCacheSelection(NULL, group); } void AppCacheHost::LoadSelectedCache(int64 cache_id) { DCHECK(cache_id != kNoCacheId); pending_selected_cache_id_ = cache_id; service_->storage()->LoadCache(cache_id, this); } void AppCacheHost::OnCacheLoaded(AppCache* cache, int64 cache_id) { if (cache_id == pending_main_resource_cache_id_) { pending_main_resource_cache_id_ = kNoCacheId; main_resource_cache_ = cache; } else if (cache_id == pending_selected_cache_id_) { pending_selected_cache_id_ = kNoCacheId; FinishCacheSelection(cache, NULL); } } void AppCacheHost::FinishCacheSelection( AppCache *cache, AppCacheGroup* group) { DCHECK(!associated_cache()); // 6.9.6 The application cache selection algorithm if (cache) { // If document was loaded from an application cache, Associate document // with the application cache from which it was loaded. Invoke the // application cache update process for that cache and with the browsing // context being navigated. DCHECK(cache->owning_group()); DCHECK(new_master_entry_url_.is_empty()); AssociateCache(cache); cache->owning_group()->StartUpdateWithHost(this); ObserveGroupBeingUpdated(cache->owning_group()); } else if (group) { // If document was loaded using HTTP GET or equivalent, and, there is a // manifest URL, and manifest URL has the same origin as document. // Invoke the application cache update process for manifest URL, with // the browsing context being navigated, and with document and the // resource from which document was loaded as the new master resourse. DCHECK(new_master_entry_url_.is_valid()); AssociateCache(NULL); // The UpdateJob may produce one for us later. group->StartUpdateWithNewMasterEntry(this, new_master_entry_url_); ObserveGroupBeingUpdated(group); } else { // Otherwise, the Document is not associated with any application cache. AssociateCache(NULL); } // Respond to pending callbacks now that we have a selection. if (pending_get_status_callback_) DoPendingGetStatus(); else if (pending_start_update_callback_) DoPendingStartUpdate(); else if (pending_swap_cache_callback_) DoPendingSwapCache(); FOR_EACH_OBSERVER(Observer, observers_, OnCacheSelectionComplete(this)); } void AppCacheHost::ObserveGroupBeingUpdated(AppCacheGroup* group) { DCHECK(!group_being_updated_); group_being_updated_ = group; group->AddUpdateObserver(this); } void AppCacheHost::OnUpdateComplete(AppCacheGroup* group) { DCHECK_EQ(group, group_being_updated_); group->RemoveUpdateObserver(this); // Add a reference to the newest complete cache. SetSwappableCache(group); group_being_updated_ = NULL; } void AppCacheHost::SetSwappableCache(AppCacheGroup* group) { AppCache* new_cache = group ? group->newest_complete_cache() : NULL; if (new_cache != associated_cache_) swappable_cache_ = new_cache; else swappable_cache_ = NULL; } void AppCacheHost::LoadMainResourceCache(int64 cache_id) { DCHECK(cache_id != kNoCacheId); if (pending_main_resource_cache_id_ == cache_id || (main_resource_cache_ && main_resource_cache_->cache_id() == cache_id)) { return; } pending_main_resource_cache_id_ = cache_id; service_->storage()->LoadCache(cache_id, this); } void AppCacheHost::AssociateCache(AppCache* cache) { if (associated_cache_.get()) { associated_cache_->UnassociateHost(this); } associated_cache_ = cache; if (cache) { cache->AssociateHost(this); frontend_->OnCacheSelected(host_id_, cache->cache_id(), GetStatus()); } else { frontend_->OnCacheSelected(host_id_, kNoCacheId, UNCACHED); } SetSwappableCache(cache ? cache->owning_group() : NULL); } } // namespace appcache <commit_msg>Valgrind fix<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/appcache/appcache_host.h" #include "base/logging.h" #include "webkit/appcache/appcache_request_handler.h" namespace appcache { AppCacheHost::AppCacheHost(int host_id, AppCacheFrontend* frontend, AppCacheService* service) : host_id_(host_id), pending_main_resource_cache_id_(kNoCacheId), pending_selected_cache_id_(kNoCacheId), frontend_(frontend), service_(service), pending_get_status_callback_(NULL), pending_start_update_callback_(NULL), pending_swap_cache_callback_(NULL), pending_callback_param_(NULL) { } AppCacheHost::~AppCacheHost() { FOR_EACH_OBSERVER(Observer, observers_, OnDestructionImminent(this)); if (associated_cache_.get()) associated_cache_->UnassociateHost(this); if (group_being_updated_.get()) group_being_updated_->RemoveUpdateObserver(this); service_->storage()->CancelDelegateCallbacks(this); } void AppCacheHost::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void AppCacheHost::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void AppCacheHost::SelectCache(const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); // First we handle an unusual case of SelectCache being called a second // time. Generally this shouldn't happen, but with bad content I think // this can occur... <html manifest=foo> <html manifest=bar></html></html> // We handle this by killing whatever loading we have initiated, and by // unassociating any hosts we currently have associated... and starting // anew with the inputs to this SelectCache call. // TODO(michaeln): at some point determine what behavior the algorithms // described in the HTML5 draft produce and have our impl produce those // results (or suggest changes to the algorihtms described in the spec // if the resulting behavior is just too insane). if (is_selection_pending()) { service_->storage()->CancelDelegateCallbacks(this); pending_selected_manifest_url_ = GURL::EmptyGURL(); pending_selected_cache_id_ = kNoCacheId; } else if (associated_cache()) { AssociateCache(NULL); } new_master_entry_url_ = GURL::EmptyGURL(); // 6.9.6 The application cache selection algorithm. // The algorithm is started here and continues in FinishCacheSelection, // after cache or group loading is complete. // Note: Foreign entries are detected on the client side and // MarkAsForeignEntry is called in that case, so that detection // step is skipped here. See WebApplicationCacheHostImpl.cc if (cache_document_was_loaded_from != kNoCacheId) { LoadSelectedCache(cache_document_was_loaded_from); return; } if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { // Note: The client detects if the document was not loaded using HTTP GET // and invokes SelectCache without a manifest url, so that detection step // is also skipped here. See WebApplicationCacheHostImpl.cc new_master_entry_url_ = document_url; LoadOrCreateGroup(manifest_url); return; } // TODO(michaeln): If there was a manifest URL, the user agent may report // to the user that it was ignored, to aid in application development. FinishCacheSelection(NULL, NULL); } // TODO(michaeln): change method name to MarkEntryAsForeign for consistency void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { service_->storage()->MarkEntryAsForeign( document_url, cache_document_was_loaded_from); SelectCache(document_url, kNoCacheId, GURL::EmptyGURL()); } void AppCacheHost::GetStatusWithCallback(GetStatusCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_get_status_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingGetStatus(); } void AppCacheHost::DoPendingGetStatus() { DCHECK(pending_get_status_callback_); pending_get_status_callback_->Run( GetStatus(), pending_callback_param_); pending_get_status_callback_ = NULL; pending_callback_param_ = NULL; } void AppCacheHost::StartUpdateWithCallback(StartUpdateCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_start_update_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingStartUpdate(); } void AppCacheHost::DoPendingStartUpdate() { DCHECK(pending_start_update_callback_); // TODO(michaeln): start an update if appropiate to do so pending_start_update_callback_->Run( false, pending_callback_param_); pending_start_update_callback_ = NULL; pending_callback_param_ = NULL; } void AppCacheHost::SwapCacheWithCallback(SwapCacheCallback* callback, void* callback_param) { DCHECK(!pending_start_update_callback_ && !pending_swap_cache_callback_ && !pending_get_status_callback_); pending_swap_cache_callback_ = callback; pending_callback_param_ = callback_param; if (is_selection_pending()) return; DoPendingSwapCache(); } void AppCacheHost::DoPendingSwapCache() { DCHECK(pending_swap_cache_callback_); // TODO(michaeln): swap if we have a cache that can be swapped. pending_swap_cache_callback_->Run( false, pending_callback_param_); pending_swap_cache_callback_ = NULL; pending_callback_param_ = NULL; } AppCacheRequestHandler* AppCacheHost::CreateRequestHandler( URLRequest* request, bool is_main_request) { if (is_main_request) return new AppCacheRequestHandler(this, true); if ((associated_cache() && associated_cache()->is_complete()) || is_selection_pending()) { return new AppCacheRequestHandler(this, false); } return NULL; } Status AppCacheHost::GetStatus() { // TODO(michaeln): determine a real status value Status status = associated_cache() ? IDLE : UNCACHED; return status; } void AppCacheHost::LoadOrCreateGroup(const GURL& manifest_url) { DCHECK(manifest_url.is_valid()); pending_selected_manifest_url_ = manifest_url; service_->storage()->LoadOrCreateGroup(manifest_url, this); } void AppCacheHost::OnGroupLoaded(AppCacheGroup* group, const GURL& manifest_url) { DCHECK(manifest_url == pending_selected_manifest_url_); pending_selected_manifest_url_ = GURL::EmptyGURL(); FinishCacheSelection(NULL, group); } void AppCacheHost::LoadSelectedCache(int64 cache_id) { DCHECK(cache_id != kNoCacheId); pending_selected_cache_id_ = cache_id; service_->storage()->LoadCache(cache_id, this); } void AppCacheHost::OnCacheLoaded(AppCache* cache, int64 cache_id) { if (cache_id == pending_main_resource_cache_id_) { pending_main_resource_cache_id_ = kNoCacheId; main_resource_cache_ = cache; } else if (cache_id == pending_selected_cache_id_) { pending_selected_cache_id_ = kNoCacheId; FinishCacheSelection(cache, NULL); } } void AppCacheHost::FinishCacheSelection( AppCache *cache, AppCacheGroup* group) { DCHECK(!associated_cache()); // 6.9.6 The application cache selection algorithm if (cache) { // If document was loaded from an application cache, Associate document // with the application cache from which it was loaded. Invoke the // application cache update process for that cache and with the browsing // context being navigated. DCHECK(cache->owning_group()); DCHECK(new_master_entry_url_.is_empty()); AssociateCache(cache); cache->owning_group()->StartUpdateWithHost(this); ObserveGroupBeingUpdated(cache->owning_group()); } else if (group) { // If document was loaded using HTTP GET or equivalent, and, there is a // manifest URL, and manifest URL has the same origin as document. // Invoke the application cache update process for manifest URL, with // the browsing context being navigated, and with document and the // resource from which document was loaded as the new master resourse. DCHECK(new_master_entry_url_.is_valid()); AssociateCache(NULL); // The UpdateJob may produce one for us later. group->StartUpdateWithNewMasterEntry(this, new_master_entry_url_); ObserveGroupBeingUpdated(group); } else { // Otherwise, the Document is not associated with any application cache. AssociateCache(NULL); } // Respond to pending callbacks now that we have a selection. if (pending_get_status_callback_) DoPendingGetStatus(); else if (pending_start_update_callback_) DoPendingStartUpdate(); else if (pending_swap_cache_callback_) DoPendingSwapCache(); FOR_EACH_OBSERVER(Observer, observers_, OnCacheSelectionComplete(this)); } void AppCacheHost::ObserveGroupBeingUpdated(AppCacheGroup* group) { DCHECK(!group_being_updated_); group_being_updated_ = group; group->AddUpdateObserver(this); } void AppCacheHost::OnUpdateComplete(AppCacheGroup* group) { DCHECK_EQ(group, group_being_updated_); group->RemoveUpdateObserver(this); // Add a reference to the newest complete cache. SetSwappableCache(group); group_being_updated_ = NULL; } void AppCacheHost::SetSwappableCache(AppCacheGroup* group) { AppCache* new_cache = group ? group->newest_complete_cache() : NULL; if (new_cache != associated_cache_) swappable_cache_ = new_cache; else swappable_cache_ = NULL; } void AppCacheHost::LoadMainResourceCache(int64 cache_id) { DCHECK(cache_id != kNoCacheId); if (pending_main_resource_cache_id_ == cache_id || (main_resource_cache_ && main_resource_cache_->cache_id() == cache_id)) { return; } pending_main_resource_cache_id_ = cache_id; service_->storage()->LoadCache(cache_id, this); } void AppCacheHost::AssociateCache(AppCache* cache) { if (associated_cache_.get()) { associated_cache_->UnassociateHost(this); } associated_cache_ = cache; if (cache) { cache->AssociateHost(this); frontend_->OnCacheSelected(host_id_, cache->cache_id(), GetStatus()); } else { frontend_->OnCacheSelected(host_id_, kNoCacheId, UNCACHED); } SetSwappableCache(cache ? cache->owning_group() : NULL); } } // namespace appcache <|endoftext|>
<commit_before>#include <wiringPi.h> int main (void) { wiringPiSetup () ; pinMode (0, OUTPUT) ; for (;;) { digitalWrite (0, HIGH) ; delay (500) ; digitalWrite (0, LOW) ; delay (500) ; } return 0 ; }<commit_msg>minor change<commit_after><|endoftext|>