text
stringlengths
54
60.6k
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2FBOMultiRenderTarget.h" namespace Ogre { GLES2FBOMultiRenderTarget::GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name): MultiRenderTarget(name), fbo(manager, 0 /* TODO: multisampling on MRTs? */) { } GLES2FBOMultiRenderTarget::~GLES2FBOMultiRenderTarget() { } void GLES2FBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target) { #if GL_OES_packed_depth_stencil /// Check if the render target is in the rendertarget->FBO map GLES2FrameBufferObject *fbobj = 0; target->getCustomAttribute("FBO", &fbobj); assert(fbobj); fbo.bindSurface(attachment, fbobj->getSurface(0)); GL_CHECK_ERROR; #endif // Initialise? // Set width and height mWidth = fbo.getWidth(); mHeight = fbo.getHeight(); } void GLES2FBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment) { fbo.unbindSurface(attachment); GL_CHECK_ERROR; // Set width and height mWidth = fbo.getWidth(); mHeight = fbo.getHeight(); } void GLES2FBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) { if(name=="FBO") { *static_cast<GLES2FrameBufferObject **>(pData) = &fbo; } } //----------------------------------------------------------------------------- bool GLES2FBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) { bool result; if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) ) fbo.attachDepthBuffer( depthBuffer ); return result; } //----------------------------------------------------------------------------- void GLES2FBOMultiRenderTarget::detachDepthBuffer() { fbo.detachDepthBuffer(); MultiRenderTarget::detachDepthBuffer(); } //----------------------------------------------------------------------------- void GLES2FBOMultiRenderTarget::_detachDepthBuffer() { fbo.detachDepthBuffer(); MultiRenderTarget::_detachDepthBuffer(); } } <commit_msg>Fix the GLES 2 build<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2FBOMultiRenderTarget.h" #include "OgreLogManager.h" namespace Ogre { GLES2FBOMultiRenderTarget::GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name): MultiRenderTarget(name), fbo(manager, 0 /* TODO: multisampling on MRTs? */) { } GLES2FBOMultiRenderTarget::~GLES2FBOMultiRenderTarget() { } void GLES2FBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target) { #if GL_OES_packed_depth_stencil /// Check if the render target is in the rendertarget->FBO map GLES2FrameBufferObject *fbobj = 0; target->getCustomAttribute("FBO", &fbobj); assert(fbobj); fbo.bindSurface(attachment, fbobj->getSurface(0)); GL_CHECK_ERROR; #endif // Initialise? // Set width and height mWidth = fbo.getWidth(); mHeight = fbo.getHeight(); } void GLES2FBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment) { fbo.unbindSurface(attachment); GL_CHECK_ERROR; // Set width and height mWidth = fbo.getWidth(); mHeight = fbo.getHeight(); } void GLES2FBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) { if(name=="FBO") { *static_cast<GLES2FrameBufferObject **>(pData) = &fbo; } } //----------------------------------------------------------------------------- bool GLES2FBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) { bool result; if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) ) fbo.attachDepthBuffer( depthBuffer ); return result; } //----------------------------------------------------------------------------- void GLES2FBOMultiRenderTarget::detachDepthBuffer() { fbo.detachDepthBuffer(); MultiRenderTarget::detachDepthBuffer(); } //----------------------------------------------------------------------------- void GLES2FBOMultiRenderTarget::_detachDepthBuffer() { fbo.detachDepthBuffer(); MultiRenderTarget::_detachDepthBuffer(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkBox.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkBox.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkBox, "1.1"); vtkStandardNewMacro(vtkBox); // Construct the box centered at the origin and each side length 1.0. vtkBox::vtkBox() { this->XMin[0] = -0.5; this->XMin[1] = -0.5; this->XMin[2] = -0.5; this->XMax[0] = 0.5; this->XMax[1] = 0.5; this->XMax[2] = 0.5; } // Set the bounds in various ways void vtkBox::SetBounds(float xMin, float xMax, float yMin, float yMax, float zMin, float zMax) { if ( this->XMin[0] != xMin || this->XMax[0] != xMax || this->XMin[1] != yMin || this->XMax[1] != yMax || this->XMin[2] != zMin || this->XMax[2] != yMax ) { this->XMin[0] = xMin; this->XMax[0] = xMax; this->XMin[1] = yMin; this->XMax[1] = yMax; this->XMin[2] = zMin; this->XMax[2] = zMax; for (int i=0; i<3; i++) { if ( this->XMax[i] < this->XMin[i] ) { this->XMax[i] = this->XMin[i]; } } this->Modified(); } } void vtkBox::SetBounds(float bounds[6]) { this->SetBounds(bounds[0],bounds[1], bounds[2],bounds[3], bounds[4],bounds[5]); } void vtkBox::GetBounds(float &xMin, float &xMax, float &yMin, float &yMax, float &zMin, float &zMax) { xMin = this->XMin[0]; yMin = this->XMin[1]; zMin = this->XMin[2]; xMax = this->XMax[0]; yMax = this->XMax[1]; zMax = this->XMax[2]; } void vtkBox::GetBounds(float bounds[6]) { for (int i=0; i<3; i++) { bounds[2*i] = this->XMin[i]; bounds[2*i+1] = this->XMax[i]; } } // Evaluate box equation. This differs from the similar vtkPlanes // (with six planes) because of the "rounded" nature of the corners. float vtkBox::EvaluateFunction(float x[3]) { float diff, dist, minDistance=(-VTK_LARGE_FLOAT), t, distance=0.0; int inside=1; for (int i=0; i<3; i++) { diff = this->XMax[i] - this->XMin[i]; if ( diff != 0.0 ) { t = (x[i]-this->XMin[i]) / (this->XMax[i]-this->XMin[i]); if ( t < 0.0 ) { inside = 0; dist = this->XMin[i] - x[i]; } else if ( t > 1.0 ) { inside = 0; dist = x[i] - this->XMax[i]; } else {//want negative distance, we are inside if ( t <= 0.5 ) { dist = this->XMin[i] - x[i]; } else { dist = x[i] - this->XMax[i]; } if ( dist > minDistance ) //remember, it's negative { minDistance = dist; } }//if inside } else { dist = fabs(x[i]-this->XMin[i]); if ( x[i] != this->XMin[i] ) { inside = 0; } } if ( dist > 0.0 ) { distance += dist*dist; } }//for all coordinate directions distance = sqrt(distance); if ( inside ) { return minDistance; } else { return distance; } } // Evaluate box gradient. void vtkBox::EvaluateGradient(float x[3], float n[3]) { int i, dir[3], loc[3], minAxis, minDir; float dist, minDist=VTK_LARGE_FLOAT, center[3]; // Compute the location of the point with respect to the box for (i=0; i<3; i++) { if ( x[i] < this->XMin[i] ) { loc[i] = 0; } else if ( x[i] > this->XMax[i] ) { loc[i] = 2; } else { loc[i] = 1; center[i] = (this->XMin[i] + this->XMax[i])/2.0; if ( x[i] <= center[i] ) { dist = x[i] - this->XMin[i]; dir[i] = -1; } else { dist = this->XMax[i] - x[i]; dir[i] = 1; } if ( dist < minDist ) //remember, it's negative { minDist = dist; minAxis = i; minDir = dir[i]; } }//if inside }//for all coordinate directions int indx = loc[0] + 3*loc[1] + 9*loc[2]; n[0] = n[1] = n[2] = 0.0; switch (indx) { case 0: break; } } #define VTK_RIGHT 0 #define VTK_LEFT 1 #define VTK_MIDDLE 2 // Bounding box intersection modified from Graphics Gems Vol I. The method // returns a non-zero value if the bounding box is hit. Origin[3] starts // the ray, dir[3] is the vector components of the ray in the x-y-z // directions, coord[3] is the location of hit, and t is the parametric // coordinate along line. (Notes: the intersection ray dir[3] is NOT // normalized. Valid intersections will only occur between 0<=t<=1.) char vtkBox::IntersectBox (float bounds[6], float origin[3], float dir[3], float coord[3], float& t) { char inside=1; char quadrant[3]; int i, whichPlane=0; float maxT[3], candidatePlane[3]; // First find closest planes // for (i=0; i<3; i++) { if ( origin[i] < bounds[2*i] ) { quadrant[i] = VTK_LEFT; candidatePlane[i] = bounds[2*i]; inside = 0; } else if ( origin[i] > bounds[2*i+1] ) { quadrant[i] = VTK_RIGHT; candidatePlane[i] = bounds[2*i+1]; inside = 0; } else { quadrant[i] = VTK_MIDDLE; } } // Check whether origin of ray is inside bbox // if (inside) { coord[0] = origin[0]; coord[1] = origin[1]; coord[2] = origin[2]; t = 0; return 1; } // Calculate parametric distances to plane // for (i=0; i<3; i++) { if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 ) { maxT[i] = (candidatePlane[i]-origin[i]) / dir[i]; } else { maxT[i] = -1.0; } } // Find the largest parametric value of intersection // for (i=0; i<3; i++) { if ( maxT[whichPlane] < maxT[i] ) { whichPlane = i; } } // Check for valid intersection along line // if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 ) { return 0; } else { t = maxT[whichPlane]; } // Intersection point along line is okay. Check bbox. // for (i=0; i<3; i++) { if (whichPlane != i) { coord[i] = origin[i] + maxT[whichPlane]*dir[i]; if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] ) { return 0; } } else { coord[i] = candidatePlane[i]; } } return 1; } #undef VTK_RIGHT #undef VTK_LEFT #undef VTK_MIDDLE void vtkBox::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "XMin: (" << this->XMin[0] << ", " << this->XMin[1] << ", " << this->XMin[2] << ")\n"; os << indent << "XMax: (" << this->XMax[0] << ", " << this->XMax[1] << ", " << this->XMax[2] << ")\n"; } <commit_msg>ENH:Added vtkBox implicit function; gradient computed properly<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkBox.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkBox.h" #include "vtkMath.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkBox, "1.2"); vtkStandardNewMacro(vtkBox); // Construct the box centered at the origin and each side length 1.0. vtkBox::vtkBox() { this->XMin[0] = -0.5; this->XMin[1] = -0.5; this->XMin[2] = -0.5; this->XMax[0] = 0.5; this->XMax[1] = 0.5; this->XMax[2] = 0.5; } // Set the bounds in various ways void vtkBox::SetBounds(float xMin, float xMax, float yMin, float yMax, float zMin, float zMax) { if ( this->XMin[0] != xMin || this->XMax[0] != xMax || this->XMin[1] != yMin || this->XMax[1] != yMax || this->XMin[2] != zMin || this->XMax[2] != yMax ) { this->XMin[0] = xMin; this->XMax[0] = xMax; this->XMin[1] = yMin; this->XMax[1] = yMax; this->XMin[2] = zMin; this->XMax[2] = zMax; for (int i=0; i<3; i++) { if ( this->XMax[i] < this->XMin[i] ) { this->XMax[i] = this->XMin[i]; } } this->Modified(); } } void vtkBox::SetBounds(float bounds[6]) { this->SetBounds(bounds[0],bounds[1], bounds[2],bounds[3], bounds[4],bounds[5]); } void vtkBox::GetBounds(float &xMin, float &xMax, float &yMin, float &yMax, float &zMin, float &zMax) { xMin = this->XMin[0]; yMin = this->XMin[1]; zMin = this->XMin[2]; xMax = this->XMax[0]; yMax = this->XMax[1]; zMax = this->XMax[2]; } void vtkBox::GetBounds(float bounds[6]) { for (int i=0; i<3; i++) { bounds[2*i] = this->XMin[i]; bounds[2*i+1] = this->XMax[i]; } } // Evaluate box equation. This differs from the similar vtkPlanes // (with six planes) because of the "rounded" nature of the corners. float vtkBox::EvaluateFunction(float x[3]) { float diff, dist, minDistance=(-VTK_LARGE_FLOAT), t, distance=0.0; int inside=1; for (int i=0; i<3; i++) { diff = this->XMax[i] - this->XMin[i]; if ( diff != 0.0 ) { t = (x[i]-this->XMin[i]) / (this->XMax[i]-this->XMin[i]); if ( t < 0.0 ) { inside = 0; dist = this->XMin[i] - x[i]; } else if ( t > 1.0 ) { inside = 0; dist = x[i] - this->XMax[i]; } else {//want negative distance, we are inside if ( t <= 0.5 ) { dist = this->XMin[i] - x[i]; } else { dist = x[i] - this->XMax[i]; } if ( dist > minDistance ) //remember, it's negative { minDistance = dist; } }//if inside } else { dist = fabs(x[i]-this->XMin[i]); if ( x[i] != this->XMin[i] ) { inside = 0; } } if ( dist > 0.0 ) { distance += dist*dist; } }//for all coordinate directions distance = sqrt(distance); if ( inside ) { return minDistance; } else { return distance; } } // Evaluate box gradient. void vtkBox::EvaluateGradient(float x[3], float n[3]) { int i, loc[3], minAxis=0; float dist, minDist=VTK_LARGE_FLOAT, center[3]; float inDir[3], outDir[3]; // Compute the location of the point with respect to the box. // Ultimately the point will lie in one of 27 separate regions around // or within the box. The gradient vector is computed differently in // each of the regions. inDir[0] = inDir[1] = inDir[2] = 0.0f; outDir[0] = outDir[1] = outDir[2] = 0.0f; for (i=0; i<3; i++) { center[i] = (this->XMin[i] + this->XMax[i])/2.0; if ( x[i] < this->XMin[i] ) { loc[i] = 0; outDir[i] = -1.0f; } else if ( x[i] > this->XMax[i] ) { loc[i] = 2; outDir[i] = 1.0f; } else { loc[i] = 1; if ( x[i] <= center[i] ) { dist = x[i] - this->XMin[i]; inDir[i] = -1.0f; } else { dist = this->XMax[i] - x[i]; inDir[i] = 1.0f; } if ( dist < minDist ) //remember, it's negative { minDist = dist; minAxis = i; } }//if inside }//for all coordinate directions int indx = loc[0] + 3*loc[1] + 9*loc[2]; switch (indx) { // verts - gradient points away from center point case 0: case 2: case 6: case 8: case 18: case 20: case 24: case 26: for (i=0; i<3; i++) { n[i] = x[i] - center[i]; } vtkMath::Normalize(n); break; // edges - gradient points out from axis of cube case 1: case 3: case 5: case 7: case 9: case 11: case 15: case 17: case 19: case 21: case 23: case 25: for (i=0; i<3; i++) { if ( outDir[i] != 0.0f ) { n[i] = x[i] - center[i]; } else { n[i] = 0.0; } } vtkMath::Normalize(n); break; // faces - gradient points perpendicular to face case 4: case 10: case 12: case 14: case 16: case 22: for (i=0; i<3; i++) { n[i] = outDir[i]; } break; // interior - gradient is perpendicular to closest face case 13: n[0] = n[1] = n[2] = 0.0; n[minAxis] = inDir[minAxis]; break; } } #define VTK_RIGHT 0 #define VTK_LEFT 1 #define VTK_MIDDLE 2 // Bounding box intersection modified from Graphics Gems Vol I. The method // returns a non-zero value if the bounding box is hit. Origin[3] starts // the ray, dir[3] is the vector components of the ray in the x-y-z // directions, coord[3] is the location of hit, and t is the parametric // coordinate along line. (Notes: the intersection ray dir[3] is NOT // normalized. Valid intersections will only occur between 0<=t<=1.) char vtkBox::IntersectBox (float bounds[6], float origin[3], float dir[3], float coord[3], float& t) { char inside=1; char quadrant[3]; int i, whichPlane=0; float maxT[3], candidatePlane[3]; // First find closest planes // for (i=0; i<3; i++) { if ( origin[i] < bounds[2*i] ) { quadrant[i] = VTK_LEFT; candidatePlane[i] = bounds[2*i]; inside = 0; } else if ( origin[i] > bounds[2*i+1] ) { quadrant[i] = VTK_RIGHT; candidatePlane[i] = bounds[2*i+1]; inside = 0; } else { quadrant[i] = VTK_MIDDLE; } } // Check whether origin of ray is inside bbox // if (inside) { coord[0] = origin[0]; coord[1] = origin[1]; coord[2] = origin[2]; t = 0; return 1; } // Calculate parametric distances to plane // for (i=0; i<3; i++) { if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 ) { maxT[i] = (candidatePlane[i]-origin[i]) / dir[i]; } else { maxT[i] = -1.0; } } // Find the largest parametric value of intersection // for (i=0; i<3; i++) { if ( maxT[whichPlane] < maxT[i] ) { whichPlane = i; } } // Check for valid intersection along line // if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 ) { return 0; } else { t = maxT[whichPlane]; } // Intersection point along line is okay. Check bbox. // for (i=0; i<3; i++) { if (whichPlane != i) { coord[i] = origin[i] + maxT[whichPlane]*dir[i]; if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] ) { return 0; } } else { coord[i] = candidatePlane[i]; } } return 1; } #undef VTK_RIGHT #undef VTK_LEFT #undef VTK_MIDDLE void vtkBox::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "XMin: (" << this->XMin[0] << ", " << this->XMin[1] << ", " << this->XMin[2] << ")\n"; os << indent << "XMax: (" << this->XMax[0] << ", " << this->XMax[1] << ", " << this->XMax[2] << ")\n"; } <|endoftext|>
<commit_before>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include "xml_syntax_error.h" #include "xml_document.h" #include "xml_node.h" #include "xml_parser.h" #include "html_parser.h" namespace libxmljs { v8::Persistent<v8::FunctionTemplate> memory_usage; namespace { void on_libxml_destruct(xmlNode* node) { } } // namespace LibXMLJS::LibXMLJS() { xmlInitParser(); // Not always necessary, but necessary for thread safety. // xmlRegisterNodeDefault(on_libxml_construct); xmlDeregisterNodeDefault(on_libxml_destruct); // xmlThrDefRegisterNodeDefault(on_libxml_construct); xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. // TODO: Fix this error state, maybe throw exception? const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void UpdateV8Memory() { v8::V8::AdjustAmountOfExternalAllocatedMemory(-current_xml_memory); current_xml_memory = xmlMemUsed(); v8::V8::AdjustAmountOfExternalAllocatedMemory(current_xml_memory); } v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> obj = v8::Object::New(); long c = xmlMemUsed(); obj->Set(v8::String::New("libxml"), v8::Integer::New(c)); obj->Set(v8::String::New("v8"), v8::Integer::New(current_xml_memory)); return scope.Close(obj); } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup); xmlInitMemory(); XmlSyntaxError::Initialize(target); XmlDocument::Initialize(target); XmlParser::Initialize(target); HtmlParser::Initialize(target); target->Set(v8::String::NewSymbol("version"), v8::String::New(LIBXMLJS_VERSION)); target->Set(v8::String::NewSymbol("libxml_version"), v8::String::New(LIBXML_DOTTED_VERSION)); target->Set(v8::String::NewSymbol("libxml_parser_version"), v8::String::New(xmlParserVersion)); target->Set(v8::String::NewSymbol("libxml_debug_enabled"), v8::Boolean::New(debugging)); v8::Local<v8::FunctionTemplate> func = v8::FunctionTemplate::New(MemoryUsage); memory_usage = v8::Persistent<v8::FunctionTemplate>::New(func); memory_usage->InstanceTemplate()->SetInternalFieldCount(1); target->Set(v8::String::NewSymbol("memoryUsage"), memory_usage->GetFunction()); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("xml_sax_parser.js", native_xml_sax_parser); ExecuteNativeJS("xml_document.js", native_xml_document); ExecuteNativeJS("xml_element.js", native_xml_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <commit_msg>Call xmlMemSetup in static constructor to track memory from xmlInitParser<commit_after>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include "xml_syntax_error.h" #include "xml_document.h" #include "xml_node.h" #include "xml_parser.h" #include "html_parser.h" namespace libxmljs { v8::Persistent<v8::FunctionTemplate> memory_usage; namespace { void on_libxml_destruct(xmlNode* node) { } } // namespace LibXMLJS::LibXMLJS() { xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup); xmlInitParser(); // Not always necessary, but necessary for thread safety. // xmlRegisterNodeDefault(on_libxml_construct); xmlDeregisterNodeDefault(on_libxml_destruct); // xmlThrDefRegisterNodeDefault(on_libxml_construct); xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. // TODO: Fix this error state, maybe throw exception? const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void UpdateV8Memory() { v8::V8::AdjustAmountOfExternalAllocatedMemory(-current_xml_memory); current_xml_memory = xmlMemUsed(); v8::V8::AdjustAmountOfExternalAllocatedMemory(current_xml_memory); } v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> obj = v8::Object::New(); long c = xmlMemUsed(); obj->Set(v8::String::New("libxml"), v8::Integer::New(c)); obj->Set(v8::String::New("v8"), v8::Integer::New(current_xml_memory)); return scope.Close(obj); } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; XmlSyntaxError::Initialize(target); XmlDocument::Initialize(target); XmlParser::Initialize(target); HtmlParser::Initialize(target); target->Set(v8::String::NewSymbol("version"), v8::String::New(LIBXMLJS_VERSION)); target->Set(v8::String::NewSymbol("libxml_version"), v8::String::New(LIBXML_DOTTED_VERSION)); target->Set(v8::String::NewSymbol("libxml_parser_version"), v8::String::New(xmlParserVersion)); target->Set(v8::String::NewSymbol("libxml_debug_enabled"), v8::Boolean::New(debugging)); v8::Local<v8::FunctionTemplate> func = v8::FunctionTemplate::New(MemoryUsage); memory_usage = v8::Persistent<v8::FunctionTemplate>::New(func); memory_usage->InstanceTemplate()->SetInternalFieldCount(1); target->Set(v8::String::NewSymbol("memoryUsage"), memory_usage->GetFunction()); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("xml_sax_parser.js", native_xml_sax_parser); ExecuteNativeJS("xml_document.js", native_xml_document); ExecuteNativeJS("xml_element.js", native_xml_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <|endoftext|>
<commit_before>/// \file CryptKeyEntry.cpp //----------------------------------------------------------------------------- #include "stdafx.h" #include "PasswordSafe.h" #include "CryptKeyEntry.h" #include "util.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //----------------------------------------------------------------------------- CCryptKeyEntry::CCryptKeyEntry(CWnd* pParent) : CDialog(CCryptKeyEntry::IDD, pParent) { m_cryptkey1 = ""; m_cryptkey2 = ""; } void CCryptKeyEntry::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_CRYPTKEY1, m_cryptkey1.m_mystring); DDX_Text(pDX, IDC_CRYPTKEY2, m_cryptkey2.m_mystring); } BEGIN_MESSAGE_MAP(CCryptKeyEntry, CDialog) ON_BN_CLICKED(ID_HELP, OnHelp) END_MESSAGE_MAP() void CCryptKeyEntry::OnCancel() { app.m_pMainWnd = NULL; CDialog::OnCancel(); } void CCryptKeyEntry::OnOK() { UpdateData(TRUE); if (m_cryptkey1 != m_cryptkey2) { AfxMessageBox("The two entries do not match."); ((CEdit*)GetDlgItem(IDC_CRYPTKEY2))->SetFocus(); return; } if (m_cryptkey1 == "") { AfxMessageBox("Please enter the key and verify it."); ((CEdit*)GetDlgItem(IDC_CRYPTKEY1))->SetFocus(); return; } app.m_pMainWnd = NULL; CDialog::OnOK(); } void CCryptKeyEntry::OnHelp() { WinHelp(0x20084, HELP_CONTEXT); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- <commit_msg>ThisMfcApp header, HtmlHelp<commit_after>/// \file CryptKeyEntry.cpp //----------------------------------------------------------------------------- #include "stdafx.h" #include "PasswordSafe.h" #include "ThisMfcApp.h" #include "resource.h" #include "util.h" #include "CryptKeyEntry.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //----------------------------------------------------------------------------- CCryptKeyEntry::CCryptKeyEntry(CWnd* pParent) : CDialog(CCryptKeyEntry::IDD, pParent) { m_cryptkey1 = ""; m_cryptkey2 = ""; } void CCryptKeyEntry::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_CRYPTKEY1, m_cryptkey1.m_mystring); DDX_Text(pDX, IDC_CRYPTKEY2, m_cryptkey2.m_mystring); } BEGIN_MESSAGE_MAP(CCryptKeyEntry, CDialog) ON_BN_CLICKED(ID_HELP, OnHelp) END_MESSAGE_MAP() void CCryptKeyEntry::OnCancel() { app.m_pMainWnd = NULL; CDialog::OnCancel(); } void CCryptKeyEntry::OnOK() { UpdateData(TRUE); if (m_cryptkey1 != m_cryptkey2) { AfxMessageBox("The two entries do not match."); ((CEdit*)GetDlgItem(IDC_CRYPTKEY2))->SetFocus(); return; } if (m_cryptkey1 == "") { AfxMessageBox("Please enter the key and verify it."); ((CEdit*)GetDlgItem(IDC_CRYPTKEY1))->SetFocus(); return; } app.m_pMainWnd = NULL; CDialog::OnOK(); } void CCryptKeyEntry::OnHelp() { //WinHelp(0x20084, HELP_CONTEXT); ::HtmlHelp(NULL, "pwsafe.chm::/html/pws_combo_entry.htm", HH_DISPLAY_TOPIC, 0); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/** * @file logging.cpp * @brief Logging class * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #if defined(WINDOWS_PHONE) && !defined(__STDC_LIMIT_MACROS) #define __STDC_LIMIT_MACROS #endif #include "mega/logging.h" #include <ctime> #if defined(WINDOWS_PHONE) #include <stdint.h> #endif namespace mega { Logger *SimpleLogger::logger = nullptr; // by the default, display logs with level equal or less than logInfo enum LogLevel SimpleLogger::logCurrentLevel = logInfo; long long SimpleLogger::maxPayloadLogSize = 10240; #ifdef ENABLE_LOG_PERFORMANCE #ifdef WIN32 thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #endif #else // static member initialization std::mutex SimpleLogger::outputs_mutex; OutputMap SimpleLogger::outputs; std::string SimpleLogger::getTime() { char ts[50]; time_t t = std::time(NULL); if (!std::strftime(ts, sizeof(ts), "%H:%M:%S", std::gmtime(&t))) { ts[0] = '\0'; } return ts; } void SimpleLogger::flush() { for (auto& o : outputs) { OutputStreams::iterator iter; OutputStreams vec; { std::lock_guard<std::mutex> guard(outputs_mutex); vec = o; } for (iter = vec.begin(); iter != vec.end(); iter++) { std::ostream *os = *iter; os->flush(); } } } OutputStreams SimpleLogger::getOutput(enum LogLevel ll) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); return outputs[ll]; } void SimpleLogger::addOutput(enum LogLevel ll, std::ostream *os) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); outputs[ll].push_back(os); } void SimpleLogger::setAllOutputs(std::ostream *os) { std::lock_guard<std::mutex> guard(outputs_mutex); for (auto& o : outputs) { o.push_back(os); } } #endif } // namespace <commit_msg>use gmtime_r and check return result<commit_after>/** * @file logging.cpp * @brief Logging class * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #if defined(WINDOWS_PHONE) && !defined(__STDC_LIMIT_MACROS) #define __STDC_LIMIT_MACROS #endif #include "mega/logging.h" #include <ctime> #if defined(WINDOWS_PHONE) #include <stdint.h> #endif namespace mega { Logger *SimpleLogger::logger = nullptr; // by the default, display logs with level equal or less than logInfo enum LogLevel SimpleLogger::logCurrentLevel = logInfo; long long SimpleLogger::maxPayloadLogSize = 10240; #ifdef ENABLE_LOG_PERFORMANCE #ifdef WIN32 thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #endif #else // static member initialization std::mutex SimpleLogger::outputs_mutex; OutputMap SimpleLogger::outputs; std::string SimpleLogger::getTime() { char ts[50]; time_t t = std::time(NULL); struct tm tp; if (gmtime_r(&t, &tp) && std::strftime(ts, sizeof(ts), "%H:%M:%S", &tp)) return ts; return {}; } void SimpleLogger::flush() { for (auto& o : outputs) { OutputStreams::iterator iter; OutputStreams vec; { std::lock_guard<std::mutex> guard(outputs_mutex); vec = o; } for (iter = vec.begin(); iter != vec.end(); iter++) { std::ostream *os = *iter; os->flush(); } } } OutputStreams SimpleLogger::getOutput(enum LogLevel ll) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); return outputs[ll]; } void SimpleLogger::addOutput(enum LogLevel ll, std::ostream *os) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); outputs[ll].push_back(os); } void SimpleLogger::setAllOutputs(std::ostream *os) { std::lock_guard<std::mutex> guard(outputs_mutex); for (auto& o : outputs) { o.push_back(os); } } #endif } // namespace <|endoftext|>
<commit_before>#include <string.h> #include <types.h> #include <idt.h> #include <terminal.h> #include <log.h> #include <x86.h> struct idt_entry idt[256]; struct idt_ptr idtp; void idt_set_gate(unsigned char num, unsigned long base, unsigned short sel, unsigned char flags) { idt[num].base_lo = (base & 0xFFFF); idt[num].base_hi = (base >> 16) & 0xFFFF; idt[num].sel = sel; idt[num].always0 = 0; idt[num].flags = flags; } int idt_setup() { idtp.limit = (sizeof (struct idt_entry) * 256) - 1; idtp.base = (unsigned int)&idt; memset(&idt, 0, sizeof(struct idt_entry) * 256); idt_load(); klog(0,"CPU","IDT Setup\n"); return 0; } <commit_msg>Made IDT not output at panic level<commit_after>#include <string.h> #include <types.h> #include <idt.h> #include <terminal.h> #include <log.h> #include <x86.h> struct idt_entry idt[256]; struct idt_ptr idtp; void idt_set_gate(unsigned char num, unsigned long base, unsigned short sel, unsigned char flags) { idt[num].base_lo = (base & 0xFFFF); idt[num].base_hi = (base >> 16) & 0xFFFF; idt[num].sel = sel; idt[num].always0 = 0; idt[num].flags = flags; } int idt_setup() { idtp.limit = (sizeof (struct idt_entry) * 256) - 1; idtp.base = (unsigned int)&idt; memset(&idt, 0, sizeof(struct idt_entry) * 256); idt_load(); klog(LOG_DEBUG,"CPU","IDT Setup\n"); return 0; } <|endoftext|>
<commit_before>#include "manager.h" #include "capturer.h" #include "corrector.h" #include "debug.h" #include "recognizer.h" #include "representer.h" #include "settingseditor.h" #include "task.h" #include "translator.h" #include "trayicon.h" #include "updates.h" #include <QApplication> #include <QDesktopServices> #include <QFileInfo> #include <QMessageBox> #include <QNetworkProxy> #include <QThread> namespace { #ifdef DEVELOP const auto updatesUrl = "http://localhost:8081/updates.json"; #else const auto updatesUrl = "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/" "updates.json"; #endif const auto resultHideWaitUs = 300'000; } // namespace using Loader = update::Loader; Manager::Manager() : settings_(std::make_unique<Settings>()) , updater_(std::make_unique<Loader>(Loader::Urls{{updatesUrl}})) , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_)) , models_(std::make_unique<CommonModels>()) { SOFT_ASSERT(settings_, return ); tray_ = std::make_unique<TrayIcon>(*this, *settings_); capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_); recognizer_ = std::make_unique<Recognizer>(*this, *settings_); translator_ = std::make_unique<Translator>(*this, *settings_); corrector_ = std::make_unique<Corrector>(*this, *settings_); representer_ = std::make_unique<Representer>(*this, *tray_, *settings_, *models_); qRegisterMetaType<TaskPtr>(); settings_->load(); updateSettings(); if (settings_->showMessageOnStart) tray_->showInformation(QObject::tr("Screen translator started")); warnIfOutdated(); QObject::connect(updater_.get(), &update::Loader::error, // tray_.get(), &TrayIcon::showError); QObject::connect(updater_.get(), &update::Loader::updated, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Update completed")); }); QObject::connect(updater_.get(), &update::Loader::updatesAvailable, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Updates available")); }); } Manager::~Manager() { SOFT_ASSERT(settings_, return ); if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) { settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate(); settings_->saveLastUpdateCheck(); } setupTrace(false); } void Manager::warnIfOutdated() { const auto now = QDateTime::currentDateTime(); const auto binaryInfo = QFileInfo(QApplication::applicationFilePath()); const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime); const auto deadlineDays = 90; if (date.daysTo(now) < deadlineDays) return; const auto updateDate = settings_->lastUpdateCheck; if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays) return; tray_->showInformation( QObject::tr("Current version might be outdated.\n" "Check for updates to silence this warning")); } void Manager::updateSettings() { LTRACE() << "updateSettings"; SOFT_ASSERT(settings_, return ); setupTrace(settings_->writeTrace); setupProxy(*settings_); setupUpdates(*settings_); models_->update(settings_->tessdataPath); tray_->updateSettings(); capturer_->updateSettings(); recognizer_->updateSettings(); translator_->updateSettings(); representer_->updateSettings(); tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); } void Manager::setupProxy(const Settings &settings) { if (settings.proxyType == ProxyType::System) { QNetworkProxyFactory::setUseSystemConfiguration(true); return; } QNetworkProxyFactory::setUseSystemConfiguration(false); if (settings.proxyType == ProxyType::Disabled) { QNetworkProxy::setApplicationProxy({}); return; } QNetworkProxy proxy; using T = QNetworkProxy::ProxyType; proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy : T::HttpProxy); proxy.setHostName(settings.proxyHostName); proxy.setPort(settings.proxyPort); proxy.setUser(settings.proxyUser); proxy.setPassword(settings.proxyPassword); QNetworkProxy::setApplicationProxy(proxy); } void Manager::setupUpdates(const Settings &settings) { updater_->model()->setExpansions({ {"$translators$", settings.translatorsDir}, {"$tessdata$", settings.tessdataPath}, }); SOFT_ASSERT(updateAutoChecker_, return ); updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck); updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays); } void Manager::setupTrace(bool isOn) { const auto oldFile = debug::traceFileName(); if (!isOn) { debug::setTraceFileName({}); debug::isTrace = false; if (!oldFile.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile)); return; } if (!oldFile.isEmpty()) return; const auto traceFile = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/multidir-") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"); if (!debug::setTraceFileName(traceFile)) { QMessageBox::warning( nullptr, {}, QObject::tr("Failed to setup log to file: %1").arg(traceFile)); return; } debug::isTrace = true; QMessageBox::information( nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile)); } void Manager::finishTask(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "finishTask" << task->captured << task->error; --activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { tray_->showError(task->error); tray_->setTaskActionsEnabled(false); return; } tray_->showSuccess(); } void Manager::captured(const TaskPtr &task) { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); SOFT_ASSERT(task, return ); LTRACE() << "captured" << task->captured << task->error; ++activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { finishTask(task); return; } recognizer_->recognize(task); } void Manager::captureCanceled() { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); } void Manager::recognized(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "recognized" << task->recognized << task->error; if (!task->isValid()) { finishTask(task); return; } corrector_->correct(task); } void Manager::corrected(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "corrected" << task->recognized << task->error; if (!task->isValid()) { finishTask(task); return; } if (!task->targetLanguage.isEmpty()) translator_->translate(task); else translated(task); } void Manager::translated(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "translated" << task->recognized << task->error; finishTask(task); representer_->represent(task); tray_->setTaskActionsEnabled(!task->isNull()); } void Manager::applySettings(const Settings &settings) { SOFT_ASSERT(settings_, return ); const auto lastUpdate = settings_->lastUpdateCheck; // not handled in editor *settings_ = settings; settings_->lastUpdateCheck = lastUpdate; settings_->save(); updateSettings(); } void Manager::fatalError(const QString &text) { tray_->blockActions(false); tray_->showFatalError(text); } void Manager::capture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->capture(); tray_->setRepeatCaptureEnabled(true); } void Manager::repeatCapture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); capturer_->repeatCapture(); } void Manager::captureLocked() { SOFT_ASSERT(capturer_, return ); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->captureLocked(); } void Manager::settings() { SettingsEditor editor(*this, *updater_); SOFT_ASSERT(settings_, return ); editor.setSettings(*settings_); tray_->blockActions(true); auto result = editor.exec(); tray_->blockActions(false); if (result != QDialog::Accepted) return; tray_->resetFatalError(); const auto edited = editor.settings(); applySettings(edited); } void Manager::showLast() { SOFT_ASSERT(representer_, return ); representer_->showLast(); } void Manager::showTranslator() { SOFT_ASSERT(translator_, return ); translator_->show(); } void Manager::copyLastToClipboard() { SOFT_ASSERT(representer_, return ); representer_->clipboardLast(); } void Manager::quit() { QApplication::quit(); } <commit_msg>Enable trace if env variable is set<commit_after>#include "manager.h" #include "capturer.h" #include "corrector.h" #include "debug.h" #include "recognizer.h" #include "representer.h" #include "settingseditor.h" #include "task.h" #include "translator.h" #include "trayicon.h" #include "updates.h" #include <QApplication> #include <QDesktopServices> #include <QFileInfo> #include <QMessageBox> #include <QNetworkProxy> #include <QThread> namespace { #ifdef DEVELOP const auto updatesUrl = "http://localhost:8081/updates.json"; #else const auto updatesUrl = "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/" "updates.json"; #endif const auto resultHideWaitUs = 300'000; } // namespace using Loader = update::Loader; Manager::Manager() : settings_(std::make_unique<Settings>()) , updater_(std::make_unique<Loader>(Loader::Urls{{updatesUrl}})) , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_)) , models_(std::make_unique<CommonModels>()) { SOFT_ASSERT(settings_, return ); tray_ = std::make_unique<TrayIcon>(*this, *settings_); capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_); recognizer_ = std::make_unique<Recognizer>(*this, *settings_); translator_ = std::make_unique<Translator>(*this, *settings_); corrector_ = std::make_unique<Corrector>(*this, *settings_); representer_ = std::make_unique<Representer>(*this, *tray_, *settings_, *models_); qRegisterMetaType<TaskPtr>(); settings_->load(); updateSettings(); if (settings_->showMessageOnStart) tray_->showInformation(QObject::tr("Screen translator started")); warnIfOutdated(); QObject::connect(updater_.get(), &update::Loader::error, // tray_.get(), &TrayIcon::showError); QObject::connect(updater_.get(), &update::Loader::updated, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Update completed")); }); QObject::connect(updater_.get(), &update::Loader::updatesAvailable, // tray_.get(), [this] { tray_->showInformation(QObject::tr("Updates available")); }); } Manager::~Manager() { SOFT_ASSERT(settings_, return ); if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) { settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate(); settings_->saveLastUpdateCheck(); } setupTrace(false); } void Manager::warnIfOutdated() { const auto now = QDateTime::currentDateTime(); const auto binaryInfo = QFileInfo(QApplication::applicationFilePath()); const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime); const auto deadlineDays = 90; if (date.daysTo(now) < deadlineDays) return; const auto updateDate = settings_->lastUpdateCheck; if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays) return; tray_->showInformation( QObject::tr("Current version might be outdated.\n" "Check for updates to silence this warning")); } void Manager::updateSettings() { LTRACE() << "updateSettings"; SOFT_ASSERT(settings_, return ); setupTrace(settings_->writeTrace); setupProxy(*settings_); setupUpdates(*settings_); models_->update(settings_->tessdataPath); tray_->updateSettings(); capturer_->updateSettings(); recognizer_->updateSettings(); translator_->updateSettings(); representer_->updateSettings(); tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); } void Manager::setupProxy(const Settings &settings) { if (settings.proxyType == ProxyType::System) { QNetworkProxyFactory::setUseSystemConfiguration(true); return; } QNetworkProxyFactory::setUseSystemConfiguration(false); if (settings.proxyType == ProxyType::Disabled) { QNetworkProxy::setApplicationProxy({}); return; } QNetworkProxy proxy; using T = QNetworkProxy::ProxyType; proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy : T::HttpProxy); proxy.setHostName(settings.proxyHostName); proxy.setPort(settings.proxyPort); proxy.setUser(settings.proxyUser); proxy.setPassword(settings.proxyPassword); QNetworkProxy::setApplicationProxy(proxy); } void Manager::setupUpdates(const Settings &settings) { updater_->model()->setExpansions({ {"$translators$", settings.translatorsDir}, {"$tessdata$", settings.tessdataPath}, }); SOFT_ASSERT(updateAutoChecker_, return ); updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck); updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays); } void Manager::setupTrace(bool isOn) { const auto oldFile = debug::traceFileName(); if (!isOn) { debug::setTraceFileName({}); debug::isTrace = qEnvironmentVariableIsSet("TRACE"); if (!oldFile.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile)); return; } if (!oldFile.isEmpty()) return; const auto traceFile = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/multidir-") + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss"); if (!debug::setTraceFileName(traceFile)) { QMessageBox::warning( nullptr, {}, QObject::tr("Failed to setup log to file: %1").arg(traceFile)); return; } debug::isTrace = true; QMessageBox::information( nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile)); } void Manager::finishTask(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "finishTask" << task->captured << task->error; --activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { tray_->showError(task->error); tray_->setTaskActionsEnabled(false); return; } tray_->showSuccess(); } void Manager::captured(const TaskPtr &task) { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); SOFT_ASSERT(task, return ); LTRACE() << "captured" << task->captured << task->error; ++activeTaskCount_; tray_->setActiveTaskCount(activeTaskCount_); if (!task->isValid()) { finishTask(task); return; } recognizer_->recognize(task); } void Manager::captureCanceled() { tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked()); tray_->blockActions(false); } void Manager::recognized(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "recognized" << task->recognized << task->error; if (!task->isValid()) { finishTask(task); return; } corrector_->correct(task); } void Manager::corrected(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "corrected" << task->recognized << task->error; if (!task->isValid()) { finishTask(task); return; } if (!task->targetLanguage.isEmpty()) translator_->translate(task); else translated(task); } void Manager::translated(const TaskPtr &task) { SOFT_ASSERT(task, return ); LTRACE() << "translated" << task->recognized << task->error; finishTask(task); representer_->represent(task); tray_->setTaskActionsEnabled(!task->isNull()); } void Manager::applySettings(const Settings &settings) { SOFT_ASSERT(settings_, return ); const auto lastUpdate = settings_->lastUpdateCheck; // not handled in editor *settings_ = settings; settings_->lastUpdateCheck = lastUpdate; settings_->save(); updateSettings(); } void Manager::fatalError(const QString &text) { tray_->blockActions(false); tray_->showFatalError(text); } void Manager::capture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->capture(); tray_->setRepeatCaptureEnabled(true); } void Manager::repeatCapture() { SOFT_ASSERT(capturer_, return ); tray_->blockActions(true); capturer_->repeatCapture(); } void Manager::captureLocked() { SOFT_ASSERT(capturer_, return ); if (representer_->isVisible()) { representer_->hide(); QThread::usleep(resultHideWaitUs); } capturer_->captureLocked(); } void Manager::settings() { SettingsEditor editor(*this, *updater_); SOFT_ASSERT(settings_, return ); editor.setSettings(*settings_); tray_->blockActions(true); auto result = editor.exec(); tray_->blockActions(false); if (result != QDialog::Accepted) return; tray_->resetFatalError(); const auto edited = editor.settings(); applySettings(edited); } void Manager::showLast() { SOFT_ASSERT(representer_, return ); representer_->showLast(); } void Manager::showTranslator() { SOFT_ASSERT(translator_, return ); translator_->show(); } void Manager::copyLastToClipboard() { SOFT_ASSERT(representer_, return ); representer_->clipboardLast(); } void Manager::quit() { QApplication::quit(); } <|endoftext|>
<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015-2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <set> #include <unordered_map> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "TimeUtil.h" #include "util.h" namespace { struct CollectionInfo { std::string shortened_title_, year_; unsigned article_count_; public: CollectionInfo(const std::string &shortened_title, const std::string &year) : shortened_title_(shortened_title), year_(year), article_count_(0) { } CollectionInfo() = default; CollectionInfo(const CollectionInfo &other) = default; }; bool IsCollection(const MARC::Record &record) { for (const auto &_655_field : record.getTagRange("655")) { const auto a_contents(_655_field.getFirstSubfieldWithCode('a')); if (not a_contents.empty()) { if (a_contents == "Aufsatzsammlung" or a_contents == "Festschrift" or a_contents == "Konferenzschrift") return true; } } return false; } std::string GetShortenedTitle(const MARC::Record &record, const size_t max_length) { auto complete_title(record.getCompleteTitle()); if (complete_title.length() > max_length) { if (unlikely(not TextUtil::UnicodeTruncate(&complete_title, max_length))) LOG_ERROR("bad Unicode in title of record with PPN " + record.getControlNumber() + "!"); return complete_title + "..."; } return complete_title; } bool IsPossibleYear(const std::string &year_candidate) { if (year_candidate.length() != 4) return false; for (auto ch : year_candidate) { if (not StringUtil::IsDigit(ch)) return false; } return true; } std::string YYMMDateToString(const std::string &control_number, const std::string &yymm_date) { const unsigned CURRENT_YEAR(TimeUtil::GetCurrentTimeGMT().tm_year + 1900); const unsigned TWO_DIGIT_CURRENT_YEAR(CURRENT_YEAR - 2000); unsigned year_digits; if (StringUtil::ToUnsigned(yymm_date.substr(0, 2), &year_digits)) return std::to_string(year_digits > TWO_DIGIT_CURRENT_YEAR ? 1900 + year_digits : 2000 + year_digits); LOG_WARNING("in yyMMDateToString: expected date in YYMM format, found \"" + yymm_date + "\" instead! (Control number was " + control_number + ")"); return std::to_string(CURRENT_YEAR); } std::string GetDateForWebsite(const MARC::Record &record) { const auto _008_field(record.findTag("008")); const auto &control_number(record.getControlNumber()); if (unlikely(_008_field == record.end())) LOG_ERROR("No 008 Field for website w/ control number " + control_number + "!"); return YYMMDateToString(control_number, _008_field->getContents()); } std::string GetDateForReproduction(const MARC::Record &record) { const auto _534_field(record.findTag("534")); const auto &control_number(record.getControlNumber()); if (unlikely(_534_field == record.end())) LOG_ERROR("No 534 Field for reproduction w/ control number " + control_number + "!"); const auto c_contents(_534_field->getFirstSubfieldWithCode('c')); if (c_contents.empty()) return ""; static const auto digit_matcher(RegexMatcher::RegexMatcherFactoryOrDie("(\\d+)")); return digit_matcher->matched(c_contents) ? (*digit_matcher)[1] : ""; } std::string GetDateForArticleOrReview(const MARC::Record &record) { for (const auto &_936_field : record.getTagRange("936")) { const auto j_contents(_936_field.getFirstSubfieldWithCode('j')); if (not j_contents.empty()) { static const auto year_matcher(RegexMatcher::RegexMatcherFactoryOrDie("\\d{4}")); if (year_matcher->matched(j_contents)) return (*year_matcher)[1]; } } return ""; } std::string GetDateFrom190j(const MARC::Record &record) { for (const auto &_190_field : record.getTagRange("190")) { const auto j_contents(_190_field.getFirstSubfieldWithCode('j')); if (likely(not j_contents.empty())) return j_contents; LOG_ERROR("No 190j subfield for PPN " + record.getControlNumber() + "!"); } return ""; } // Extract the sort date from the 008 field. std::string GetSortDate(const MARC::Record &record) { const auto _008_field(record.findTag("008")); if (unlikely(_008_field == record.end())) LOG_ERROR("record w/ control number " + record.getControlNumber() + " is missing a 008 field!"); const auto &_008_contents(_008_field->getContents()); if (unlikely(_008_contents.length() < 12)) return ""; const auto year_candidate(_008_contents.substr(7, 4)); if (unlikely(not IsPossibleYear(year_candidate))) LOG_ERROR("bad year in 008 field \"" + year_candidate + "\" for control number " + record.getControlNumber() + "!"); return year_candidate; } std::string GetPublicationYear(const MARC::Record &record) { if (record.isWebsite()) return GetDateForWebsite(record); if (record.isReproduction()) { const auto date(GetDateForReproduction(record)); if (not date.empty()) return date; } if ((record.isArticle() or MARC::IsAReviewArticle(record)) and not record.isMonograph()) { const auto date(GetDateForArticleOrReview(record)); if (unlikely(date.empty())) LOG_ERROR("Could not find proper 936 field date content for record w/ control number " + record.getControlNumber() + "!"); return date; } // Test whether we have a 190j field // This was generated in the pipeline for superior works that do not contain a reasonable 008(7,10) entry const std::string date(GetDateFrom190j(record)); if (not date.empty()) return date; return GetSortDate(record); } void ProcessRecords(const bool use_religious_studies_only, MARC::Reader * const marc_reader, std::unordered_map<std::string, CollectionInfo> * const ppn_to_collection_info_map) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { if (use_religious_studies_only and record.findTag("REL") == record.end()) continue; if (not IsCollection(record)) continue; ppn_to_collection_info_map->emplace(record.getControlNumber(), CollectionInfo(GetShortenedTitle(record, 30), GetPublicationYear(record))); ++record_count; } LOG_INFO("Processed " + std::to_string(record_count) + " MARC record(s)."); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) ::Usage("ixtheo|relbib marc_input stats_output"); const std::string ssg(argv[1]); if (ssg != "ixtheo" and ssg != "relbib") LOG_ERROR("Sondersammelgebiet muss \"ixtheo\" oder \"relbib\" sein!"); auto marc_reader(MARC::Reader::Factory(argv[2])); std::unordered_map<std::string, CollectionInfo> ppn_to_collection_info_map; ProcessRecords(ssg == "relbib", marc_reader.get(), &ppn_to_collection_info_map); const auto stats_output(FileUtil::OpenOutputFileOrDie(argv[3])); for (const auto &ppn_and_collection_info : ppn_to_collection_info_map) *stats_output << ppn_and_collection_info.first << ": " << ppn_and_collection_info.second.shortened_title_ << ", " << ppn_and_collection_info.second.year_ << '\n'; return EXIT_SUCCESS; } <commit_msg>First feature-complete version.<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015-2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <set> #include <unordered_map> #include <cstdio> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "TimeUtil.h" #include "util.h" namespace { struct CollectionInfo { std::string shortened_title_, year_; bool is_toc_; unsigned article_count_; public: CollectionInfo(const std::string &shortened_title, const std::string &year, const bool is_toc) : shortened_title_(shortened_title), year_(year), is_toc_(is_toc), article_count_(0) { } CollectionInfo() = default; CollectionInfo(const CollectionInfo &other) = default; }; bool IsCollection(const MARC::Record &record) { for (const auto &_655_field : record.getTagRange("655")) { const auto a_contents(_655_field.getFirstSubfieldWithCode('a')); if (not a_contents.empty()) { if (a_contents == "Aufsatzsammlung" or a_contents == "Festschrift" or a_contents == "Konferenzschrift") return true; } } return false; } std::string GetShortenedTitle(const MARC::Record &record, const size_t max_length) { auto complete_title(record.getCompleteTitle()); if (complete_title.length() > max_length) { if (unlikely(not TextUtil::UnicodeTruncate(&complete_title, max_length))) LOG_ERROR("bad Unicode in title of record with PPN " + record.getControlNumber() + "!"); return complete_title + "..."; } return complete_title; } bool IsPossibleYear(const std::string &year_candidate) { if (year_candidate.length() != 4) return false; for (auto ch : year_candidate) { if (not StringUtil::IsDigit(ch)) return false; } return true; } std::string YYMMDateToString(const std::string &control_number, const std::string &yymm_date) { const unsigned CURRENT_YEAR(TimeUtil::GetCurrentTimeGMT().tm_year + 1900); const unsigned TWO_DIGIT_CURRENT_YEAR(CURRENT_YEAR - 2000); unsigned year_digits; if (StringUtil::ToUnsigned(yymm_date.substr(0, 2), &year_digits)) return std::to_string(year_digits > TWO_DIGIT_CURRENT_YEAR ? 1900 + year_digits : 2000 + year_digits); LOG_WARNING("in yyMMDateToString: expected date in YYMM format, found \"" + yymm_date + "\" instead! (Control number was " + control_number + ")"); return std::to_string(CURRENT_YEAR); } std::string GetDateForWebsite(const MARC::Record &record) { const auto _008_field(record.findTag("008")); const auto &control_number(record.getControlNumber()); if (unlikely(_008_field == record.end())) LOG_ERROR("No 008 Field for website w/ control number " + control_number + "!"); return YYMMDateToString(control_number, _008_field->getContents()); } std::string GetDateForReproduction(const MARC::Record &record) { const auto _534_field(record.findTag("534")); const auto &control_number(record.getControlNumber()); if (unlikely(_534_field == record.end())) LOG_ERROR("No 534 Field for reproduction w/ control number " + control_number + "!"); const auto c_contents(_534_field->getFirstSubfieldWithCode('c')); if (c_contents.empty()) return ""; static const auto digit_matcher(RegexMatcher::RegexMatcherFactoryOrDie("(\\d+)")); return digit_matcher->matched(c_contents) ? (*digit_matcher)[1] : ""; } std::string GetDateForArticleOrReview(const MARC::Record &record) { for (const auto &_936_field : record.getTagRange("936")) { const auto j_contents(_936_field.getFirstSubfieldWithCode('j')); if (not j_contents.empty()) { static const auto year_matcher(RegexMatcher::RegexMatcherFactoryOrDie("(\\d{4})")); if (year_matcher->matched(j_contents)) return (*year_matcher)[1]; } } return ""; } std::string GetDateFrom190j(const MARC::Record &record) { for (const auto &_190_field : record.getTagRange("190")) { const auto j_contents(_190_field.getFirstSubfieldWithCode('j')); if (likely(not j_contents.empty())) return j_contents; LOG_ERROR("No 190j subfield for PPN " + record.getControlNumber() + "!"); } return ""; } bool HasCentruryOnly(const std::string &year_candidate) { if (year_candidate.length() != 4 or not StringUtil::IsDigit(year_candidate[0]) or not StringUtil::IsDigit(year_candidate[1])) return false; return year_candidate[2] == 'u' and year_candidate[3] == 'u'; } // Extract the sort date from the 008 field. std::string GetSortDate(const MARC::Record &record) { const auto _008_field(record.findTag("008")); if (unlikely(_008_field == record.end())) LOG_ERROR("record w/ control number " + record.getControlNumber() + " is missing a 008 field!"); const auto &_008_contents(_008_field->getContents()); if (unlikely(_008_contents.length() < 12)) return ""; const auto year_candidate(_008_contents.substr(7, 4)); if (unlikely(not HasCentruryOnly(year_candidate) and not IsPossibleYear(year_candidate))) LOG_ERROR("bad year in 008 field \"" + year_candidate + "\" for control number " + record.getControlNumber() + "!"); return year_candidate; } std::string GetPublicationYear(const MARC::Record &record) { if (record.isWebsite()) return GetDateForWebsite(record); if (record.isReproduction()) { const auto date(GetDateForReproduction(record)); if (not date.empty()) return date; } if ((record.isArticle() or MARC::IsAReviewArticle(record)) and not record.isMonograph()) { const auto date(GetDateForArticleOrReview(record)); if (unlikely(date.empty())) LOG_ERROR("Could not find proper 936 field date content for record w/ control number " + record.getControlNumber() + "!"); return date; } // Test whether we have a 190j field // This was generated in the pipeline for superior works that do not contain a reasonable 008(7,10) entry const std::string date(GetDateFrom190j(record)); if (not date.empty()) return date; return GetSortDate(record); } bool IsTOC(const MARC::Record &record) { for (const auto &_856_field : record.getTagRange("856")) { const MARC::Subfields subfields(_856_field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == '3' and (subfield.value_ == "Inhaltsverzeichnis" or subfield.value_ == "04")) return true; } } return false; } void ProcessRecords(const bool use_religious_studies_only, MARC::Reader * const marc_reader, std::unordered_map<std::string, CollectionInfo> * const ppn_to_collection_info_map) { unsigned record_count(0); while (const MARC::Record record = marc_reader->read()) { if (use_religious_studies_only and record.findTag("REL") == record.end()) continue; if (not IsCollection(record)) continue; ppn_to_collection_info_map->emplace(record.getControlNumber(), CollectionInfo(GetShortenedTitle(record, 80), GetPublicationYear(record), IsTOC(record))); ++record_count; } LOG_INFO("Processed " + std::to_string(record_count) + " MARC record(s)."); } void DetermineAttachedArticleCounts(const bool use_religious_studies_only, MARC::Reader * const marc_reader, std::unordered_map<std::string, CollectionInfo> * const ppn_to_collection_info_map) { while (const MARC::Record record = marc_reader->read()) { if (not record.isArticle()) continue; if (use_religious_studies_only and record.findTag("REL") == record.end()) continue; const auto superior_control_number(record.getSuperiorControlNumber()); const auto ppn_and_collection_info(ppn_to_collection_info_map->find(superior_control_number)); if (ppn_and_collection_info != ppn_to_collection_info_map->end()) ++ppn_and_collection_info->second.article_count_; } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) ::Usage("ixtheo|relbib marc_input stats_output"); const std::string ssg(argv[1]); if (ssg != "ixtheo" and ssg != "relbib") LOG_ERROR("Sondersammelgebiet muss \"ixtheo\" oder \"relbib\" sein!"); auto marc_reader(MARC::Reader::Factory(argv[2])); std::unordered_map<std::string, CollectionInfo> ppn_to_collection_info_map; ProcessRecords(ssg == "relbib", marc_reader.get(), &ppn_to_collection_info_map); marc_reader->rewind(); DetermineAttachedArticleCounts(ssg == "relbib", marc_reader.get(), &ppn_to_collection_info_map); const auto stats_output(FileUtil::OpenOutputFileOrDie(argv[3])); for (const auto &ppn_and_collection_info : ppn_to_collection_info_map) *stats_output << ppn_and_collection_info.first << ": " << ppn_and_collection_info.second.shortened_title_ << ", " << ppn_and_collection_info.second.year_ << ", " << (ppn_and_collection_info.second.is_toc_ ? "IHV" : "") << ", " << ppn_and_collection_info.second.article_count_ << '\n'; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2011 by Patrick Schaefer, Zuse Institute Berlin * 2011-2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "libxtreemfs/helper.h" #include <cstdio> #include <cstdlib> #include <stdint.h> #ifdef __APPLE__ #include <sys/utsname.h> #endif // __APPLE__ #ifdef WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // WIN32 #include <boost/lexical_cast.hpp> #include <string> #include "libxtreemfs/options.h" #include "libxtreemfs/xtreemfs_exception.h" #include "rpc/sync_callback.h" #include "util/logging.h" #include "xtreemfs/GlobalTypes.pb.h" #include "xtreemfs/MRC.pb.h" #include "xtreemfs/OSD.pb.h" using namespace std; using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { int CompareOSDWriteResponses( const xtreemfs::pbrpc::OSDWriteResponse* new_response, const xtreemfs::pbrpc::OSDWriteResponse* current_response) { if (new_response == NULL && current_response == NULL) { return 0; } else if (new_response != NULL && current_response == NULL) { // new_response > current_response. return 1; } else if (new_response == NULL && current_response != NULL) { // new_response < current_response. return -1; } else if ( new_response->truncate_epoch() > current_response->truncate_epoch() || (new_response->truncate_epoch() == current_response->truncate_epoch() && new_response->size_in_bytes() > current_response->size_in_bytes())) { // new_response > current_response. return 1; } else if ( new_response->truncate_epoch() < current_response->truncate_epoch() || (new_response->truncate_epoch() == current_response->truncate_epoch() && new_response->size_in_bytes() < current_response->size_in_bytes())) { // new_response < current_response. return -1; } else { // new_response == current_response. return 0; } } /** The XCap contains the Volume UUID and File ID concatenated by a ":". */ uint64_t ExtractFileIdFromXCap(const xtreemfs::pbrpc::XCap& xcap) { string string = xcap.file_id(); int start = string.find(":") + 1; int length = string.length() - start; return boost::lexical_cast<uint64_t>( string.substr(start, length)); } std::string ResolveParentDirectory(const std::string& path) { int last_slash = path.find_last_of("/"); if (path == "/" || last_slash == 0) { return "/"; } else { return path.substr(0, last_slash); } } std::string GetBasename(const std::string& path) { int last_slash = path.find_last_of("/"); if (path == "/") { return "/"; } else { // We don't allow path to have a trailing "/". assert(last_slash != (path.length() - 1)); return path.substr(last_slash + 1); } } std::string ConcatenatePath(const std::string& directory, const std::string& file) { // handle .. and . if (file == ".") { return directory; } else if (file == "..") { if (directory == "/") { return directory; } return directory.substr(0, directory.find_last_of("/")); } if (directory == "/") { return "/" + file; } else { return directory + "/" + file; } } std::string GetOSDUUIDFromXlocSet(const xtreemfs::pbrpc::XLocSet& xlocs, uint32_t replica_index, uint32_t stripe_index) { if (xlocs.replicas_size() == 0) { Logging::log->getLog(LEVEL_ERROR) << "GetOSDUUIDFromXlocSet: Empty replicas list in XlocSet: " << xlocs.DebugString() << endl; return ""; } const xtreemfs::pbrpc::Replica& replica = xlocs.replicas(replica_index); if (replica.osd_uuids_size() == 0) { Logging::log->getLog(LEVEL_ERROR) << "GetOSDUUIDFromXlocSet: No head OSD available in XlocSet:" << xlocs.DebugString() << endl; return ""; } return replica.osd_uuids(stripe_index); } std::string GetOSDUUIDFromXlocSet( const xtreemfs::pbrpc::XLocSet& xlocs) { // Get the UUID for the first replica (r=0) and the head OSD (i.e. the first // stripe, s=0). return GetOSDUUIDFromXlocSet(xlocs, 0, 0); } /** * By default this function does read random data from /dev/urandom and falls * back to using C's rand() if /dev/random is not available. */ void GenerateVersion4UUID(std::string* result) { FILE *urandom = fopen("/dev/urandom", "r"); if (!urandom) { // Use rand() instead if /dev/urandom not available. srand(static_cast<unsigned int>(time(NULL))); } // Base62 characters for UUID generation. char set[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; uint32_t block_length[] = {8, 4, 4, 4, 12}; uint32_t block_length_count = 5; char uuid[37]; uint64_t random_value; int pos = 0; for (uint32_t j = 0; j < block_length_count; j++) { for (uint32_t i = 0; i < block_length[j]; i++) { // Read random number. if (urandom) { fread(&random_value, 1, sizeof(random_value), urandom); } else { // Use C's rand() if /dev/urandom not available. random_value = rand(); // NOLINT } uuid[pos] = set[random_value % 62]; pos++; } uuid[pos++] = '-'; } uuid[36] = '\0'; *result = string(uuid); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "Generated client UUID: " << uuid << endl; } if (urandom) { fclose(urandom); } } void InitializeStat(xtreemfs::pbrpc::Stat* stat) { stat->set_dev(0); stat->set_ino(0); stat->set_mode(0); // If not set to 1, an assertion in the metadata cache will be triggered. stat->set_nlink(1); stat->set_user_id(""); stat->set_group_id(""); stat->set_size(0); stat->set_atime_ns(0); stat->set_mtime_ns(0); stat->set_ctime_ns(0); stat->set_blksize(0); stat->set_truncate_epoch(0); } bool CheckIfLocksAreEqual(const xtreemfs::pbrpc::Lock& lock1, const xtreemfs::pbrpc::Lock& lock2) { return //lock1 != NULL && lock2 != NULL && lock1.client_uuid() == lock2.client_uuid() && lock1.client_pid() == lock2.client_pid() && lock1.offset() == lock2.offset() && lock1.length() == lock2.length(); } bool CheckIfLocksDoConflict(const xtreemfs::pbrpc::Lock& lock1, const xtreemfs::pbrpc::Lock& lock2) { // 0 means to lock till the end of the file. uint64_t lock1_end = lock1.length() == 0 ? 0 : lock1.offset() + lock1.length(); uint64_t lock2_end = lock2.length() == 0 ? 0 : lock2.offset() + lock2.length(); // Check for overlaps. if (lock1_end == 0) { if (lock2_end >= lock1.offset() || lock2_end == 0) { return true; } } if (lock2_end == 0) { if (lock1_end >= lock2.offset() || lock1_end == 0) { return true; } } // Overlapping? if (!(lock1_end < lock2.offset() || lock1.offset() > lock2_end)) { // Does overlap, check for conflicting modes. return lock1.exclusive() || lock2.exclusive(); } return false; } bool CheckIfUnsignedInteger(const std::string& string) { if (string.empty()) { return false; } try { // It's needed to use a 64 bit signed integer to detect a -(2^31)-1 // as a negative value and not as an overflowed unsigned integer of // value 2^32-1. int64_t integer = boost::lexical_cast<int64_t>(string); // If casted to uint, no bad_lexical_cast is thrown for negative values - // therefore we check for them on our own. if (integer < 0) { return false; } } catch(const boost::bad_lexical_cast&) { return false; } return true; // It actually was an unsigned integer. } RPCOptions RPCOptionsFromOptions(const Options& options) { return RPCOptions(options.max_tries, options.retry_delay_s, false, // do not delay last attempt options.was_interrupted_function); } #ifdef __APPLE__ int GetMacOSXKernelVersion() { int darwin_kernel_version = -1; struct utsname uname_result; uname(&uname_result); string darwin_release(uname_result.release); size_t first_dot = darwin_release.find_first_of("."); try { darwin_kernel_version = boost::lexical_cast<int>( darwin_release.substr(0, first_dot)); } catch(const boost::bad_lexical_cast& e) { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "Failed to retrieve the kernel " "version, got: " << darwin_kernel_version << endl; } } return darwin_kernel_version; } #endif // __APPLE__ #ifdef WIN32 std::string ConvertWindowsToUTF8(const wchar_t* windows_string) { string utf8; ConvertWindowsToUTF8(windows_string, &utf8); return utf8; } void ConvertWindowsToUTF8(const wchar_t* from, std::string* utf8) { // Assume that most strings will fit into a kDefaultBufferSize sized buffer. // If not, the buffer will be increased. const size_t kDefaultBufferSize = 1024; // resize() does not count the null-terminating char, WideCharTo... does. utf8->resize(kDefaultBufferSize - 1); int r = WideCharToMultiByte(CP_UTF8, 0, from, -1, &((*utf8)[0]), kDefaultBufferSize, 0, 0); if (r == 0) { throw XtreemFSException("Failed to convert a UTF-16" " (wide character) string to an UTF8 string." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } utf8->resize(r - 1); if (r > kDefaultBufferSize) { int r2 = WideCharToMultiByte(CP_UTF8, 0, from, -1, &((*utf8)[0]), r, 0, 0); if (r != r2 || r2 == 0) { throw XtreemFSException("Failed to convert a UTF-16" " (wide character) string to an UTF8 string." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } } void ConvertUTF8ToWindows(const std::string& utf8, wchar_t* buf, int buffer_size) { int r = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, buffer_size); if (r == 0) { throw XtreemFSException("Failed to convert this UTF8 string to a UTF-16" " (wide character) string: " + utf8 + " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } std::wstring ConvertUTF8ToWindows(const std::string& utf8) { wstring win; ConvertUTF8ToWindows(utf8, &win); return win; } void ConvertUTF8ToWindows(const std::string& utf8, std::wstring* win) { // Assume that most strings will fit into a kDefaultBufferSize sized buffer. // If not, the buffer will be increased. const size_t kDefaultBufferSize = 1024; // resize() does not count the null-terminating char, MultiByteToWide... does. win->resize(kDefaultBufferSize - 1); int r = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &((*win)[0]), kDefaultBufferSize); if (r == 0) { throw XtreemFSException("Failed to convert a UTF-8" " string to an UTF16 string (wide character)." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } win->resize(r - 1); if (r > kDefaultBufferSize) { int r2 = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &((*win)[0]), r); if (r != r2 || r2 == 0) { throw XtreemFSException("Failed to convert a UTF-8" " string to an UTF16 string (wide character)." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } } #endif // WIN32 } // namespace xtreemfs <commit_msg>client: helper.cpp: Fixed wrong comment where the word "stripe" was used, but "chunk" was meant.<commit_after>/* * Copyright (c) 2010-2011 by Patrick Schaefer, Zuse Institute Berlin * 2011-2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "libxtreemfs/helper.h" #include <cstdio> #include <cstdlib> #include <stdint.h> #ifdef __APPLE__ #include <sys/utsname.h> #endif // __APPLE__ #ifdef WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // WIN32 #include <boost/lexical_cast.hpp> #include <string> #include "libxtreemfs/options.h" #include "libxtreemfs/xtreemfs_exception.h" #include "rpc/sync_callback.h" #include "util/logging.h" #include "xtreemfs/GlobalTypes.pb.h" #include "xtreemfs/MRC.pb.h" #include "xtreemfs/OSD.pb.h" using namespace std; using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { int CompareOSDWriteResponses( const xtreemfs::pbrpc::OSDWriteResponse* new_response, const xtreemfs::pbrpc::OSDWriteResponse* current_response) { if (new_response == NULL && current_response == NULL) { return 0; } else if (new_response != NULL && current_response == NULL) { // new_response > current_response. return 1; } else if (new_response == NULL && current_response != NULL) { // new_response < current_response. return -1; } else if ( new_response->truncate_epoch() > current_response->truncate_epoch() || (new_response->truncate_epoch() == current_response->truncate_epoch() && new_response->size_in_bytes() > current_response->size_in_bytes())) { // new_response > current_response. return 1; } else if ( new_response->truncate_epoch() < current_response->truncate_epoch() || (new_response->truncate_epoch() == current_response->truncate_epoch() && new_response->size_in_bytes() < current_response->size_in_bytes())) { // new_response < current_response. return -1; } else { // new_response == current_response. return 0; } } /** The XCap contains the Volume UUID and File ID concatenated by a ":". */ uint64_t ExtractFileIdFromXCap(const xtreemfs::pbrpc::XCap& xcap) { string string = xcap.file_id(); int start = string.find(":") + 1; int length = string.length() - start; return boost::lexical_cast<uint64_t>( string.substr(start, length)); } std::string ResolveParentDirectory(const std::string& path) { int last_slash = path.find_last_of("/"); if (path == "/" || last_slash == 0) { return "/"; } else { return path.substr(0, last_slash); } } std::string GetBasename(const std::string& path) { int last_slash = path.find_last_of("/"); if (path == "/") { return "/"; } else { // We don't allow path to have a trailing "/". assert(last_slash != (path.length() - 1)); return path.substr(last_slash + 1); } } std::string ConcatenatePath(const std::string& directory, const std::string& file) { // handle .. and . if (file == ".") { return directory; } else if (file == "..") { if (directory == "/") { return directory; } return directory.substr(0, directory.find_last_of("/")); } if (directory == "/") { return "/" + file; } else { return directory + "/" + file; } } std::string GetOSDUUIDFromXlocSet(const xtreemfs::pbrpc::XLocSet& xlocs, uint32_t replica_index, uint32_t stripe_index) { if (xlocs.replicas_size() == 0) { Logging::log->getLog(LEVEL_ERROR) << "GetOSDUUIDFromXlocSet: Empty replicas list in XlocSet: " << xlocs.DebugString() << endl; return ""; } const xtreemfs::pbrpc::Replica& replica = xlocs.replicas(replica_index); if (replica.osd_uuids_size() == 0) { Logging::log->getLog(LEVEL_ERROR) << "GetOSDUUIDFromXlocSet: No head OSD available in XlocSet:" << xlocs.DebugString() << endl; return ""; } return replica.osd_uuids(stripe_index); } std::string GetOSDUUIDFromXlocSet( const xtreemfs::pbrpc::XLocSet& xlocs) { // Get the UUID for the first replica (r=0) and the head OSD (i.e. the first // chunk, c=0). return GetOSDUUIDFromXlocSet(xlocs, 0, 0); } /** * By default this function does read random data from /dev/urandom and falls * back to using C's rand() if /dev/random is not available. */ void GenerateVersion4UUID(std::string* result) { FILE *urandom = fopen("/dev/urandom", "r"); if (!urandom) { // Use rand() instead if /dev/urandom not available. srand(static_cast<unsigned int>(time(NULL))); } // Base62 characters for UUID generation. char set[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; uint32_t block_length[] = {8, 4, 4, 4, 12}; uint32_t block_length_count = 5; char uuid[37]; uint64_t random_value; int pos = 0; for (uint32_t j = 0; j < block_length_count; j++) { for (uint32_t i = 0; i < block_length[j]; i++) { // Read random number. if (urandom) { fread(&random_value, 1, sizeof(random_value), urandom); } else { // Use C's rand() if /dev/urandom not available. random_value = rand(); // NOLINT } uuid[pos] = set[random_value % 62]; pos++; } uuid[pos++] = '-'; } uuid[36] = '\0'; *result = string(uuid); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "Generated client UUID: " << uuid << endl; } if (urandom) { fclose(urandom); } } void InitializeStat(xtreemfs::pbrpc::Stat* stat) { stat->set_dev(0); stat->set_ino(0); stat->set_mode(0); // If not set to 1, an assertion in the metadata cache will be triggered. stat->set_nlink(1); stat->set_user_id(""); stat->set_group_id(""); stat->set_size(0); stat->set_atime_ns(0); stat->set_mtime_ns(0); stat->set_ctime_ns(0); stat->set_blksize(0); stat->set_truncate_epoch(0); } bool CheckIfLocksAreEqual(const xtreemfs::pbrpc::Lock& lock1, const xtreemfs::pbrpc::Lock& lock2) { return //lock1 != NULL && lock2 != NULL && lock1.client_uuid() == lock2.client_uuid() && lock1.client_pid() == lock2.client_pid() && lock1.offset() == lock2.offset() && lock1.length() == lock2.length(); } bool CheckIfLocksDoConflict(const xtreemfs::pbrpc::Lock& lock1, const xtreemfs::pbrpc::Lock& lock2) { // 0 means to lock till the end of the file. uint64_t lock1_end = lock1.length() == 0 ? 0 : lock1.offset() + lock1.length(); uint64_t lock2_end = lock2.length() == 0 ? 0 : lock2.offset() + lock2.length(); // Check for overlaps. if (lock1_end == 0) { if (lock2_end >= lock1.offset() || lock2_end == 0) { return true; } } if (lock2_end == 0) { if (lock1_end >= lock2.offset() || lock1_end == 0) { return true; } } // Overlapping? if (!(lock1_end < lock2.offset() || lock1.offset() > lock2_end)) { // Does overlap, check for conflicting modes. return lock1.exclusive() || lock2.exclusive(); } return false; } bool CheckIfUnsignedInteger(const std::string& string) { if (string.empty()) { return false; } try { // It's needed to use a 64 bit signed integer to detect a -(2^31)-1 // as a negative value and not as an overflowed unsigned integer of // value 2^32-1. int64_t integer = boost::lexical_cast<int64_t>(string); // If casted to uint, no bad_lexical_cast is thrown for negative values - // therefore we check for them on our own. if (integer < 0) { return false; } } catch(const boost::bad_lexical_cast&) { return false; } return true; // It actually was an unsigned integer. } RPCOptions RPCOptionsFromOptions(const Options& options) { return RPCOptions(options.max_tries, options.retry_delay_s, false, // do not delay last attempt options.was_interrupted_function); } #ifdef __APPLE__ int GetMacOSXKernelVersion() { int darwin_kernel_version = -1; struct utsname uname_result; uname(&uname_result); string darwin_release(uname_result.release); size_t first_dot = darwin_release.find_first_of("."); try { darwin_kernel_version = boost::lexical_cast<int>( darwin_release.substr(0, first_dot)); } catch(const boost::bad_lexical_cast& e) { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "Failed to retrieve the kernel " "version, got: " << darwin_kernel_version << endl; } } return darwin_kernel_version; } #endif // __APPLE__ #ifdef WIN32 std::string ConvertWindowsToUTF8(const wchar_t* windows_string) { string utf8; ConvertWindowsToUTF8(windows_string, &utf8); return utf8; } void ConvertWindowsToUTF8(const wchar_t* from, std::string* utf8) { // Assume that most strings will fit into a kDefaultBufferSize sized buffer. // If not, the buffer will be increased. const size_t kDefaultBufferSize = 1024; // resize() does not count the null-terminating char, WideCharTo... does. utf8->resize(kDefaultBufferSize - 1); int r = WideCharToMultiByte(CP_UTF8, 0, from, -1, &((*utf8)[0]), kDefaultBufferSize, 0, 0); if (r == 0) { throw XtreemFSException("Failed to convert a UTF-16" " (wide character) string to an UTF8 string." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } utf8->resize(r - 1); if (r > kDefaultBufferSize) { int r2 = WideCharToMultiByte(CP_UTF8, 0, from, -1, &((*utf8)[0]), r, 0, 0); if (r != r2 || r2 == 0) { throw XtreemFSException("Failed to convert a UTF-16" " (wide character) string to an UTF8 string." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } } void ConvertUTF8ToWindows(const std::string& utf8, wchar_t* buf, int buffer_size) { int r = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, buffer_size); if (r == 0) { throw XtreemFSException("Failed to convert this UTF8 string to a UTF-16" " (wide character) string: " + utf8 + " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } std::wstring ConvertUTF8ToWindows(const std::string& utf8) { wstring win; ConvertUTF8ToWindows(utf8, &win); return win; } void ConvertUTF8ToWindows(const std::string& utf8, std::wstring* win) { // Assume that most strings will fit into a kDefaultBufferSize sized buffer. // If not, the buffer will be increased. const size_t kDefaultBufferSize = 1024; // resize() does not count the null-terminating char, MultiByteToWide... does. win->resize(kDefaultBufferSize - 1); int r = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &((*win)[0]), kDefaultBufferSize); if (r == 0) { throw XtreemFSException("Failed to convert a UTF-8" " string to an UTF16 string (wide character)." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } win->resize(r - 1); if (r > kDefaultBufferSize) { int r2 = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &((*win)[0]), r); if (r != r2 || r2 == 0) { throw XtreemFSException("Failed to convert a UTF-8" " string to an UTF16 string (wide character)." " Error code: " + boost::lexical_cast<string>(::GetLastError())); } } } #endif // WIN32 } // namespace xtreemfs <|endoftext|>
<commit_before>/* * generate-license.c * * Created on: Apr 13, 2014 * */ #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <sstream> #include <fstream> #include <iostream> #include <licensecc_properties_test.h> #include "../../src/library/base/base.h" #include "../../src/library/ini/SimpleIni.h" #include "generate-license.h" namespace fs = boost::filesystem; using namespace std; namespace license { namespace test { string generate_license(const string& license_name, const vector<string>& other_args) { fs::path lcc_exe(LCC_EXE); BOOST_REQUIRE_MESSAGE(fs::is_regular_file(lcc_exe), "License generator not found: " LCC_EXE); fs::path licenses_base(LCC_LICENSES_BASE); if (!fs::exists(licenses_base)) { BOOST_REQUIRE_MESSAGE(fs::create_directories(licenses_base), "test folders created " + licenses_base.string()); } const string license_name_norm = boost::ends_with(license_name, ".lic") ? license_name : (license_name + ".lic"); const fs::path license_fname(licenses_base / license_name_norm); const string license_fname_s = license_fname.string(); remove(license_fname_s.c_str()); stringstream ss; ss << LCC_EXE << " license issue"; ss << " --" PARAM_PRIMARY_KEY " " << LCC_PROJECT_PRIVATE_KEY; ss << " --" PARAM_LICENSE_OUTPUT " " << license_fname_s; ss << " --" PARAM_PROJECT_FOLDER " " << LCC_TEST_LICENSES_PROJECT; for (int i = 0; i < other_args.size(); i++) { ss << " " << other_args[i]; } cout << "executing :" << ss.str() << endl; const int retCode = std::system(ss.str().c_str()); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(license_fname)); CSimpleIniA ini; const SI_Error rc = ini.LoadFile(license_fname.c_str()); BOOST_CHECK_GE(rc, 0); const int sectionSize = ini.GetSectionSize("DEFAULT"); BOOST_CHECK_GT(sectionSize, 0); return license_fname.string(); } string sign_data(const string& data, const string& test_name) { fs::path lcc_exe(LCC_EXE); BOOST_REQUIRE_MESSAGE(fs::is_regular_file(lcc_exe), "License generator not found: " LCC_EXE); fs::path licenses_base(LCC_LICENSES_BASE); if (!fs::exists(licenses_base)) { BOOST_REQUIRE_MESSAGE(fs::create_directories(licenses_base), "test folders created " + licenses_base.string()); } const fs::path outputFile(fs::path(PROJECT_TEST_TEMP_DIR) / (test_name + ".tmp")); const string output_file_s = outputFile.string(); remove(output_file_s.c_str()); stringstream ss; ss << LCC_EXE << " test sign"; ss << " --" PARAM_PRIMARY_KEY " " << LCC_PROJECT_PRIVATE_KEY; ss << " -d " << data; ss << " -o " << output_file_s; cout << "executing :" << ss.str() << endl; const int retCode = std::system(ss.str().c_str()); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(outputFile)); std::ifstream ifs(output_file_s.c_str()); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return content; } } // namespace test } // namespace license <commit_msg>issue #77<commit_after>/* * generate-license.c * * Created on: Apr 13, 2014 * */ #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <sstream> #include <fstream> #include <iostream> #include <licensecc_properties_test.h> #include <licensecc_properties.h> #include "../../src/library/base/base.h" #include "../../src/library/ini/SimpleIni.h" #include "generate-license.h" namespace fs = boost::filesystem; using namespace std; namespace license { namespace test { string generate_license(const string& license_name, const vector<string>& other_args) { fs::path lcc_exe(LCC_EXE); BOOST_REQUIRE_MESSAGE(fs::is_regular_file(lcc_exe), "License generator not found: " LCC_EXE); fs::path licenses_base(LCC_LICENSES_BASE); if (!fs::exists(licenses_base)) { BOOST_REQUIRE_MESSAGE(fs::create_directories(licenses_base), "test folders created " + licenses_base.string()); } const string license_name_norm = boost::ends_with(license_name, ".lic") ? license_name : (license_name + ".lic"); const fs::path license_fname(licenses_base / license_name_norm); const string license_fname_s = license_fname.string(); remove(license_fname_s.c_str()); stringstream ss; ss << LCC_EXE << " license issue"; ss << " --" PARAM_PRIMARY_KEY " " << LCC_PROJECT_PRIVATE_KEY; ss << " --" PARAM_LICENSE_OUTPUT " " << license_fname_s; ss << " --" PARAM_PROJECT_FOLDER " " << LCC_TEST_LICENSES_PROJECT; for (int i = 0; i < other_args.size(); i++) { ss << " " << other_args[i]; } cout << "executing :" << ss.str() << endl; const int retCode = std::system(ss.str().c_str()); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(license_fname)); CSimpleIniA ini; const SI_Error rc = ini.LoadFile(license_fname.c_str()); BOOST_CHECK_GE(rc, 0); const int sectionSize = ini.GetSectionSize(LCC_PROJECT_NAME); BOOST_CHECK_GT(sectionSize, 0); return license_fname.string(); } string sign_data(const string& data, const string& test_name) { fs::path lcc_exe(LCC_EXE); BOOST_REQUIRE_MESSAGE(fs::is_regular_file(lcc_exe), "License generator not found: " LCC_EXE); fs::path licenses_base(LCC_LICENSES_BASE); if (!fs::exists(licenses_base)) { BOOST_REQUIRE_MESSAGE(fs::create_directories(licenses_base), "test folders created " + licenses_base.string()); } const fs::path outputFile(fs::path(PROJECT_TEST_TEMP_DIR) / (test_name + ".tmp")); const string output_file_s = outputFile.string(); remove(output_file_s.c_str()); stringstream ss; ss << LCC_EXE << " test sign"; ss << " --" PARAM_PRIMARY_KEY " " << LCC_PROJECT_PRIVATE_KEY; ss << " -d " << data; ss << " -o " << output_file_s; cout << "executing :" << ss.str() << endl; const int retCode = std::system(ss.str().c_str()); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(outputFile)); std::ifstream ifs(output_file_s.c_str()); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return content; } } // namespace test } // namespace license <|endoftext|>
<commit_before>#include "LIBSPU.H" #include "LIBETC.H" #include <stdio.h> #include "EMULATOR.H" #include "LIBAPI.H" #include <string.h> #define SPU_CENTERNOTE (-32768 / 2) short _spu_voice_centerNote[24] = { SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE }; SpuCommonAttr dword_424;//Might be wrong struct, need to check int _spu_isCalled = 0; int _spu_FiDMA = 0;///@TODO decl as extern find initial value int _spu_EVdma = 0; int _spu_rev_flag = 0; int _spu_rev_reserve_wa = 0; int _spu_rev_offsetaddr = 0; int _spu_rev_startaddr = 0; int _spu_AllocBlockNum = 0; int _spu_AllocLastNum = 0; int _spu_memList = 0; int _spu_trans_mode = 0; int _spu_transMode = 0; int _spu_keystat = 0; int _spu_RQmask = 0; int _spu_RQvoice = 0; int _spu_env = 0; char spu[440];//0x1F801C00 is base address short* _spu_RXX = (short*)&spu[0]; int _spu_mem_mode_plus = 3; void* _spu_transferCallback = NULL;///@TODO initial value check int _spu_inTransfer = 0;///@TODO initial value check unsigned short _spu_tsa = 0; void SpuGetAllKeysStatus(char* status) { UNIMPLEMENTED(); } void SpuSetKeyOnWithAttr(SpuVoiceAttr* attr) { UNIMPLEMENTED(); } long SpuGetKeyStatus(unsigned long voice_bit) { int a1 = -1; //loc_210 for (int i = 0; i < 24; i++) { int v0 = 1 << i; if ((voice_bit & (1 << i))) { //loc_240 if (i != -1) { //loc_248 if ((_spu_keystat & (1 << i)) == 0) { return (0 < (unsigned short)_spu_RXX[i << 3]) << 1; } else { if ((unsigned short)_spu_RXX[i << 3] == 0) { return 3; } else { return 1; } } } else { return -1; } } } if (a1 != -1) { //loc_248 if ((_spu_keystat & (1 << a1)) == 0) { return (0 < (unsigned short)_spu_RXX[a1 << 3]) << 1; } else { if ((unsigned short)_spu_RXX[a1 << 3] == 0) { return 3; } else { return 1; } } } else { return -1; } return 0; } void _spu_t(int mode, int flag) { UNIMPLEMENTED(); } void _spu_Fw(unsigned char* addr, unsigned long size) { //v0 = _spu_transMode //s1 = addr //s0 = size if (_spu_trans_mode == 0) { //v0 = _spu_tsa //a1 = _spu_mem_mode_plus //a0 = 2 _spu_t(2, _spu_tsa << _spu_mem_mode_plus); ///@TODO check if a1 is modified in spu_t } //loc_A84 #if 0 jal _spu_t sllv $a1, $v0, $a1 jal _spu_t li $a0, 1 li $a0, 3 move $a1, $s1 jal _spu_t move $a2, $s0 j loc_A94 move $v0, $s0 loc_A84: move $a0, $s1 jal sub_480 move $a1, $s0 move $v0, $s0 loc_A94: lw $ra, 0x20+var_8($sp) lw $s1, 0x20+var_C($sp) lw $s0, 0x20+var_10($sp) jr $ra addiu $sp, 0x20 # End of function _spu_Fw #endif } unsigned long SpuWrite(unsigned char* addr, unsigned long size) { if (0x7EFF0 < size) { size = 0x7EFF0; } //loc_228 _spu_Fw(addr, size); if (_spu_transferCallback == NULL) { _spu_inTransfer = 0; } return size; } long SpuSetTransferMode(long mode) { long mode_fix = mode == 0 ? 0 : 1; //trans_mode = mode; //transMode = mode_fix; return mode_fix; } unsigned long SpuSetTransferStartAddr(unsigned long addr) { UNIMPLEMENTED(); return 0; } long SpuIsTransferCompleted(long flag) { UNIMPLEMENTED(); return 0; } void _SpuDataCallback(int a0) { UNIMPLEMENTED(); } void SpuStart()//(F) { long event = 0; if (_spu_isCalled == 0) { _spu_isCalled = 1; EnterCriticalSection(); _SpuDataCallback(_spu_FiDMA); //event = OpenEvent(HwSPU, EvSpCOMP, EvMdNOINTR, NULL); _spu_EVdma = event; EnableEvent(event); ExitCriticalSection(); } //loc_348 } void _spu_init(int a0) { UNIMPLEMENTED(); } void _spu_FsetRXX(int a0, int a1, int a2)//(F) { if (a2 == 0) { _spu_RXX[a0] = a1; } else { _spu_RXX[a0] = a1 >> _spu_mem_mode_plus; } } void _SpuInit(int a0) { ResetCallback(); _spu_init(a0); if (a0 == 0) { for (int i = 0; i < sizeof(_spu_voice_centerNote) / sizeof(short); i++) { _spu_voice_centerNote[i] = SPU_CENTERNOTE; } } //loc_240 SpuStart(); _spu_rev_flag = 0; _spu_rev_reserve_wa = 0; dword_424.mask = 0; dword_424.mvol.left = 0; dword_424.mvol.right = 0; dword_424.mvolmode.left = 0; dword_424.mvolmode.right = 0; dword_424.mvolx.left = 0; dword_424.mvolx.right = 0; _spu_rev_offsetaddr = _spu_rev_startaddr; _spu_FsetRXX(209, _spu_rev_startaddr, 0); _spu_AllocBlockNum = 0; _spu_AllocLastNum = 0; _spu_memList = 0; _spu_trans_mode = 0; _spu_transMode = 0; _spu_keystat = 0; _spu_RQmask = 0; _spu_RQvoice = 0; _spu_env = 0; } void SpuInit(void) { _SpuInit(0); } long SpuSetMute(long on_off) { UNIMPLEMENTED(); return 0; } long SpuSetReverb(long on_off) { UNIMPLEMENTED(); return 0; } unsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit) { UNIMPLEMENTED(); return 0; } void SpuSetCommonAttr(SpuCommonAttr* attr) { UNIMPLEMENTED(); } long SpuInitMalloc(long num, char* top)//(F) { if (num > 0) { //loc_214 ((int*)top)[0] = 0x40001010; _spu_memList = (uintptr_t)top; _spu_AllocLastNum = 0; _spu_AllocBlockNum = num; ((int*)top)[1] = (0x10000000 << _spu_mem_mode_plus) - 0x1010; } return num; } long SpuMalloc(long size) { return 0/*(long)(uintptr_t)malloc(size)*/; } long SpuMallocWithStartAddr(unsigned long addr, long size) { UNIMPLEMENTED(); return 0; } void SpuFree(unsigned long addr) { /*free((void*)(uintptr_t)addr)*/; } void SpuSetCommonMasterVolume(short mvol_left, short mvol_right)// (F) { //MasterVolume.VolumeLeft.Raw = mvol_left; //MasterVolume.VolumeRight.Raw = mvol_right; } long SpuSetReverbModeType(long mode) { UNIMPLEMENTED(); return 0; } void SpuSetReverbModeDepth(short depth_left, short depth_right) { UNIMPLEMENTED(); } <commit_msg>[Emu]: Implement SpuGetAllKeysStatus.<commit_after>#include "LIBSPU.H" #include "LIBETC.H" #include <stdio.h> #include "EMULATOR.H" #include "LIBAPI.H" #include <string.h> #define SPU_CENTERNOTE (-32768 / 2) short _spu_voice_centerNote[24] = { SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE, SPU_CENTERNOTE }; SpuCommonAttr dword_424;//Might be wrong struct, need to check int _spu_isCalled = 0; int _spu_FiDMA = 0;///@TODO decl as extern find initial value int _spu_EVdma = 0; int _spu_rev_flag = 0; int _spu_rev_reserve_wa = 0; int _spu_rev_offsetaddr = 0; int _spu_rev_startaddr = 0; int _spu_AllocBlockNum = 0; int _spu_AllocLastNum = 0; int _spu_memList = 0; int _spu_trans_mode = 0; int _spu_transMode = 0; int _spu_keystat = 0; int _spu_RQmask = 0; int _spu_RQvoice = 0; int _spu_env = 0; char spu[440];//0x1F801C00 is base address short* _spu_RXX = (short*)&spu[0]; int _spu_mem_mode_plus = 3; void* _spu_transferCallback = NULL;///@TODO initial value check int _spu_inTransfer = 0;///@TODO initial value check unsigned short _spu_tsa = 0; void SpuGetAllKeysStatus(char* status) { //loc_2EC for (int i = 0; i < 24; i++, status++) { if ((_spu_keystat & (1 << i))) { if ((unsigned short)_spu_RXX[i << 3 + 6] != 0) { *status = 1; } else { *status = 3; } } else { //loc_330 if ((unsigned short)_spu_RXX[i << 3 + 6] != 0) { *status = 2; } else { //loc_340 *status = 0; } } } } void SpuSetKeyOnWithAttr(SpuVoiceAttr* attr) { UNIMPLEMENTED(); } long SpuGetKeyStatus(unsigned long voice_bit) { int a1 = -1; //loc_210 for (int i = 0; i < 24; i++) { int v0 = 1 << i; if ((voice_bit & (1 << i))) { //loc_240 if (i != -1) { //loc_248 if ((_spu_keystat & (1 << i)) == 0) { return (0 < (unsigned short)_spu_RXX[i << 3 + 6]) << 1; } else { if ((unsigned short)_spu_RXX[i << 3 + 6] == 0) { return 3; } else { return 1; } } } else { return -1; } } } if (a1 != -1) { //loc_248 if ((_spu_keystat & (1 << a1)) == 0) { return (0 < (unsigned short)_spu_RXX[a1 << 3]) << 1; } else { if ((unsigned short)_spu_RXX[a1 << 3] == 0) { return 3; } else { return 1; } } } else { return -1; } return 0; } void _spu_t(int mode, int flag) { UNIMPLEMENTED(); } void _spu_Fw(unsigned char* addr, unsigned long size) { //v0 = _spu_transMode //s1 = addr //s0 = size if (_spu_trans_mode == 0) { //v0 = _spu_tsa //a1 = _spu_mem_mode_plus //a0 = 2 _spu_t(2, _spu_tsa << _spu_mem_mode_plus); ///@TODO check if a1 is modified in spu_t } //loc_A84 #if 0 jal _spu_t sllv $a1, $v0, $a1 jal _spu_t li $a0, 1 li $a0, 3 move $a1, $s1 jal _spu_t move $a2, $s0 j loc_A94 move $v0, $s0 loc_A84: move $a0, $s1 jal sub_480 move $a1, $s0 move $v0, $s0 loc_A94: lw $ra, 0x20+var_8($sp) lw $s1, 0x20+var_C($sp) lw $s0, 0x20+var_10($sp) jr $ra addiu $sp, 0x20 # End of function _spu_Fw #endif } unsigned long SpuWrite(unsigned char* addr, unsigned long size) { if (0x7EFF0 < size) { size = 0x7EFF0; } //loc_228 _spu_Fw(addr, size); if (_spu_transferCallback == NULL) { _spu_inTransfer = 0; } return size; } long SpuSetTransferMode(long mode) { long mode_fix = mode == 0 ? 0 : 1; //trans_mode = mode; //transMode = mode_fix; return mode_fix; } unsigned long SpuSetTransferStartAddr(unsigned long addr) { UNIMPLEMENTED(); return 0; } long SpuIsTransferCompleted(long flag) { UNIMPLEMENTED(); return 0; } void _SpuDataCallback(int a0) { UNIMPLEMENTED(); } void SpuStart()//(F) { long event = 0; if (_spu_isCalled == 0) { _spu_isCalled = 1; EnterCriticalSection(); _SpuDataCallback(_spu_FiDMA); //event = OpenEvent(HwSPU, EvSpCOMP, EvMdNOINTR, NULL); _spu_EVdma = event; EnableEvent(event); ExitCriticalSection(); } //loc_348 } void _spu_init(int a0) { UNIMPLEMENTED(); } void _spu_FsetRXX(int a0, int a1, int a2)//(F) { if (a2 == 0) { _spu_RXX[a0] = a1; } else { _spu_RXX[a0] = a1 >> _spu_mem_mode_plus; } } void _SpuInit(int a0) { ResetCallback(); _spu_init(a0); if (a0 == 0) { for (int i = 0; i < sizeof(_spu_voice_centerNote) / sizeof(short); i++) { _spu_voice_centerNote[i] = SPU_CENTERNOTE; } } //loc_240 SpuStart(); _spu_rev_flag = 0; _spu_rev_reserve_wa = 0; dword_424.mask = 0; dword_424.mvol.left = 0; dword_424.mvol.right = 0; dword_424.mvolmode.left = 0; dword_424.mvolmode.right = 0; dword_424.mvolx.left = 0; dword_424.mvolx.right = 0; _spu_rev_offsetaddr = _spu_rev_startaddr; _spu_FsetRXX(209, _spu_rev_startaddr, 0); _spu_AllocBlockNum = 0; _spu_AllocLastNum = 0; _spu_memList = 0; _spu_trans_mode = 0; _spu_transMode = 0; _spu_keystat = 0; _spu_RQmask = 0; _spu_RQvoice = 0; _spu_env = 0; } void SpuInit(void) { _SpuInit(0); } long SpuSetMute(long on_off) { UNIMPLEMENTED(); return 0; } long SpuSetReverb(long on_off) { UNIMPLEMENTED(); return 0; } unsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit) { UNIMPLEMENTED(); return 0; } void SpuSetCommonAttr(SpuCommonAttr* attr) { UNIMPLEMENTED(); } long SpuInitMalloc(long num, char* top)//(F) { if (num > 0) { //loc_214 ((int*)top)[0] = 0x40001010; _spu_memList = (uintptr_t)top; _spu_AllocLastNum = 0; _spu_AllocBlockNum = num; ((int*)top)[1] = (0x10000000 << _spu_mem_mode_plus) - 0x1010; } return num; } long SpuMalloc(long size) { return 0/*(long)(uintptr_t)malloc(size)*/; } long SpuMallocWithStartAddr(unsigned long addr, long size) { UNIMPLEMENTED(); return 0; } void SpuFree(unsigned long addr) { /*free((void*)(uintptr_t)addr)*/; } void SpuSetCommonMasterVolume(short mvol_left, short mvol_right)// (F) { //MasterVolume.VolumeLeft.Raw = mvol_left; //MasterVolume.VolumeRight.Raw = mvol_right; } long SpuSetReverbModeType(long mode) { UNIMPLEMENTED(); return 0; } void SpuSetReverbModeDepth(short depth_left, short depth_right) { UNIMPLEMENTED(); } <|endoftext|>
<commit_before>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef ENABLE_INTEGRATION_TESTS #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> #include "base/fscapi.h" #include "base/Log.h" #include "base/adapter/PlatformAdapter.h" #include "base/util/XMLProcessor.h" #include "syncml/core/TagNames.h" #include "SyncManagerTest.h" #include "ManyItemsTestSyncSource.h" USE_NAMESPACE #define MIN_SYNCML_MSG_SIZE 5000 // in Byte. Smaller than 5k can be unacceptable for Server. #define NUM_CALENDAR_ITEMS 50 // A high number is requested, to force multimessage. /** * Parses a syncML message, and returns its Message ID (integer value). */ static int getMsgID(const StringBuffer& syncMLmsg) { char* value = XMLProcessor::copyElementContent(syncMLmsg.c_str(), MSG_ID, NULL); CPPUNIT_ASSERT(value); CPPUNIT_ASSERT(strlen(value)); int msgID = atoi(value); delete [] value; return msgID; } /** * Generates and returns a default configuration, with ssources contacts and calendar */ static SyncManagerConfig* getConfiguration(const char* name) { PlatformAdapter::init(name, true); SyncManagerConfig* config = new SyncManagerConfig(); config->setClientDefaults(); config->setSourceDefaults("contact"); config->setSourceDefaults("calendar"); // Can be removed once vCal is the default format... SyncSourceConfig* ssc = config->getSyncSourceConfig("calendar"); ssc->setType("text/x-vcalendar"); ssc->setEncoding("bin"); ssc->setVersion("1.0"); ssc->setURI("event"); //set custom configuration StringBuffer devID("sc-pim-"); devID += name; config->getDeviceConfig().setDevID(devID.c_str()); const char *serverUrl = getenv("CLIENT_TEST_SERVER_URL"); const char *username = getenv("CLIENT_TEST_USERNAME"); const char *password = getenv("CLIENT_TEST_PASSWORD"); if(serverUrl) { config->getAccessConfig().setSyncURL(serverUrl); } if(username) { config->getAccessConfig().setUsername(username); } if(password) { config->getAccessConfig().setPassword(password); } return config; } void SyncManagerTest::testServerError506() { LOG.setLevel(LOG_LEVEL_DEBUG); SyncManagerConfig* config = getConfiguration("testServerError506"); // Must use 2 syncsources: contact (no items) + calendar (many items: 50) // so that the last source has to send items in multimessage, first // won't have the Final tag. SyncSourceConfig* ssc = config->getSyncSourceConfig("contact"); ManyItemsTestSyncSource ssContact(TEXT("contact"), ssc, 0); ssc = config->getSyncSourceConfig("calendar"); ManyItemsTestSyncSource ssCalendar(TEXT("calendar"), ssc, NUM_CALENDAR_ITEMS); ssc->setSync("refresh-from-client"); // optional SyncSource* sources[3]; sources[0] = &ssContact; sources[1] = &ssCalendar; sources[2] = NULL; // Use a test transportAgent, to modify the 2nd message from the Server. // Set a low msg size, so that the calendar items are split at least in 2 syncML msg. // Note: the TransportAgent will be destroyed by the SyncManager. URL url(config->getSyncURL()); Proxy proxy; TransportAgentTestError506* testTransportAgent = new TransportAgentTestError506(url, proxy, config->getResponseTimeout(), MIN_SYNCML_MSG_SIZE); SyncClient client; client.setTransportAgent(testTransportAgent); int ret = client.sync(*config, sources); StringBuffer report(""); client.getSyncReport()->toString(report); LOG.info("\n%s", report.c_str()); delete config; } void TransportAgentTestError506::beforeSendingMessage(StringBuffer& msgToSend) { if (!msgToSend) { return; } int msgID = getMsgID(msgToSend); int maxMsgID = NUM_CALENDAR_ITEMS + 2; CPPUNIT_ASSERT_MESSAGE("infinite loop in sync", (msgID < maxMsgID)); } void TransportAgentTestError506::afterReceivingResponse(StringBuffer& msgReceived) { if (!msgReceived) { return; } // Modify only the 3rd message int msgID = getMsgID(msgReceived); if (msgID != 3) { return; } unsigned int pos = 0, previous = 0; StringBuffer status; const char* msg = msgReceived.c_str(); XMLProcessor::copyElementContent(status, msg, STATUS, &pos); while ( !status.empty() ) { StringBuffer cmd; XMLProcessor::copyElementContent(cmd, status, CMD); if (cmd == SYNC) { // // It's the status of Sync command: replace the <Data> with a "506" // unsigned int dataPos=0, start=0, end=0; CPPUNIT_ASSERT(XMLProcessor::getElementContent(status, DATA, &dataPos, &start, &end)); StringBuffer data = status.substr(start, end-start); CPPUNIT_ASSERT(!data.empty()); dataPos = previous + start; // absolute position in full msg msgReceived.replace(data, "506", dataPos); return; } pos += previous; previous = pos; XMLProcessor::copyElementContent(status, &msg[pos], STATUS, &pos); } } #endif // ENABLE_INTEGRATION_TESTS <commit_msg>removed unused variable<commit_after>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef ENABLE_INTEGRATION_TESTS #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> #include "base/fscapi.h" #include "base/Log.h" #include "base/adapter/PlatformAdapter.h" #include "base/util/XMLProcessor.h" #include "syncml/core/TagNames.h" #include "SyncManagerTest.h" #include "ManyItemsTestSyncSource.h" USE_NAMESPACE #define MIN_SYNCML_MSG_SIZE 5000 // in Byte. Smaller than 5k can be unacceptable for Server. #define NUM_CALENDAR_ITEMS 50 // A high number is requested, to force multimessage. /** * Parses a syncML message, and returns its Message ID (integer value). */ static int getMsgID(const StringBuffer& syncMLmsg) { char* value = XMLProcessor::copyElementContent(syncMLmsg.c_str(), MSG_ID, NULL); CPPUNIT_ASSERT(value); CPPUNIT_ASSERT(strlen(value)); int msgID = atoi(value); delete [] value; return msgID; } /** * Generates and returns a default configuration, with ssources contacts and calendar */ static SyncManagerConfig* getConfiguration(const char* name) { PlatformAdapter::init(name, true); SyncManagerConfig* config = new SyncManagerConfig(); config->setClientDefaults(); config->setSourceDefaults("contact"); config->setSourceDefaults("calendar"); // Can be removed once vCal is the default format... SyncSourceConfig* ssc = config->getSyncSourceConfig("calendar"); ssc->setType("text/x-vcalendar"); ssc->setEncoding("bin"); ssc->setVersion("1.0"); ssc->setURI("event"); //set custom configuration StringBuffer devID("sc-pim-"); devID += name; config->getDeviceConfig().setDevID(devID.c_str()); const char *serverUrl = getenv("CLIENT_TEST_SERVER_URL"); const char *username = getenv("CLIENT_TEST_USERNAME"); const char *password = getenv("CLIENT_TEST_PASSWORD"); if(serverUrl) { config->getAccessConfig().setSyncURL(serverUrl); } if(username) { config->getAccessConfig().setUsername(username); } if(password) { config->getAccessConfig().setPassword(password); } return config; } void SyncManagerTest::testServerError506() { LOG.setLevel(LOG_LEVEL_DEBUG); SyncManagerConfig* config = getConfiguration("testServerError506"); // Must use 2 syncsources: contact (no items) + calendar (many items: 50) // so that the last source has to send items in multimessage, first // won't have the Final tag. SyncSourceConfig* ssc = config->getSyncSourceConfig("contact"); ManyItemsTestSyncSource ssContact(TEXT("contact"), ssc, 0); ssc = config->getSyncSourceConfig("calendar"); ManyItemsTestSyncSource ssCalendar(TEXT("calendar"), ssc, NUM_CALENDAR_ITEMS); ssc->setSync("refresh-from-client"); // optional SyncSource* sources[3]; sources[0] = &ssContact; sources[1] = &ssCalendar; sources[2] = NULL; // Use a test transportAgent, to modify the 2nd message from the Server. // Set a low msg size, so that the calendar items are split at least in 2 syncML msg. // Note: the TransportAgent will be destroyed by the SyncManager. URL url(config->getSyncURL()); Proxy proxy; TransportAgentTestError506* testTransportAgent = new TransportAgentTestError506(url, proxy, config->getResponseTimeout(), MIN_SYNCML_MSG_SIZE); SyncClient client; client.setTransportAgent(testTransportAgent); client.sync(*config, sources); StringBuffer report(""); client.getSyncReport()->toString(report); LOG.info("\n%s", report.c_str()); delete config; } void TransportAgentTestError506::beforeSendingMessage(StringBuffer& msgToSend) { if (!msgToSend) { return; } int msgID = getMsgID(msgToSend); int maxMsgID = NUM_CALENDAR_ITEMS + 2; CPPUNIT_ASSERT_MESSAGE("infinite loop in sync", (msgID < maxMsgID)); } void TransportAgentTestError506::afterReceivingResponse(StringBuffer& msgReceived) { if (!msgReceived) { return; } // Modify only the 3rd message int msgID = getMsgID(msgReceived); if (msgID != 3) { return; } unsigned int pos = 0, previous = 0; StringBuffer status; const char* msg = msgReceived.c_str(); XMLProcessor::copyElementContent(status, msg, STATUS, &pos); while ( !status.empty() ) { StringBuffer cmd; XMLProcessor::copyElementContent(cmd, status, CMD); if (cmd == SYNC) { // // It's the status of Sync command: replace the <Data> with a "506" // unsigned int dataPos=0, start=0, end=0; CPPUNIT_ASSERT(XMLProcessor::getElementContent(status, DATA, &dataPos, &start, &end)); StringBuffer data = status.substr(start, end-start); CPPUNIT_ASSERT(!data.empty()); dataPos = previous + start; // absolute position in full msg msgReceived.replace(data, "506", dataPos); return; } pos += previous; previous = pos; XMLProcessor::copyElementContent(status, &msg[pos], STATUS, &pos); } } #endif // ENABLE_INTEGRATION_TESTS <|endoftext|>
<commit_before>/* * Copyright 2020 Google LLC * * 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 * * https://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 <filesystem> #include <fstream> #include "../src/proto_value.h" #include "../src/proto_parser.h" #include "proto/event_predicate.pb.h" using ::wireless_android_play_analytics::ProtoValue; using ::wireless_android_play_analytics::MessageValue; using ::wireless_android_play_analytics::PrimitiveValue; using ::wireless_android_play_analytics::EventPredicate; using ::wireless_android_play_analytics::ProtoParser; namespace { class EventPredicateConverter { public: std::unique_ptr<ProtoValue> ConvertEventPredicateFromFile( absl::string_view path) { ProtoParser parser(ReadTextProtoFromStream(path)); EventPredicate event_predicate_prototype; std::unique_ptr<ProtoValue> and_field = absl::make_unique<MessageValue>("and", 0, 0); MessageValue* and_field_ptr = static_cast<MessageValue*>(and_field.get()); std::unique_ptr<ProtoValue> event_predicate = parser.Create(event_predicate_prototype); MessageValue* event_predicate_ptr = static_cast<MessageValue*>(event_predicate.get()); const std::vector<std::unique_ptr<ProtoValue>>& fields = event_predicate_ptr->GetFields(); for (const std::unique_ptr<ProtoValue>& field : fields) { if (field.get()->GetName() == "event_matcher") { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(*field.get()); if (name_to_ptr_map.find("int_comparator") == name_to_ptr_map.end()) { and_field_ptr->AddField(EventMatcherToFieldExists(*field.get())); } else { and_field_ptr->AddField(EventMatcherToFieldValue(*field.get())); } } else if (field.get()->GetName() == "ui_element_path_predicate") { and_field_ptr->AddField(UiElementPathPredicateToUiElement(*field.get())); } } return and_field; } private: // Reads text proto into a string from a file. std::string ReadTextProtoFromStream(absl::string_view path) { std::ifstream ifs; std::string text_proto; ifs.open(std::string(path)); assert(ifs.good()); while (ifs.good()) { std::string tmp; std::getline(ifs, tmp); text_proto += tmp + "\n"; } return text_proto; } // Copies the comments of an original proto value to a copy, if they're both // primitive types also copy the value. void CopyVal(ProtoValue* copy, const ProtoValue& original) { copy->SetCommentBehindField(original.GetCommentBehindField()); copy->SetCommentAboveField(original.GetCommentAboveField()); PrimitiveValue* copy_val = dynamic_cast<PrimitiveValue*>(copy); const PrimitiveValue* original_val = dynamic_cast<const PrimitiveValue*>( &original); if (copy_val != nullptr && original_val != nullptr) { // Copy their values only if they are both primitive values. copy_val->SetVal(original_val->GetVal()); } } // Gets a hash table that maps field names of a message value to their // corresponding protovalue pointer. absl::flat_hash_map<std::string, ProtoValue*> GetFieldNameToPtrMap( const ProtoValue& original) { const MessageValue* original_ptr = static_cast<const MessageValue*>(&original); absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map; const std::vector<std::unique_ptr<ProtoValue>>& fields = original_ptr->GetFields(); for (const std::unique_ptr<ProtoValue>& field : fields) { name_to_ptr_map[field.get()->GetName()] = field.get(); } return name_to_ptr_map; } // A universal converter for message matcher into either index_ui, // field_value, or field_exists. std::unique_ptr<ProtoValue> MessageMatcherUniversalConverter( const ProtoValue& original, absl::string_view name, const ProtoValue* index = nullptr) { std::unique_ptr<ProtoValue> constructed_field = nullptr; // Get the name of each field on the original proto. absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); if (name == "index_ui" || name == "field_value" || name == "leaf_ui") { constructed_field = absl::make_unique<MessageValue>(name, original.GetIndentCount() + 1, 0); MessageValue* constructed_field_ptr = static_cast<MessageValue*>( constructed_field.get()); if (name == "index_ui") { // Index UI has an extra field of index. std::unique_ptr<ProtoValue> index_field = absl::make_unique<PrimitiveValue>("index", original.GetIndentCount() + 2, 0); CopyVal(index_field.get(), *index); constructed_field_ptr->AddField(std::move(index_field)); } std::unique_ptr<ProtoValue> path = absl::make_unique<PrimitiveValue>( "path", original.GetIndentCount() + 2, 1); CopyVal(path.get(), *name_to_ptr_map["input_field"]); std::unique_ptr<ProtoValue> equals_int = absl::make_unique<PrimitiveValue>("equals_int", original.GetIndentCount() + 2, 2); CopyVal(equals_int.get(), *name_to_ptr_map["int_comparator"]); constructed_field_ptr->AddField(std::move(path)); constructed_field_ptr->AddField(std::move(equals_int)); } else { constructed_field = absl::make_unique<PrimitiveValue>(name, original.GetIndentCount() + 1, 0); PrimitiveValue* constructed_field_ptr = static_cast<PrimitiveValue*>( constructed_field.get()); PrimitiveValue* input_field_ptr = static_cast<PrimitiveValue*>( name_to_ptr_map["input_field"]); constructed_field_ptr->SetVal(input_field_ptr->GetVal()); } // Copy the comments of the original proto to the constructed field CopyVal(constructed_field.get(), original); return constructed_field; } std::unique_ptr<ProtoValue> LeafUiPredicateToLeafUi( const ProtoValue& original) { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); return MessageMatcherUniversalConverter( *name_to_ptr_map["ui_element_matcher"], "leaf_ui"); } std::unique_ptr<ProtoValue> IndexUiPredicateToIndexUi( const ProtoValue& original) { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); return MessageMatcherUniversalConverter( *name_to_ptr_map["ui_element_matcher"], "index_ui", name_to_ptr_map["index"]); } std::unique_ptr<ProtoValue> EventMatcherToFieldExists( const ProtoValue& original) { return MessageMatcherUniversalConverter(original, "field_exists"); } std::unique_ptr<ProtoValue> EventMatcherToFieldValue( const ProtoValue& original) { return MessageMatcherUniversalConverter(original, "field_value"); } std::unique_ptr<ProtoValue> UiElementPathPredicateToUiElement( const ProtoValue& original) { std::unique_ptr<ProtoValue> ui_element = absl::make_unique<MessageValue>( "ui_element", original.GetIndentCount() + 1, 0); MessageValue* ui_element_ptr = static_cast<MessageValue*>(ui_element.get()); CopyVal(ui_element.get(), original); absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); // Convert ui_element_type to type std::unique_ptr<ProtoValue> type = absl::make_unique<PrimitiveValue>( "type", name_to_ptr_map["ui_element_type"]->GetIndentCount() + 1, 0); CopyVal(type.get(), *name_to_ptr_map["ui_element_type"]); ui_element_ptr->AddField(std::move(type)); // Create nested predicate only if they exist. if (name_to_ptr_map.size() > 1) { std::unique_ptr<ProtoValue> and_field = absl::make_unique<MessageValue>( "and", original.GetIndentCount() + 2, 1); MessageValue* and_field_ptr = static_cast<MessageValue*>(and_field.get()); if (name_to_ptr_map.find("leaf_ui_predicate") != name_to_ptr_map.end()) { and_field_ptr->AddField(LeafUiPredicateToLeafUi( *name_to_ptr_map["leaf_ui_predicate"])); } if (name_to_ptr_map.find("index_ui_matcher") != name_to_ptr_map.end()) { and_field_ptr->AddField(IndexUiPredicateToIndexUi( *name_to_ptr_map["index_ui_matcher"])); } ui_element_ptr->AddField(std::move(and_field)); } return ui_element; } }; } // namespace int main() { EventPredicateConverter converter; std::unique_ptr<ProtoValue> output = converter.ConvertEventPredicateFromFile( "demo/proto_texts/original_proto_text.txt"); std::cout << output.get()->PrintToTextProto(); return 0; }<commit_msg>added comments to make the job of each function clearer<commit_after>/* * Copyright 2020 Google LLC * * 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 * * https://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 <filesystem> #include <fstream> #include "../src/proto_value.h" #include "../src/proto_parser.h" #include "proto/event_predicate.pb.h" using ::wireless_android_play_analytics::ProtoValue; using ::wireless_android_play_analytics::MessageValue; using ::wireless_android_play_analytics::PrimitiveValue; using ::wireless_android_play_analytics::EventPredicate; using ::wireless_android_play_analytics::ProtoParser; namespace { class EventPredicateConverter { public: // Original: // # comment // # to // # save // # Condition 1 // event_matcher { // input_field: "PlayExtension.store.click" // } // # Condition 2 // event_matcher { // input_field: "PlayExtension.log_source" // int_comparator: 65 # WEB_STORE // } // # Condition 3 // ui_element_path_predicate { // ui_element_type: STORE_UI_ELEMENT // # Condition 3.1 // leaf_ui_predicate { // # ... // ui_element_type: STORE_UI_ELEMENT // ui_element_matcher { // input_field: "type" // int_comparator: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } // } // # Condition 3.2 // index_ui_matcher { // ui_element_type: STORE_UI_ELEMENT // index: -2 // ui_element_matcher { // input_field: "type" // int_comparator: 1 # SOMETHING // } // } // } // Modified: // and { // # Condition 1 // field_exists: "PlayExtension.store.click" // # Condition 2 // field_value { // path: "PlayExtension.log_source" // equals_int: 65 # WEB_STORE // } // # Condition 3 // ui_element { // type: STORE_UI_ELEMENT // and { // # Condition 3.1 // leaf_ui { // path: "type" // equals_int: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } // # Condition 3.2 // index_ui { // index: -2 // path: "type" // equals_int: 1 # SOMETHING // } // } // } // } std::unique_ptr<ProtoValue> ConvertEventPredicateFromFile( absl::string_view path) { ProtoParser parser(ReadTextProtoFromStream(path)); EventPredicate event_predicate_prototype; std::unique_ptr<ProtoValue> and_field = absl::make_unique<MessageValue>("and", 0, 0); MessageValue* and_field_ptr = static_cast<MessageValue*>(and_field.get()); std::unique_ptr<ProtoValue> event_predicate = parser.Create(event_predicate_prototype); MessageValue* event_predicate_ptr = static_cast<MessageValue*>(event_predicate.get()); const std::vector<std::unique_ptr<ProtoValue>>& fields = event_predicate_ptr->GetFields(); for (const std::unique_ptr<ProtoValue>& field : fields) { if (field.get()->GetName() == "event_matcher") { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(*field.get()); if (name_to_ptr_map.find("int_comparator") == name_to_ptr_map.end()) { and_field_ptr->AddField(EventMatcherToFieldExists(*field.get())); } else { and_field_ptr->AddField(EventMatcherToFieldValue(*field.get())); } } else if (field.get()->GetName() == "ui_element_path_predicate") { and_field_ptr->AddField(UiElementPathPredicateToUiElement(*field.get())); } } return and_field; } private: // Reads text proto into a string from a file. std::string ReadTextProtoFromStream(absl::string_view path) { std::ifstream ifs; std::string text_proto; ifs.open(std::string(path)); assert(ifs.good()); while (ifs.good()) { std::string tmp; std::getline(ifs, tmp); text_proto += tmp + "\n"; } return text_proto; } // Copies the comments of an original proto value to a copy, if they're both // primitive types also copy the value. void CopyVal(ProtoValue* copy, const ProtoValue& original) { copy->SetCommentBehindField(original.GetCommentBehindField()); copy->SetCommentAboveField(original.GetCommentAboveField()); PrimitiveValue* copy_val = dynamic_cast<PrimitiveValue*>(copy); const PrimitiveValue* original_val = dynamic_cast<const PrimitiveValue*>( &original); if (copy_val != nullptr && original_val != nullptr) { // Copy their values only if they are both primitive values. copy_val->SetVal(original_val->GetVal()); } } // Gets a hash table that maps field names of a message value to their // corresponding protovalue pointer. absl::flat_hash_map<std::string, ProtoValue*> GetFieldNameToPtrMap( const ProtoValue& original) { const MessageValue* original_ptr = static_cast<const MessageValue*>(&original); absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map; const std::vector<std::unique_ptr<ProtoValue>>& fields = original_ptr->GetFields(); for (const std::unique_ptr<ProtoValue>& field : fields) { name_to_ptr_map[field.get()->GetName()] = field.get(); } return name_to_ptr_map; } // A universal converter for message matcher into either index_ui, // field_value, or field_exists. std::unique_ptr<ProtoValue> MessageMatcherUniversalConverter( const ProtoValue& original, absl::string_view name, const ProtoValue* index = nullptr) { std::unique_ptr<ProtoValue> constructed_field = nullptr; // Get the name of each field on the original proto. absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); if (name == "index_ui" || name == "field_value" || name == "leaf_ui") { constructed_field = absl::make_unique<MessageValue>(name, original.GetIndentCount() + 1, 0); MessageValue* constructed_field_ptr = static_cast<MessageValue*>( constructed_field.get()); if (name == "index_ui") { // Index UI has an extra field of index. std::unique_ptr<ProtoValue> index_field = absl::make_unique<PrimitiveValue>("index", original.GetIndentCount() + 2, 0); CopyVal(index_field.get(), *index); constructed_field_ptr->AddField(std::move(index_field)); } std::unique_ptr<ProtoValue> path = absl::make_unique<PrimitiveValue>( "path", original.GetIndentCount() + 2, 1); CopyVal(path.get(), *name_to_ptr_map["input_field"]); std::unique_ptr<ProtoValue> equals_int = absl::make_unique<PrimitiveValue>("equals_int", original.GetIndentCount() + 2, 2); CopyVal(equals_int.get(), *name_to_ptr_map["int_comparator"]); constructed_field_ptr->AddField(std::move(path)); constructed_field_ptr->AddField(std::move(equals_int)); } else { constructed_field = absl::make_unique<PrimitiveValue>(name, original.GetIndentCount() + 1, 0); PrimitiveValue* constructed_field_ptr = static_cast<PrimitiveValue*>( constructed_field.get()); PrimitiveValue* input_field_ptr = static_cast<PrimitiveValue*>( name_to_ptr_map["input_field"]); constructed_field_ptr->SetVal(input_field_ptr->GetVal()); } // Copy the comments of the original proto to the constructed field CopyVal(constructed_field.get(), original); return constructed_field; } // Original: // # Condition 3.1 // leaf_ui_predicate { // # ... // ui_element_type: STORE_UI_ELEMENT // ui_element_matcher { // input_field: "type" // int_comparator: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } // } // Modified: // # Condition 3.1 // leaf_ui { // path: "type" // equals_int: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } std::unique_ptr<ProtoValue> LeafUiPredicateToLeafUi( const ProtoValue& original) { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); return MessageMatcherUniversalConverter( *name_to_ptr_map["ui_element_matcher"], "leaf_ui"); } // Original: // # Condition 3.2 // index_ui_matcher { // ui_element_type: STORE_UI_ELEMENT // index: -2 // ui_element_matcher { // input_field: "type" // int_comparator: 1 # SOMETHING // } // } // Modified: // # Condition 3.2 // index_ui { // index: -2 // path: "type" // equals_int: 1 # SOMETHING // } std::unique_ptr<ProtoValue> IndexUiPredicateToIndexUi( const ProtoValue& original) { absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); return MessageMatcherUniversalConverter( *name_to_ptr_map["ui_element_matcher"], "index_ui", name_to_ptr_map["index"]); } // Original: // # Condition 1 // event_matcher { // input_field: "PlayExtension.store.click" // } // Modified: // # Condition 1 // field_exists: "PlayExtension.store.click" std::unique_ptr<ProtoValue> EventMatcherToFieldExists( const ProtoValue& original) { return MessageMatcherUniversalConverter(original, "field_exists"); } // Original: // # Condition 2 // event_matcher { // input_field: "PlayExtension.log_source" // int_comparator: 65 # WEB_STORE // } // Modified: // # Condition 2 // field_value { // path: "PlayExtension.log_source" // equals_int: 65 # WEB_STORE // } std::unique_ptr<ProtoValue> EventMatcherToFieldValue( const ProtoValue& original) { return MessageMatcherUniversalConverter(original, "field_value"); } // Original: // # Condition 3 // ui_element_path_predicate { // ui_element_type: STORE_UI_ELEMENT // # Condition 3.1 // leaf_ui_predicate { // # ... // ui_element_type: STORE_UI_ELEMENT // ui_element_matcher { // input_field: "type" // int_comparator: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } // } // # Condition 3.2 // index_ui_matcher { // ui_element_type: STORE_UI_ELEMENT // index: -2 // ui_element_matcher { // input_field: "type" // int_comparator: 1 # SOMETHING // } // } // } // Modified: // ui_element { // type: STORE_UI_ELEMENT // and { // # Condition 3.1 // leaf_ui { // path: "type" // equals_int: 7305 # AUTHENTICATION_OPT_OUT_CHECKED // } // # Condition 3.2 // index_ui { // index: -2 // path: "type" // equals_int: 1 # SOMETHING // } // } // } std::unique_ptr<ProtoValue> UiElementPathPredicateToUiElement( const ProtoValue& original) { std::unique_ptr<ProtoValue> ui_element = absl::make_unique<MessageValue>( "ui_element", original.GetIndentCount() + 1, 0); MessageValue* ui_element_ptr = static_cast<MessageValue*>(ui_element.get()); CopyVal(ui_element.get(), original); absl::flat_hash_map<std::string, ProtoValue*> name_to_ptr_map = GetFieldNameToPtrMap(original); // Convert ui_element_type to type std::unique_ptr<ProtoValue> type = absl::make_unique<PrimitiveValue>( "type", name_to_ptr_map["ui_element_type"]->GetIndentCount() + 1, 0); CopyVal(type.get(), *name_to_ptr_map["ui_element_type"]); ui_element_ptr->AddField(std::move(type)); // Create nested predicate only if they exist. if (name_to_ptr_map.size() > 1) { std::unique_ptr<ProtoValue> and_field = absl::make_unique<MessageValue>( "and", original.GetIndentCount() + 2, 1); MessageValue* and_field_ptr = static_cast<MessageValue*>(and_field.get()); if (name_to_ptr_map.find("leaf_ui_predicate") != name_to_ptr_map.end()) { and_field_ptr->AddField(LeafUiPredicateToLeafUi( *name_to_ptr_map["leaf_ui_predicate"])); } if (name_to_ptr_map.find("index_ui_matcher") != name_to_ptr_map.end()) { and_field_ptr->AddField(IndexUiPredicateToIndexUi( *name_to_ptr_map["index_ui_matcher"])); } ui_element_ptr->AddField(std::move(and_field)); } return ui_element; } }; } // namespace int main() { EventPredicateConverter converter; std::unique_ptr<ProtoValue> output = converter.ConvertEventPredicateFromFile( "demo/proto_texts/original_proto_text.txt"); std::cout << output.get()->PrintToTextProto(); return 0; }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // 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 LUA_PARSER_HPP #define LUA_PARSER_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <ResourceManager/ResourceData.hpp> #include <ResourceManager\Logger.hpp> #include <string> #include <list> #include <vector> #include <algorithm> extern "C" { #include <lua.h> #include <lauxlib.h> #include <lualib.h> } //////////////////////////////////////////////////////////// /// \brief LuaParser that takes in a path name, and returns a list<ResourceData>. /// The Parser will open the lua table specifying a resource pack, parse its /// contents and leaf resources or continue opening resources packs. /// //////////////////////////////////////////////////////////// namespace rm { typedef std::list<ResourceData> ResourceDataList; class LuaParser { public: //////////////////////////////////////////////////////////// /// \brief Parse resource pack from file and return resource data list /// /// \param path File path from which to load the resource pack /// //////////////////////////////////////////////////////////// static ResourceDataList parsePack(const std::string& path); private: //////////////////////////////////////////////////////////// /// \brief Parse individual resource pack from file and return resource data list /// /// \param path File path from which to load the individual resource pack /// //////////////////////////////////////////////////////////// static ResourceDataList leafPack(const std::string& path); //////////////////////////////////////////////////////////// /// \brief Parse current individual resource pack leaf and return resource data /// //////////////////////////////////////////////////////////// static ResourceData parseLeaf(); //////////////////////////////////////////////////////////// /// Member data //////////////////////////////////////////////////////////// static lua_State* m_luaState; // Reference to Lua state }; } // namespace rm #endif //LUA_PARSER_HPP /////////////////////////////////////////////////////////// /// \class LuaParser /// \ingroup /// rm::LuaParser is the class which handles loading in of useful data /// from resource packs. These resource packs are lua tables. Each /// lua table represents one resource pack and each pack is contained /// in it's own file. /// /// rm::LuaParser takes the topmost resource packs and evaluates it's /// data, it then performs a breadth-first search through the tree structure /// possibly specifed in the resource packs. As the parser finds resources /// in the packs it creates a resource data which contains the relevant data, /// this is then added to a list. Once the parser has discovered all the leafed /// nodes it returns the list of resource datas to rm::ResourceManager. /// /// Note that access to rm::LuaParser is intended to be restricted. Most /// of the usage of rm::LuaParser should be handled by rm::ResourceManager. ////////////////////////////////////////////////////////////<commit_msg>Fixed invalid include<commit_after>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // 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 LUA_PARSER_HPP #define LUA_PARSER_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <ResourceManager/ResourceData.hpp> #include <ResourceManager/Logger.hpp> #include <string> #include <list> #include <vector> #include <algorithm> extern "C" { #include <lua.h> #include <lauxlib.h> #include <lualib.h> } //////////////////////////////////////////////////////////// /// \brief LuaParser that takes in a path name, and returns a list<ResourceData>. /// The Parser will open the lua table specifying a resource pack, parse its /// contents and leaf resources or continue opening resources packs. /// //////////////////////////////////////////////////////////// namespace rm { typedef std::list<ResourceData> ResourceDataList; class LuaParser { public: //////////////////////////////////////////////////////////// /// \brief Parse resource pack from file and return resource data list /// /// \param path File path from which to load the resource pack /// //////////////////////////////////////////////////////////// static ResourceDataList parsePack(const std::string& path); private: //////////////////////////////////////////////////////////// /// \brief Parse individual resource pack from file and return resource data list /// /// \param path File path from which to load the individual resource pack /// //////////////////////////////////////////////////////////// static ResourceDataList leafPack(const std::string& path); //////////////////////////////////////////////////////////// /// \brief Parse current individual resource pack leaf and return resource data /// //////////////////////////////////////////////////////////// static ResourceData parseLeaf(); //////////////////////////////////////////////////////////// /// Member data //////////////////////////////////////////////////////////// static lua_State* m_luaState; // Reference to Lua state }; } // namespace rm #endif //LUA_PARSER_HPP /////////////////////////////////////////////////////////// /// \class LuaParser /// \ingroup /// rm::LuaParser is the class which handles loading in of useful data /// from resource packs. These resource packs are lua tables. Each /// lua table represents one resource pack and each pack is contained /// in it's own file. /// /// rm::LuaParser takes the topmost resource packs and evaluates it's /// data, it then performs a breadth-first search through the tree structure /// possibly specifed in the resource packs. As the parser finds resources /// in the packs it creates a resource data which contains the relevant data, /// this is then added to a list. Once the parser has discovered all the leafed /// nodes it returns the list of resource datas to rm::ResourceManager. /// /// Note that access to rm::LuaParser is intended to be restricted. Most /// of the usage of rm::LuaParser should be handled by rm::ResourceManager. ////////////////////////////////////////////////////////////<|endoftext|>
<commit_before>/**************************************************************************** urid.hpp - support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> 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 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 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 01222-1307 USA ****************************************************************************/ #ifndef LV2_URID_HPP #define LV2_URID_HPP #include <lv2/lv2plug.in/ns/ext/urid/urid.h> namespace LV2 { /** The URID Extension. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ #define LV2MM_EXTENSION (slug) \ LV2MM_MIXIN_CLASS $slug { \ LV2MM_MIXIN_DERIVED { #define LV2MM_EXTENSION_END }; }; LV2MM_MIXIN_CLASS URID { LV2MM_MIXIN_DERIVED { I() { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_URID__map] = &I<Derived>::handle_map_feature; hmap[LV2_URID__unmap] = &I<Derived>::handle_unmap_feature; } /** @internal */ static void handle_map_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->p_map = reinterpret_cast<LV2_URID_Map*>(data); fe->m_ok = true; } /** @internal */ static void handle_unmap_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->p_unmap = reinterpret_cast<LV2_URID_Unmap*> (data); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::URID] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** Get the URI for a previously mapped numeric ID. Returns NULL if @p urid is not yet mapped. Otherwise, the corresponding URI is returned in a canonical form. This MAY not be the exact same string that was originally passed to LV2_URID_Map::map(), but it MUST be an identical URI according to the URI syntax specification (RFC3986). A non-NULL return for a given @p urid will always be the same for the life of the plugin. Plugins that intend to perform string comparison on unmapped URIs SHOULD first canonicalise URI strings with a call to map_uri() followed by a call to unmap_uri(). @param urid The ID to be mapped back to the URI string. */ const char* unmap (LV2_URID urid) { return p_unmap->unmap (p_unmap->handle, urid); } /** Get the numeric ID of a URI. If the ID does not already exist, it will be created. This function is referentially transparent; any number of calls with the same arguments is guaranteed to return the same value over the life of a plugin instance. Note, however, that several URIs MAY resolve to the same ID if the host considers those URIs equivalent. This function is not necessarily very fast or RT-safe: plugins SHOULD cache any IDs they might need in performance critical situations. The return value 0 is reserved and indicates that an ID for that URI could not be created for whatever reason. However, hosts SHOULD NOT return 0 from this function in non-exceptional circumstances (i.e. the URI map SHOULD be dynamic). @param uri The URI to be mapped to an integer ID. */ LV2_URID map (const char* uri) { return p_map->map (p_map->handle, uri); } LV2_URID_Map *p_map; LV2_URID_Unmap *p_unmap; private: }; }; } #endif /* LV2_URID_HPP */ <commit_msg>Cleanup Test Code<commit_after>/**************************************************************************** urid.hpp - support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> 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 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 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 01222-1307 USA ****************************************************************************/ #ifndef LV2_URID_HPP #define LV2_URID_HPP #include <lv2/lv2plug.in/ns/ext/urid/urid.h> namespace LV2 { /** The URID Extension. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS URID { LV2MM_MIXIN_DERIVED { I() { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_URID__map] = &I<Derived>::handle_map_feature; hmap[LV2_URID__unmap] = &I<Derived>::handle_unmap_feature; } /** @internal */ static void handle_map_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->p_map = reinterpret_cast<LV2_URID_Map*>(data); fe->m_ok = true; } /** @internal */ static void handle_unmap_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->p_unmap = reinterpret_cast<LV2_URID_Unmap*> (data); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::URID] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** Get the URI for a previously mapped numeric ID. Returns NULL if @p urid is not yet mapped. Otherwise, the corresponding URI is returned in a canonical form. This MAY not be the exact same string that was originally passed to LV2_URID_Map::map(), but it MUST be an identical URI according to the URI syntax specification (RFC3986). A non-NULL return for a given @p urid will always be the same for the life of the plugin. Plugins that intend to perform string comparison on unmapped URIs SHOULD first canonicalise URI strings with a call to map_uri() followed by a call to unmap_uri(). @param urid The ID to be mapped back to the URI string. */ const char* unmap (LV2_URID urid) { return p_unmap->unmap (p_unmap->handle, urid); } /** Get the numeric ID of a URI. If the ID does not already exist, it will be created. This function is referentially transparent; any number of calls with the same arguments is guaranteed to return the same value over the life of a plugin instance. Note, however, that several URIs MAY resolve to the same ID if the host considers those URIs equivalent. This function is not necessarily very fast or RT-safe: plugins SHOULD cache any IDs they might need in performance critical situations. The return value 0 is reserved and indicates that an ID for that URI could not be created for whatever reason. However, hosts SHOULD NOT return 0 from this function in non-exceptional circumstances (i.e. the URI map SHOULD be dynamic). @param uri The URI to be mapped to an integer ID. */ LV2_URID map (const char* uri) { return p_map->map (p_map->handle, uri); } LV2_URID_Map *p_map; LV2_URID_Unmap *p_unmap; private: }; }; } #endif /* LV2_URID_HPP */ <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <boost/range/adaptor/transformed.hpp> class T : public ::testing::Test { public: virtual ~T(){} }; TEST_F(T, test1) { EXPECT_TRUE(true); } TEST(F, test2) { EXPECT_TRUE(true); } <commit_msg>fix style<commit_after>#include <boost/range/adaptor/transformed.hpp> #include <gtest/gtest.h> class T : public ::testing::Test { public: virtual ~T() { } }; TEST_F(T, test1) { EXPECT_TRUE(true); } TEST(F, test2) { EXPECT_TRUE(true); } <|endoftext|>
<commit_before>#include "ATypeEffect.h" ATypeEffect::ATypeEffect(CPlayer* follower) { for (int i = 0; i < 3;++i) mExplosion[i] = NNAnimation::Create(); wchar_t temp[256] = { 0 }; for (int i = 0; i < 40; i++) { wsprintf(temp, L"Sprite/FireSkill/%d.png", i); for (int j = 0; j < 3; ++j) mExplosion[j]->AddFrameNode(temp); } for (int i = 0; i < 3; ++i) mExplosion[i]->SetFrameTimeInSection(0.05f, 0, 39); mFollower = follower; mLifeTime = mExplosion[0]->GetPlayTime() * 3; mDirection = mFollower->GetPlayerRotation(); mDistance = 100.f; mIndex = 0; mExplosionTerm = 0.5f; mTimeCount = 0.f; SetPosition(mFollower->GetPlayerPosition().GetX() - 65.f, mFollower->GetPlayerPosition().GetY() - 40.f); mNextExplosionPoint.SetPoint(mDistance * std::cosf(mDirection), mDistance * std::sinf(mDirection)); for (int i = 0; i < 3; ++i) { mExplosion[i]->SetLoop(false); mExplosion[i]->SetVisible(false); if (i>0) mExplosion[i]->SetPosition(mExplosion[i-1]->GetPositionX() + mNextExplosionPoint.GetX(), mExplosion[i-1]->GetPositionY() + mNextExplosionPoint.GetY()); AddChild(mExplosion[i]); } mExplosion[mIndex++]->SetVisible(true); // mTypeEffect = NNParticleSystem::Create(L"Sprite/FlashEffect.png"); // // mTypeEffect->SetMinStartSpeed(100.f); // mTypeEffect->SetMaxStartSpeed(110.f); // mTypeEffect->SetMinEndSpeed(120.f); // mTypeEffect->SetMaxEndSpeed(130.f); // // mTypeEffect->SetCreateParticlePerSecond(60); // mTypeEffect->SetSpreadDegree(360.f); // mTypeEffect->SetMinLifeTime(0.5f); // mTypeEffect->SetMaxLifeTime(0.5f); // // mTypeEffect->SetMinStartRodiusX( 50.f ); // mTypeEffect->SetMinStartRodiusY( 50.f ); // mTypeEffect->SetMaxStartRodiusX( 60.f ); // mTypeEffect->SetMaxStartRodiusY( 60.f ); // // AddChild(mTypeEffect); } ATypeEffect::~ATypeEffect() { } void ATypeEffect::Render() { IEffect::Render(); } void ATypeEffect::Update( float dTime ) { IEffect::Update( dTime ); mTimeCount += dTime; if (mTimeCount >= mExplosionTerm) { mTimeCount -= mExplosionTerm; mExplosion[mIndex++]->SetVisible(false); mExplosion[mIndex]->SetVisible(true); } if (mLifeTime < mNowLifeTime) { mIsEnd = true; // mTypeEffect->SetCreate(false); // // if (mTypeEffect->GetCount() == 0) // } }<commit_msg># ATypeEffect<commit_after>#include "ATypeEffect.h" ATypeEffect::ATypeEffect(CPlayer* follower) { for (int i = 0; i < 3;++i) mExplosion[i] = NNAnimation::Create(); wchar_t temp[256] = { 0 }; for (int i = 0; i < 40; i++) { wsprintf(temp, L"Sprite/FireSkill/%d.png", i); for (int j = 0; j < 3; ++j) mExplosion[j]->AddFrameNode(temp); } for (int i = 0; i < 3; ++i) mExplosion[i]->SetFrameTimeInSection(0.02f, 0, 39); mFollower = follower; mDirection = mFollower->GetPlayerRotation(); mDistance = 100.f; mIndex = 0; mExplosionTerm = 0.3f; mTimeCount = 0.f; mLifeTime = mExplosion[0]->GetPlayTime() + mExplosionTerm * 3; mLifeTime = 4.f; SetPosition(mFollower->GetPlayerPosition().GetX() - 65.f, mFollower->GetPlayerPosition().GetY() - 65.f); mNextExplosionPoint.SetPoint(mDistance * std::cosf(mDirection), mDistance * std::sinf(mDirection)); mExplosion[0]->SetPosition(mNextExplosionPoint.GetX(), mNextExplosionPoint.GetY()); for (int i = 0; i < 3; ++i) { mExplosion[i]->SetLoop(false); mExplosion[i]->SetVisible(false); if (i>0) mExplosion[i]->SetPosition(mExplosion[i-1]->GetPositionX() + mNextExplosionPoint.GetX(), mExplosion[i-1]->GetPositionY() + mNextExplosionPoint.GetY()); AddChild(mExplosion[i]); } mExplosion[mIndex]->SetVisible(true); // mTypeEffect = NNParticleSystem::Create(L"Sprite/FlashEffect.png"); // // mTypeEffect->SetMinStartSpeed(100.f); // mTypeEffect->SetMaxStartSpeed(110.f); // mTypeEffect->SetMinEndSpeed(120.f); // mTypeEffect->SetMaxEndSpeed(130.f); // // mTypeEffect->SetCreateParticlePerSecond(60); // mTypeEffect->SetSpreadDegree(360.f); // mTypeEffect->SetMinLifeTime(0.5f); // mTypeEffect->SetMaxLifeTime(0.5f); // // mTypeEffect->SetMinStartRodiusX( 50.f ); // mTypeEffect->SetMinStartRodiusY( 50.f ); // mTypeEffect->SetMaxStartRodiusX( 60.f ); // mTypeEffect->SetMaxStartRodiusY( 60.f ); // // AddChild(mTypeEffect); } ATypeEffect::~ATypeEffect() { } void ATypeEffect::Render() { IEffect::Render(); } void ATypeEffect::Update( float dTime ) { IEffect::Update( dTime ); mTimeCount += dTime; if (mIndex < 2 && mTimeCount >= mExplosionTerm) { mTimeCount -= mExplosionTerm; mExplosion[++mIndex]->SetVisible(true); } if (mLifeTime < mNowLifeTime) { mIsEnd = true; // mTypeEffect->SetCreate(false); // // if (mTypeEffect->GetCount() == 0) // } }<|endoftext|>
<commit_before>namespace gen { /* Internal functions only to be used from other sources in this directory. */ namespace internal { /* Writers preference */ struct rw_semaphore { protected: std::mutex m{}; // protects both the members of this and the resource unsigned r{0}, w{0}; // active readers, waiting writers std::condition_variable rq{}, wq{}; // read queue, write queue size_t mod_cnt{0}; // modification counter friend class rw_lock; public: rw_semaphore() { } rw_semaphore(const rw_semaphore&) = delete; rw_semaphore(rw_semaphore&&) = delete; rw_semaphore& operator= (const rw_semaphore&) = delete; rw_semaphore& operator= (rw_semaphore&&) = delete; size_t get_mod_cnt() { return mod_cnt; } }; class rw_lock { /* Invariants: * mutex free ⇒ semaphore members and resource constant * pers_lock free ⇒ no active writes (resource constant) * w = 0 ⇒ rq notified * r = 0 ⇒ wq notified * write active ⇒ r = 0, w > 0, pers_lock */ rw_semaphore& s; std::unique_lock<std::mutex> pers_lock{}; bool write{false}; protected: rw_lock(rw_semaphore& _s, bool _w): s(_s), write(_w) { if(write) { // Logic: write creates a persistent lock, preventing other writes from // starting. They can still execute ++s.w to let themselves known but // this enqueues them at the end of wq.wait. Write can only start when // everyone is finished reading. pers_lock = std::unique_lock<std::mutex>(s.m); ++s.w; s.wq.wait(pers_lock, [&] { return s.r == 0; }); } else { // Logic: read creates a temporary lock for the purposes of rq.wait and // s.r access. Read can only start when no one is writing or waiting to // write. std::unique_lock<std::mutex> temp_lock(s.m); s.rq.wait(temp_lock, [&] { return s.w == 0; }); ++s.r; } } ~rw_lock() { if(write) { --s.w; ++s.mod_cnt; pers_lock.unlock(); s.rq.notify_all(); } else { { std::unique_lock<std::mutex> temp_lock(s.m); --s.r; } s.wq.notify_all(); } } rw_lock(const rw_lock&) = delete; rw_lock(rw_lock&&) = delete; rw_lock& operator= (const rw_lock&) = delete; rw_lock& operator= (rw_lock&&) = delete; public: bool upgrade() { if(write) return false; // Atomically combined action of -read and +write pers_lock = std::unique_lock<std::mutex>(s.m); ++s.w; --s.r; write = true; s.wq.wait(pers_lock, [&] { return s.r == 0; }); // It makes no sense for another waiting write to wake up now, that // would defeat the purpose of the upgrade. But we need to notify the // other threads that r might be zero as no one else would do that. // Keeping pers_lock allows them to exit wait() but stay stuck at the // mutex lock. s.wq.notify_all(); return true; } void downgrade() { if(!write) return; // Atomically combined action of -write and +read. --s.w; ++s.mod_cnt; ++s.r; write = false; pers_lock.unlock(); // Other waiting reads can proceed now, the write is done s.rq.notify_all(); } }; class read_lock: public rw_lock { public: read_lock(rw_semaphore& s): rw_lock(s, false) { } }; class write_lock: public rw_lock { public: write_lock(rw_semaphore& s): rw_lock(s, true) { } }; class upgrade_lock { rw_lock& l; bool u{false}; public: upgrade_lock(rw_lock& _l): l(_l) { u = l.upgrade(); } ~upgrade_lock() { if(u) l.downgrade(); } }; } // namespace internal } // namespace gen <commit_msg>RW semaphore: update mod_cnt logic and invariants<commit_after>namespace gen { /* Internal functions only to be used from other sources in this directory. */ namespace internal { /* Writers preference */ struct rw_semaphore { /* Invariants: * mutex free ⇒ semaphore members and resource constant * pers_lock free ⇒ no active writes (resource constant) * w = 0 ⇔ no writers waiting * r = 0 ⇔ no readers active * w → 0 ⇒ rq notified * r → 0 ⇒ wq notified * cnt = cache_cnt ⇒ res = cache_res * write active ⇒ r = 0, w > 0, pers_lock, cnt > cache_cnt * Corollary: * see rw_lock::upgrade()! */ protected: std::mutex m{}; // protects both the members of this and the resource unsigned r{0}, w{0}; // active readers, waiting writers std::condition_variable rq{}, wq{}; // read queue, write queue size_t mod_cnt{0}; // modification counter friend class rw_lock; public: rw_semaphore() { } rw_semaphore(const rw_semaphore&) = delete; rw_semaphore(rw_semaphore&&) = delete; rw_semaphore& operator= (const rw_semaphore&) = delete; rw_semaphore& operator= (rw_semaphore&&) = delete; size_t get_mod_cnt() { return mod_cnt; } }; class rw_lock { rw_semaphore& s; std::unique_lock<std::mutex> pers_lock{}; bool write{false}; protected: rw_lock(rw_semaphore& _s, bool _w): s(_s), write(_w) { if(write) { // Logic: write creates a persistent lock, preventing other writes from // starting. They can still execute ++s.w to let themselves known but // this enqueues them at the end of wq.wait. Write can only start when // everyone is finished reading. pers_lock = std::unique_lock<std::mutex>(s.m); ++s.w; s.wq.wait(pers_lock, [&] { return s.r == 0; }); ++s.mod_cnt; } else { // Logic: read creates a temporary lock for the purposes of rq.wait and // s.r access. Read can only start when no one is writing or waiting to // write. std::unique_lock<std::mutex> temp_lock(s.m); s.rq.wait(temp_lock, [&] { return s.w == 0; }); ++s.r; } } ~rw_lock() { if(write) { --s.w; pers_lock.unlock(); s.rq.notify_all(); } else { { std::unique_lock<std::mutex> temp_lock(s.m); --s.r; } s.wq.notify_all(); } } rw_lock(const rw_lock&) = delete; rw_lock(rw_lock&&) = delete; rw_lock& operator= (const rw_lock&) = delete; rw_lock& operator= (rw_lock&&) = delete; public: /* Important: don't rely on any information about the resource obtained * prior to upgrade()! Other writers may have stepped in during the wait. * This won't be any of the threads started with a writers' lock since * they are waiting for *us* to finish but if more readers simultaneously * want to upgrade then they will have to wait for each other. * * However, a thread can check if its upgrade request was uninterrupted * by other threads by comparing if s.mod_cnt raised by 1 exactly. * * This admittedly makes a lock upgrade not much different from a read * release followed by write acquire. The difference is that an upgraded * lock always has priority over waiting writes. */ bool upgrade() { if(write) return false; // Atomically combined action of -read and +write pers_lock = std::unique_lock<std::mutex>(s.m); ++s.w; --s.r; write = true; s.wq.wait(pers_lock, [&] { return s.r == 0; }); ++s.mod_cnt; // It makes no sense for another waiting write to wake up now, that // would defeat the purpose of the upgrade. But we need to notify the // other threads that r might be zero as no one else would do that. // Keeping pers_lock allows them to exit wait() but stay stuck at the // mutex lock. s.wq.notify_all(); return true; } /* Downgrade a write lock to a read lock, allowing the read to finish * before another writer obtains the lock. */ void downgrade() { if(!write) return; // Atomically combined action of -write and +read. --s.w; ++s.r; write = false; pers_lock.unlock(); // Other waiting reads can proceed now, the write is done s.rq.notify_all(); } }; class read_lock: public rw_lock { public: read_lock(rw_semaphore& s): rw_lock(s, false) { } }; class write_lock: public rw_lock { public: write_lock(rw_semaphore& s): rw_lock(s, true) { } }; class upgrade_lock { rw_lock& l; bool u{false}; public: upgrade_lock(rw_lock& _l): l(_l) { u = l.upgrade(); } ~upgrade_lock() { if(u) l.downgrade(); } }; } // namespace internal } // namespace gen <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Characters/CString/Utilities.h" #include "../Characters/StringBuilder.h" #include "../Characters/ToString.h" #include "../Memory/BlockAllocated.h" #include "Common.h" #include "Sleep.h" #include "TimeOutException.h" #include "ThreadPool.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using Characters::String; using Characters::StringBuilder; class ThreadPool::MyRunnable_ { public: MyRunnable_ (ThreadPool& threadPool) : fCurTaskUpdateCritSection_ () , fThreadPool_ (threadPool) , fCurTask_ () , fNextTask_ () { } public: ThreadPool::TaskType GetCurrentTask () const { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; // THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK // Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either Assert (fCurTask_ == nullptr or fNextTask_ == nullptr); // one or both must be null return fCurTask_ == nullptr ? fNextTask_ : fCurTask_; } public: nonvirtual void Run () { // For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability // Keep grabbing new tasks, and running them while (true) { { fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; Assert (fNextTask_ != nullptr); Assert (fCurTask_ == nullptr); fCurTask_ = fNextTask_; fNextTask_ = nullptr; Assert (fCurTask_ != nullptr); Assert (fNextTask_ == nullptr); } try { fCurTask_ (); fCurTask_ = nullptr; } catch (const Thread::AbortException&) { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; fCurTask_ = nullptr; throw; // cancel this thread } catch (...) { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; fCurTask_ = nullptr; // other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE } } } private: mutable recursive_mutex fCurTaskUpdateCritSection_; ThreadPool& fThreadPool_; ThreadPool::TaskType fCurTask_; ThreadPool::TaskType fNextTask_; }; /* ******************************************************************************** ****************************** Execution::ThreadPool *************************** ******************************************************************************** */ ThreadPool::ThreadPool (unsigned int nThreads) : fCriticalSection_ () , fAborted_ (false) , fThreads_ () , fPendingTasks_ () , fTasksMaybeAdded_ (WaitableEvent::eAutoReset) { SetPoolSize (nThreads); } ThreadPool::~ThreadPool () { try { this->AbortAndWaitForDone (); } catch (...) { DbgTrace ("Ignore exception in destroying thread pool ** probably bad thing..."); } } unsigned int ThreadPool::GetPoolSize () const { return static_cast<unsigned int> (fThreads_.size ()); } void ThreadPool::SetPoolSize (unsigned int poolSize) { Debug::TraceContextBumper ctx ("ThreadPool::SetPoolSize"); Require (not fAborted_); auto critSec { make_unique_lock (fCriticalSection_) }; while (poolSize > fThreads_.size ()) { fThreads_.Add (mkThread_ ()); } // Still quite weak implementation of REMOVAL while (poolSize < fThreads_.size ()) { // iterate over threads if any not busy, remove that one bool anyFoundToKill = false; for (Iterator<TPInfo_> i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType ct { tr->GetCurrentTask () }; if (ct == nullptr) { // since we have fCriticalSection_ - we can safely remove this thread fThreads_.Remove (i); anyFoundToKill = true; break; } } if (not anyFoundToKill) { // @todo - fix this better/eventually DbgTrace ("Failed to lower the loop size - cuz all threads busy - giving up"); return; } } } ThreadPool::TaskType ThreadPool::AddTask (const TaskType& task) { //Debug::TraceContextBumper ctx ("ThreadPool::AddTask"); Require (not fAborted_); { auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.push_back (task); } // Notify any waiting threads to wakeup and claim the next task fTasksMaybeAdded_.Set (); // this would be a race - if aborting and adding tasks at the same time Require (not fAborted_); return task; } void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout) { Debug::TraceContextBumper ctx ("ThreadPool::AbortTask"); { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) { if (*i == task) { fPendingTasks_.erase (i); return; } } } // If we got here - its NOT in the task Q, so maybe its already running. // // // TODO: // We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task. // But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK // actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for something // quite rare. // // Anyhow SB OK for now to just not allow aborting a task which has already started.... Thread thread2Kill; { auto critSec { make_unique_lock (fCriticalSection_) }; for (Iterator<TPInfo_> i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType ct { tr->GetCurrentTask () }; if (task == ct) { thread2Kill = i->fThread; fThreads_.Update (i, mkThread_ ()); break; } } } if (thread2Kill.GetStatus () != Thread::Status::eNull) { thread2Kill.AbortAndWaitForDone (timeout); } } void ThreadPool::AbortTasks (Time::DurationSecondsType timeout) { Debug::TraceContextBumper ctx ("ThreadPool::AbortTasks"); auto tps = GetPoolSize (); { auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.clear (); } { auto critSec { make_unique_lock (fCriticalSection_) }; for (TPInfo_ ti : fThreads_) { ti.fThread.Abort (); } } { auto critSec { make_unique_lock (fCriticalSection_) }; for (TPInfo_ ti : fThreads_) { // @todo fix wrong timeout value here ti.fThread.AbortAndWaitForDone (timeout); } fThreads_.RemoveAll (); } // hack - not a good design or impl!!! - waste to recreate if not needed! SetPoolSize (tps); } bool ThreadPool::IsPresent (const TaskType& task) const { Require (task != nullptr); { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) { if (*i == task) { return true; } } } return IsRunning (task); } bool ThreadPool::IsRunning (const TaskType& task) const { Require (task != nullptr); { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType rTask { tr->GetCurrentTask () }; if (task == rTask) { return true; } } } return false; } void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const { Debug::TraceContextBumper ctx ("ThreadPool::WaitForTask"); // Inefficient / VERY SLOPPY impl using Time::DurationSecondsType; DurationSecondsType timeoutAt = timeout + Time::GetTickCount (); while (true) { if (not IsPresent (task)) { return; } DurationSecondsType remaining = timeoutAt - Time::GetTickCount (); Execution::ThrowTimeoutExceptionAfter (timeoutAt); Execution::Sleep (min<DurationSecondsType> (remaining, 1.0)); } } Collection<ThreadPool::TaskType> ThreadPool::GetTasks () const { Collection<ThreadPool::TaskType> result; { auto critSec { make_unique_lock (fCriticalSection_) }; result.AddAll (fPendingTasks_.begin (), fPendingTasks_.end ()); // copy pending tasks for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { result.Add (task); } } } return result; } Collection<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const { Collection<ThreadPool::TaskType> result; { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { result.Add (task); } } } return result; } size_t ThreadPool::GetTasksCount () const { size_t count = 0; { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; count += fPendingTasks_.size (); for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { count++; } } } return count; } size_t ThreadPool::GetPendingTasksCount () const { size_t count = 0; { auto critSec { make_unique_lock (fCriticalSection_) }; count += fPendingTasks_.size (); } return count; } void ThreadPool::WaitForDoneUntil (Time::DurationSecondsType timeoutAt) const { Debug::TraceContextBumper ctx ("ThreadPool::WaitForDoneUntil"); DbgTrace (L"this-status: %s", ToString ().c_str ()); Require (fAborted_); { Collection<Thread> threadsToShutdown; // cannot keep critical section while waiting on subthreads since they may need to acquire the critsection for whatever they are doing... #if qDefaultTracingOn Collection<String> threadsNotAlreadyDone; // just for DbgTrace message purposes #endif { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto ti : fThreads_) { threadsToShutdown.Add (ti.fThread); #if qDefaultTracingOn if (not ti.fThread.IsDone ()) { threadsNotAlreadyDone.Add (Execution::FormatThreadID (ti.fThread.GetID ())); } #endif } } DbgTrace (L"threadsToShutdown.size = %d", threadsToShutdown.size ()); #if qDefaultTracingOn DbgTrace (L"threadsNotAlreadyDone = %s", Characters::ToString (threadsNotAlreadyDone).c_str ()); #endif for (auto t : threadsToShutdown) { t.WaitForDoneUntil (timeoutAt); } } } void ThreadPool::Abort () { Debug::TraceContextBumper ctx ("ThreadPool::Abort"); DbgTrace (L"this-status: %s", ToString ().c_str ()); fAborted_ = true; // No race, because fAborted never 'unset' // no need to set fTasksMaybeAdded_, since aborting each thread should be sufficient { // Clear the task Q and then abort each thread auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.clear (); for (TPInfo_ && ti : fThreads_) { ti.fThread.Abort (); } } } void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout) { Debug::TraceContextBumper traceCtx ("ThreadPool::AbortAndWaitForDone"); DbgTrace (L"this-status: %s", ToString ().c_str ()); Thread::SuppressInterruptionInContext ctx; // must cleanly shut down each of our subthreads - even if our thread is aborting... Abort (); WaitForDone (timeout); } String ThreadPool::ToString () const { auto critSec { make_unique_lock (fCriticalSection_) }; StringBuilder sb; sb += L"{"; sb += Characters::Format (L"pending-task-count: %d", GetPendingTasksCount ()) + L", "; sb += Characters::Format (L"running-task-count: %d", GetRunningTasks ().size ()) + L", "; sb += Characters::Format (L"pool-thread-count: %d", fThreads_.size ()) + L", "; sb += L"}"; return sb.str (); } // THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool void ThreadPool::WaitForNextTask_ (TaskType* result) { RequireNotNull (result); if (fAborted_) { Execution::Throw (Thread::AbortException ()); } while (true) { { auto critSec { make_unique_lock (fCriticalSection_) }; if (not fPendingTasks_.empty ()) { *result = fPendingTasks_.front (); fPendingTasks_.pop_front (); DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task"); return; } } // Prevent spinwaiting... This event is SET when any new item arrives //DbgTrace ("ThreadPool::WaitForNextTask_ () - about to wait for added tasks"); fTasksMaybeAdded_.Wait (); //DbgTrace ("ThreadPool::WaitForNextTask_ () - completed wait for added tasks"); } } ThreadPool::TPInfo_ ThreadPool::mkThread_ () { shared_ptr<MyRunnable_> r { make_shared<ThreadPool::MyRunnable_> (*this) }; Thread t { [r] () { r->Run (); } }; static int sThreadNum_ = 1; // race condition for updating this number, but who cares - its purely cosmetic... t.SetThreadName (Characters::CString::Format (L"Thread Pool Entry %d", sThreadNum_++)); t.Start (); return TPInfo_ { t, r }; } <commit_msg>moved Thread::SuppressInterruptionInContext in ThreadPool::Abort ()<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/Format.h" #include "../Characters/CString/Utilities.h" #include "../Characters/StringBuilder.h" #include "../Characters/ToString.h" #include "../Memory/BlockAllocated.h" #include "Common.h" #include "Sleep.h" #include "TimeOutException.h" #include "ThreadPool.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using Characters::String; using Characters::StringBuilder; class ThreadPool::MyRunnable_ { public: MyRunnable_ (ThreadPool& threadPool) : fCurTaskUpdateCritSection_ () , fThreadPool_ (threadPool) , fCurTask_ () , fNextTask_ () { } public: ThreadPool::TaskType GetCurrentTask () const { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; // THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK // Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either Assert (fCurTask_ == nullptr or fNextTask_ == nullptr); // one or both must be null return fCurTask_ == nullptr ? fNextTask_ : fCurTask_; } public: nonvirtual void Run () { // For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability // Keep grabbing new tasks, and running them while (true) { { fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; Assert (fNextTask_ != nullptr); Assert (fCurTask_ == nullptr); fCurTask_ = fNextTask_; fNextTask_ = nullptr; Assert (fCurTask_ != nullptr); Assert (fNextTask_ == nullptr); } try { fCurTask_ (); fCurTask_ = nullptr; } catch (const Thread::AbortException&) { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; fCurTask_ = nullptr; throw; // cancel this thread } catch (...) { auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) }; fCurTask_ = nullptr; // other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE } } } private: mutable recursive_mutex fCurTaskUpdateCritSection_; ThreadPool& fThreadPool_; ThreadPool::TaskType fCurTask_; ThreadPool::TaskType fNextTask_; }; /* ******************************************************************************** ****************************** Execution::ThreadPool *************************** ******************************************************************************** */ ThreadPool::ThreadPool (unsigned int nThreads) : fCriticalSection_ () , fAborted_ (false) , fThreads_ () , fPendingTasks_ () , fTasksMaybeAdded_ (WaitableEvent::eAutoReset) { SetPoolSize (nThreads); } ThreadPool::~ThreadPool () { try { this->AbortAndWaitForDone (); } catch (...) { DbgTrace ("Ignore exception in destroying thread pool ** probably bad thing..."); } } unsigned int ThreadPool::GetPoolSize () const { return static_cast<unsigned int> (fThreads_.size ()); } void ThreadPool::SetPoolSize (unsigned int poolSize) { Debug::TraceContextBumper ctx ("ThreadPool::SetPoolSize"); Require (not fAborted_); auto critSec { make_unique_lock (fCriticalSection_) }; while (poolSize > fThreads_.size ()) { fThreads_.Add (mkThread_ ()); } // Still quite weak implementation of REMOVAL while (poolSize < fThreads_.size ()) { // iterate over threads if any not busy, remove that one bool anyFoundToKill = false; for (Iterator<TPInfo_> i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType ct { tr->GetCurrentTask () }; if (ct == nullptr) { // since we have fCriticalSection_ - we can safely remove this thread fThreads_.Remove (i); anyFoundToKill = true; break; } } if (not anyFoundToKill) { // @todo - fix this better/eventually DbgTrace ("Failed to lower the loop size - cuz all threads busy - giving up"); return; } } } ThreadPool::TaskType ThreadPool::AddTask (const TaskType& task) { //Debug::TraceContextBumper ctx ("ThreadPool::AddTask"); Require (not fAborted_); { auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.push_back (task); } // Notify any waiting threads to wakeup and claim the next task fTasksMaybeAdded_.Set (); // this would be a race - if aborting and adding tasks at the same time Require (not fAborted_); return task; } void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout) { Debug::TraceContextBumper ctx ("ThreadPool::AbortTask"); { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) { if (*i == task) { fPendingTasks_.erase (i); return; } } } // If we got here - its NOT in the task Q, so maybe its already running. // // // TODO: // We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task. // But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK // actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for something // quite rare. // // Anyhow SB OK for now to just not allow aborting a task which has already started.... Thread thread2Kill; { auto critSec { make_unique_lock (fCriticalSection_) }; for (Iterator<TPInfo_> i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType ct { tr->GetCurrentTask () }; if (task == ct) { thread2Kill = i->fThread; fThreads_.Update (i, mkThread_ ()); break; } } } if (thread2Kill.GetStatus () != Thread::Status::eNull) { thread2Kill.AbortAndWaitForDone (timeout); } } void ThreadPool::AbortTasks (Time::DurationSecondsType timeout) { Debug::TraceContextBumper ctx ("ThreadPool::AbortTasks"); auto tps = GetPoolSize (); { auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.clear (); } { auto critSec { make_unique_lock (fCriticalSection_) }; for (TPInfo_ ti : fThreads_) { ti.fThread.Abort (); } } { auto critSec { make_unique_lock (fCriticalSection_) }; for (TPInfo_ ti : fThreads_) { // @todo fix wrong timeout value here ti.fThread.AbortAndWaitForDone (timeout); } fThreads_.RemoveAll (); } // hack - not a good design or impl!!! - waste to recreate if not needed! SetPoolSize (tps); } bool ThreadPool::IsPresent (const TaskType& task) const { Require (task != nullptr); { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) { if (*i == task) { return true; } } } return IsRunning (task); } bool ThreadPool::IsRunning (const TaskType& task) const { Require (task != nullptr); { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType rTask { tr->GetCurrentTask () }; if (task == rTask) { return true; } } } return false; } void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const { Debug::TraceContextBumper ctx ("ThreadPool::WaitForTask"); // Inefficient / VERY SLOPPY impl using Time::DurationSecondsType; DurationSecondsType timeoutAt = timeout + Time::GetTickCount (); while (true) { if (not IsPresent (task)) { return; } DurationSecondsType remaining = timeoutAt - Time::GetTickCount (); Execution::ThrowTimeoutExceptionAfter (timeoutAt); Execution::Sleep (min<DurationSecondsType> (remaining, 1.0)); } } Collection<ThreadPool::TaskType> ThreadPool::GetTasks () const { Collection<ThreadPool::TaskType> result; { auto critSec { make_unique_lock (fCriticalSection_) }; result.AddAll (fPendingTasks_.begin (), fPendingTasks_.end ()); // copy pending tasks for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { result.Add (task); } } } return result; } Collection<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const { Collection<ThreadPool::TaskType> result; { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { result.Add (task); } } } return result; } size_t ThreadPool::GetTasksCount () const { size_t count = 0; { // First see if its in the Q auto critSec { make_unique_lock (fCriticalSection_) }; count += fPendingTasks_.size (); for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) { shared_ptr<MyRunnable_> tr { i->fRunnable }; TaskType task { tr->GetCurrentTask () }; if (task != nullptr) { count++; } } } return count; } size_t ThreadPool::GetPendingTasksCount () const { size_t count = 0; { auto critSec { make_unique_lock (fCriticalSection_) }; count += fPendingTasks_.size (); } return count; } void ThreadPool::WaitForDoneUntil (Time::DurationSecondsType timeoutAt) const { Debug::TraceContextBumper ctx ("ThreadPool::WaitForDoneUntil"); DbgTrace (L"this-status: %s", ToString ().c_str ()); Require (fAborted_); { Collection<Thread> threadsToShutdown; // cannot keep critical section while waiting on subthreads since they may need to acquire the critsection for whatever they are doing... #if qDefaultTracingOn Collection<String> threadsNotAlreadyDone; // just for DbgTrace message purposes #endif { auto critSec { make_unique_lock (fCriticalSection_) }; for (auto ti : fThreads_) { threadsToShutdown.Add (ti.fThread); #if qDefaultTracingOn if (not ti.fThread.IsDone ()) { threadsNotAlreadyDone.Add (Execution::FormatThreadID (ti.fThread.GetID ())); } #endif } } DbgTrace (L"threadsToShutdown.size = %d", threadsToShutdown.size ()); #if qDefaultTracingOn DbgTrace (L"threadsNotAlreadyDone = %s", Characters::ToString (threadsNotAlreadyDone).c_str ()); #endif for (auto t : threadsToShutdown) { t.WaitForDoneUntil (timeoutAt); } } } void ThreadPool::Abort () { Debug::TraceContextBumper ctx ("ThreadPool::Abort"); DbgTrace (L"this-status: %s", ToString ().c_str ()); fAborted_ = true; // No race, because fAborted never 'unset' // no need to set fTasksMaybeAdded_, since aborting each thread should be sufficient { // Clear the task Q and then abort each thread auto critSec { make_unique_lock (fCriticalSection_) }; fPendingTasks_.clear (); for (TPInfo_ && ti : fThreads_) { ti.fThread.Abort (); } } } void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout) { Debug::TraceContextBumper traceCtx ("ThreadPool::AbortAndWaitForDone"); Thread::SuppressInterruptionInContext ctx; // must cleanly shut down each of our subthreads - even if our thread is aborting... DbgTrace (L"this-status: %s", ToString ().c_str ()); Abort (); WaitForDone (timeout); } String ThreadPool::ToString () const { auto critSec { make_unique_lock (fCriticalSection_) }; StringBuilder sb; sb += L"{"; sb += Characters::Format (L"pending-task-count: %d", GetPendingTasksCount ()) + L", "; sb += Characters::Format (L"running-task-count: %d", GetRunningTasks ().size ()) + L", "; sb += Characters::Format (L"pool-thread-count: %d", fThreads_.size ()) + L", "; sb += L"}"; return sb.str (); } // THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool void ThreadPool::WaitForNextTask_ (TaskType* result) { RequireNotNull (result); if (fAborted_) { Execution::Throw (Thread::AbortException ()); } while (true) { { auto critSec { make_unique_lock (fCriticalSection_) }; if (not fPendingTasks_.empty ()) { *result = fPendingTasks_.front (); fPendingTasks_.pop_front (); DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task"); return; } } // Prevent spinwaiting... This event is SET when any new item arrives //DbgTrace ("ThreadPool::WaitForNextTask_ () - about to wait for added tasks"); fTasksMaybeAdded_.Wait (); //DbgTrace ("ThreadPool::WaitForNextTask_ () - completed wait for added tasks"); } } ThreadPool::TPInfo_ ThreadPool::mkThread_ () { shared_ptr<MyRunnable_> r { make_shared<ThreadPool::MyRunnable_> (*this) }; Thread t { [r] () { r->Run (); } }; static int sThreadNum_ = 1; // race condition for updating this number, but who cares - its purely cosmetic... t.SetThreadName (Characters::CString::Format (L"Thread Pool Entry %d", sThreadNum_++)); t.Start (); return TPInfo_ { t, r }; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2015 libbitcoin developers (see COPYING). // // GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY // /////////////////////////////////////////////////////////////////////////////// #ifndef MVS_VERSION_HPP #define MVS_VERSION_HPP /** * The semantic version of this repository as: [major].[minor].[patch] * For interpretation of the versioning scheme see: http://semver.org */ #define MVS_VERSION "0.7.3" #define MVS_MAJOR_VERSION 0 #define MVS_MINOR_VERSION 7 #define MVS_PATCH_VERSION 3 #endif <commit_msg>修改版本号<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2015 libbitcoin developers (see COPYING). // // GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY // /////////////////////////////////////////////////////////////////////////////// #ifndef MVS_VERSION_HPP #define MVS_VERSION_HPP /** * The semantic version of this repository as: [major].[minor].[patch] * For interpretation of the versioning scheme see: http://semver.org */ #define MVS_VERSION "0.7.4" #define MVS_MAJOR_VERSION 0 #define MVS_MINOR_VERSION 7 #define MVS_PATCH_VERSION 4 #endif <|endoftext|>
<commit_before>#pragma once #include <microscopes/common/macros.hpp> #include <microscopes/common/typedefs.hpp> #include <microscopes/common/util.hpp> #include <microscopes/common/variadic/dataview.hpp> namespace microscopes{ namespace hdp_hmm{ } // namespace hdp_hmm } // namespace microscopes<commit_msg>Started fast-and-simple HDP-HMM implementation<commit_after>#pragma once namespace microscopes{ namespace hdp_hmm{ typedef std::vector<std::vector<size_t>> data_type; // shorten type // To start with, just build an HDP-HMM for discrete distributions with Dirichlet prior on observations class hdm_hmm { public: hdp_hmm(size_t alphalen, data_type data) : alphalen_(alphalen), gamma_(), alpha0_(), obs_hp_(alphalen, 1.0 / alphalen) data_(data) {} protected: // hyperparameters const size_t alphalen_; // alphabet size float gamma_; // top-level concentration parameter float alpha0_; // lower-level concentration parameter std::vector<double> obs_hp_; // vector of Dirichlet distribution hyperparameters for prior on observation distribution // data const data_type data_; // parameters updated by Gibbs sampling data_type assignments_; // assignment of every time step in the data to a latent state std::map<std::pair<size_t, size_t>, size_t> table_counts_; // (dish_id, restaurant_id) maps to number of tables in that restaurant that serve that dish std::vector<double> betas_; // stick lengths for upper level Dirichlet Process sample }; } // namespace hdp_hmm } // namespace microscopes<|endoftext|>
<commit_before>// Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ENDIAN_HPP #define TAO_PEGTL_INTERNAL_ENDIAN_HPP #include <cstdint> #include <cstring> #include "../config.hpp" #if defined( _WIN32 ) && !defined( __MINGW32__ ) #include "endian_win.hpp" #else #include "endian_gcc.hpp" #endif namespace TAO_PEGTL_NAMESPACE::internal { template< typename N > [[nodiscard]] N h_to_be( const N n ) noexcept { return N( to_and_from_be< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N be_to_h( const N n ) noexcept { return h_to_be( n ); } template< typename N > [[nodiscard]] N be_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::be_to_h( n ); } template< typename N > [[nodiscard]] N h_to_le( const N n ) noexcept { return N( to_and_from_le< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N le_to_h( const N n ) noexcept { return h_to_le( n ); } template< typename N > [[nodiscard]] N le_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::le_to_h( n ); } } // namespace TAO_PEGTL_NAMESPACE::internal #endif <commit_msg>Fix Cygwin build<commit_after>// Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ENDIAN_HPP #define TAO_PEGTL_INTERNAL_ENDIAN_HPP #include <cstdint> #include <cstring> #include "../config.hpp" #if defined( _WIN32 ) && !defined( __MINGW32__ ) && !defined( __CYGWIN__ ) #include "endian_win.hpp" #else #include "endian_gcc.hpp" #endif namespace TAO_PEGTL_NAMESPACE::internal { template< typename N > [[nodiscard]] N h_to_be( const N n ) noexcept { return N( to_and_from_be< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N be_to_h( const N n ) noexcept { return h_to_be( n ); } template< typename N > [[nodiscard]] N be_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::be_to_h( n ); } template< typename N > [[nodiscard]] N h_to_le( const N n ) noexcept { return N( to_and_from_le< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N le_to_h( const N n ) noexcept { return h_to_le( n ); } template< typename N > [[nodiscard]] N le_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::le_to_h( n ); } } // namespace TAO_PEGTL_NAMESPACE::internal #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 __itkTransformFileReader_hxx #define __itkTransformFileReader_hxx #include "itkTransformFileReader.h" #include "itkTransformIOFactory.h" #include "itkCompositeTransformIOHelper.h" namespace itk { template<typename ScalarType> TransformFileReaderTemplate<ScalarType> ::TransformFileReaderTemplate() : m_FileName("") /* to be removed soon. See .h */ { } template<typename ScalarType> TransformFileReaderTemplate<ScalarType> ::~TransformFileReaderTemplate() { } template<typename ScalarType> void TransformFileReaderTemplate<ScalarType> ::Update() { if ( m_FileName == "" ) { itkExceptionMacro ("No file name given"); } if( m_TransformIO.IsNull() ) { typedef TransformIOFactoryTemplate< ScalarType > TransformFactoryIOType; m_TransformIO = TransformFactoryIOType::CreateTransformIO( m_FileName.c_str(), /*TransformIOFactoryTemplate<ScalarType>::*/ ReadMode ); if ( m_TransformIO.IsNull() ) { itkExceptionMacro("Can't Create IO object for file " << m_FileName); } } m_TransformIO->SetFileName(m_FileName); m_TransformIO->Read(); typename TransformIOType::TransformListType &ioTransformList = m_TransformIO->GetTransformList(); // In the case where the first transform in the list is a // CompositeTransform, add all the transforms to that first // transform. and return a single composite item on the // m_TransformList const std::string firstTransformName = ioTransformList.front()->GetNameOfClass(); if(firstTransformName.find("CompositeTransform") != std::string::npos) { typename TransformListType::const_iterator tit = ioTransformList.begin(); typename TransformType::Pointer composite = (*tit).GetPointer(); // // CompositeTransformIOHelperTemplate knows how to assign to the composite // transform's internal list CompositeTransformIOHelperTemplate<ScalarType> helper; helper.SetTransformList(composite.GetPointer(),ioTransformList); this->m_TransformList.push_back( composite.GetPointer() ); } else //Just return the entire list of elements { for ( typename TransformListType::iterator it = ioTransformList.begin(); it != ioTransformList.end(); ++it ) { this->m_TransformList.push_back( (*it).GetPointer() ); } } } template<typename ScalarType> void TransformFileReaderTemplate<ScalarType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FileName: " << m_FileName << std::endl; } } // namespace itk #endif <commit_msg>BUG: TransformFileReader does not clear its TransformList.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 __itkTransformFileReader_hxx #define __itkTransformFileReader_hxx #include "itkTransformFileReader.h" #include "itkTransformIOFactory.h" #include "itkCompositeTransformIOHelper.h" namespace itk { template<typename ScalarType> TransformFileReaderTemplate<ScalarType> ::TransformFileReaderTemplate() : m_FileName("") /* to be removed soon. See .h */ { } template<typename ScalarType> TransformFileReaderTemplate<ScalarType> ::~TransformFileReaderTemplate() { } template<typename ScalarType> void TransformFileReaderTemplate<ScalarType> ::Update() { if ( m_FileName == "" ) { itkExceptionMacro ("No file name given"); } if( m_TransformIO.IsNull() ) { typedef TransformIOFactoryTemplate< ScalarType > TransformFactoryIOType; m_TransformIO = TransformFactoryIOType::CreateTransformIO( m_FileName.c_str(), /*TransformIOFactoryTemplate<ScalarType>::*/ ReadMode ); if ( m_TransformIO.IsNull() ) { itkExceptionMacro("Can't Create IO object for file " << m_FileName); } } m_TransformIO->SetFileName(m_FileName); m_TransformIO->Read(); typename TransformIOType::TransformListType & ioTransformList = m_TransformIO->GetTransformList(); // Clear old results. this->m_TransformList.clear(); // In the case where the first transform in the list is a // CompositeTransform, add all the transforms to that first // transform. and return a single composite item on the // m_TransformList const std::string firstTransformName = ioTransformList.front()->GetNameOfClass(); if(firstTransformName.find("CompositeTransform") != std::string::npos) { typename TransformListType::const_iterator tit = ioTransformList.begin(); typename TransformType::Pointer composite = (*tit).GetPointer(); // CompositeTransformIOHelperTemplate knows how to assign to the composite // transform's internal list CompositeTransformIOHelperTemplate<ScalarType> helper; helper.SetTransformList(composite.GetPointer(),ioTransformList); this->m_TransformList.push_back( composite.GetPointer() ); } else //Just return the entire list of elements { for ( typename TransformListType::iterator it = ioTransformList.begin(); it != ioTransformList.end(); ++it ) { this->m_TransformList.push_back( (*it).GetPointer() ); } } } template<typename ScalarType> void TransformFileReaderTemplate<ScalarType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FileName: " << m_FileName << std::endl; } } // namespace itk #endif <|endoftext|>
<commit_before>#include "data_generator.hpp" #include "feature_generator.hpp" #include "feature_sorter.hpp" #include "update_generator.hpp" #include "feature_bucketer.hpp" #include "grid_generator.hpp" #include "statistics.hpp" #include "../classif_routine.hpp" #include "../features_vector.hpp" #include "../index_builder.hpp" #include "../osm_decl.hpp" #include "../data_header.hpp" #include "../../defines.hpp" #include "../../platform/platform.hpp" #include "../../3party/gflags/src/gflags/gflags.h" #include "../../std/ctime.hpp" #include "../../std/iostream.hpp" #include "../../std/iomanip.hpp" #include "../../std/numeric.hpp" #include "../../version/version.hpp" #include "../../base/start_mem_debug.hpp" DEFINE_bool(version, false, "Display version"); DEFINE_bool(generate_update, false, "If specified, update.maps file will be generated from cells in the data path"); DEFINE_bool(sort_features, true, "Sort features data for better cache-friendliness."); DEFINE_bool(generate_classif, false, "Generate classificator."); DEFINE_bool(preprocess_xml, false, "1st pass - create nodes/ways/relations data"); DEFINE_bool(generate_features, false, "2nd pass - generate intermediate features"); DEFINE_bool(generate_geometry, false, "3rd pass - split and simplify geometry and triangles for features"); DEFINE_bool(generate_index, false, "4rd pass - generate index"); DEFINE_bool(generate_grid, false, "Generate grid for given bucketing_level"); DEFINE_bool(calc_statistics, false, "Calculate feature statistics for specified mwm bucket files"); DEFINE_bool(use_light_nodes, false, "If true, use temporary vector of nodes, instead of huge temp file"); DEFINE_string(data_path, "", "Working directory, 'path_to_exe/../../data' if empty."); DEFINE_string(output, "", "Prefix of filenames of outputted .dat and .idx files."); DEFINE_string(intermediate_data_path, "", "Path to store nodes, ways, relations."); DEFINE_int32(bucketing_level, -1, "If positive, level of cell ids for bucketing."); DEFINE_int32(generate_world_scale, -1, "If specified, features for zoomlevels [0..this_value] " "which are enabled in classificator will be MOVED to the separate world file"); DEFINE_bool(split_by_polygons, false, "Use kml shape files to split planet by regions and countries"); DEFINE_int32(simplify_countries_level, -1, "If positive, simplifies country polygons. Recommended values [10..15]"); DEFINE_bool(merge_coastlines, false, "If defined, tries to merge coastlines when renerating World file"); string AddSlashIfNeeded(string const & str) { string result(str); size_t const size = result.size(); if (size) { if (result.find_last_of('\\') == size - 1) result[size - 1] = '/'; else if (result.find_last_of('/') != size - 1) result.push_back('/'); } return result; } int main(int argc, char ** argv) { google::SetUsageMessage( "Takes OSM XML data from stdin and creates data and index files in several passes."); google::ParseCommandLineFlags(&argc, &argv, true); string const path = FLAGS_data_path.empty() ? GetPlatform().WritableDir() : AddSlashIfNeeded(FLAGS_data_path); if (FLAGS_version) { cout << "Tool version: " << VERSION_STRING << endl; cout << "Built on: " << VERSION_DATE_STRING << endl; } // Make a classificator if (FLAGS_generate_classif) { classificator::GenerateAndWrite(path); } if (FLAGS_generate_grid) { grid::GenerateGridToStdout(FLAGS_bucketing_level); } // Generating intermediate files if (FLAGS_preprocess_xml) { LOG(LINFO, ("Generating intermediate data ....")); if (!data::GenerateToFile(FLAGS_intermediate_data_path, FLAGS_use_light_nodes)) return -1; } feature::GenerateInfo genInfo; genInfo.tmpDir = FLAGS_intermediate_data_path; // load classificator only if necessary if (FLAGS_generate_features || FLAGS_generate_geometry || FLAGS_generate_index || FLAGS_calc_statistics) { classificator::Read(path + "drawing_rules.bin", path + "classificator.txt", path + "visibility.txt"); classificator::PrepareForFeatureGeneration(); } // Generate dat file if (FLAGS_generate_features) { LOG(LINFO, ("Generating final data ...")); if (FLAGS_output.empty()) genInfo.datFilePrefix = path; else genInfo.datFilePrefix = path + FLAGS_output + (FLAGS_bucketing_level > 0 ? "-" : ""); genInfo.datFileSuffix = DATA_FILE_EXTENSION; // split data by countries polygons genInfo.splitByPolygons = FLAGS_split_by_polygons; genInfo.simplifyCountriesLevel = FLAGS_simplify_countries_level; genInfo.cellBucketingLevel = FLAGS_bucketing_level; genInfo.maxScaleForWorldFeatures = FLAGS_generate_world_scale; genInfo.mergeCoastlines = FLAGS_merge_coastlines; if (!feature::GenerateFeatures(genInfo, FLAGS_use_light_nodes)) return -1; for (size_t i = 0; i < genInfo.bucketNames.size(); ++i) genInfo.bucketNames[i] = genInfo.datFilePrefix + genInfo.bucketNames[i] + genInfo.datFileSuffix; if (FLAGS_generate_world_scale >= 0) genInfo.bucketNames.push_back(genInfo.datFilePrefix + WORLD_FILE_NAME + genInfo.datFileSuffix); } else { genInfo.bucketNames.push_back(path + FLAGS_output + DATA_FILE_EXTENSION); } // Enumerate over all dat files that were created. for (size_t i = 0; i < genInfo.bucketNames.size(); ++i) { string const & datFile = genInfo.bucketNames[i]; if (FLAGS_generate_geometry) { LOG(LINFO, ("Generating result features for ", datFile)); if (!feature::GenerateFinalFeatures(datFile, FLAGS_sort_features)) { // If error - move to next bucket without index generation continue; } } if (FLAGS_generate_index) { LOG(LINFO, ("Generating index for ", datFile)); if (!indexer::BuildIndexFromDatFile(datFile, FLAGS_intermediate_data_path + FLAGS_output)) { LOG(LCRITICAL, ("Error generating index.")); } } if (FLAGS_calc_statistics) { LOG(LINFO, ("Calculating statistics for ", datFile)); stats::FileContainerStatistic(datFile); stats::MapInfo info; stats::CalcStatistic(datFile, info); stats::PrintStatistic(info); } } // Create http update list for countries and corresponding files if (FLAGS_generate_update) { LOG(LINFO, ("Creating maps.update file...")); update::GenerateFilesList(path); } return 0; } <commit_msg>[indexer_tool] Fixed incompatible split_by_polygons and output flags<commit_after>#include "data_generator.hpp" #include "feature_generator.hpp" #include "feature_sorter.hpp" #include "update_generator.hpp" #include "feature_bucketer.hpp" #include "grid_generator.hpp" #include "statistics.hpp" #include "../classif_routine.hpp" #include "../features_vector.hpp" #include "../index_builder.hpp" #include "../osm_decl.hpp" #include "../data_header.hpp" #include "../../defines.hpp" #include "../../platform/platform.hpp" #include "../../3party/gflags/src/gflags/gflags.h" #include "../../std/ctime.hpp" #include "../../std/iostream.hpp" #include "../../std/iomanip.hpp" #include "../../std/numeric.hpp" #include "../../version/version.hpp" #include "../../base/start_mem_debug.hpp" DEFINE_bool(version, false, "Display version"); DEFINE_bool(generate_update, false, "If specified, update.maps file will be generated from cells in the data path"); DEFINE_bool(sort_features, true, "Sort features data for better cache-friendliness."); DEFINE_bool(generate_classif, false, "Generate classificator."); DEFINE_bool(preprocess_xml, false, "1st pass - create nodes/ways/relations data"); DEFINE_bool(generate_features, false, "2nd pass - generate intermediate features"); DEFINE_bool(generate_geometry, false, "3rd pass - split and simplify geometry and triangles for features"); DEFINE_bool(generate_index, false, "4rd pass - generate index"); DEFINE_bool(generate_grid, false, "Generate grid for given bucketing_level"); DEFINE_bool(calc_statistics, false, "Calculate feature statistics for specified mwm bucket files"); DEFINE_bool(use_light_nodes, false, "If true, use temporary vector of nodes, instead of huge temp file"); DEFINE_string(data_path, "", "Working directory, 'path_to_exe/../../data' if empty."); DEFINE_string(output, "", "Prefix of filenames of outputted .dat and .idx files."); DEFINE_string(intermediate_data_path, "", "Path to store nodes, ways, relations."); DEFINE_int32(bucketing_level, -1, "If positive, level of cell ids for bucketing."); DEFINE_int32(generate_world_scale, -1, "If specified, features for zoomlevels [0..this_value] " "which are enabled in classificator will be MOVED to the separate world file"); DEFINE_bool(split_by_polygons, false, "Use kml shape files to split planet by regions and countries"); DEFINE_int32(simplify_countries_level, -1, "If positive, simplifies country polygons. Recommended values [10..15]"); DEFINE_bool(merge_coastlines, false, "If defined, tries to merge coastlines when renerating World file"); string AddSlashIfNeeded(string const & str) { string result(str); size_t const size = result.size(); if (size) { if (result.find_last_of('\\') == size - 1) result[size - 1] = '/'; else if (result.find_last_of('/') != size - 1) result.push_back('/'); } return result; } int main(int argc, char ** argv) { google::SetUsageMessage( "Takes OSM XML data from stdin and creates data and index files in several passes."); google::ParseCommandLineFlags(&argc, &argv, true); string const path = FLAGS_data_path.empty() ? GetPlatform().WritableDir() : AddSlashIfNeeded(FLAGS_data_path); if (FLAGS_version) { cout << "Tool version: " << VERSION_STRING << endl; cout << "Built on: " << VERSION_DATE_STRING << endl; } // Make a classificator if (FLAGS_generate_classif) { classificator::GenerateAndWrite(path); } if (FLAGS_generate_grid) { grid::GenerateGridToStdout(FLAGS_bucketing_level); } // Generating intermediate files if (FLAGS_preprocess_xml) { LOG(LINFO, ("Generating intermediate data ....")); if (!data::GenerateToFile(FLAGS_intermediate_data_path, FLAGS_use_light_nodes)) return -1; } feature::GenerateInfo genInfo; genInfo.tmpDir = FLAGS_intermediate_data_path; // load classificator only if necessary if (FLAGS_generate_features || FLAGS_generate_geometry || FLAGS_generate_index || FLAGS_calc_statistics) { classificator::Read(path + "drawing_rules.bin", path + "classificator.txt", path + "visibility.txt"); classificator::PrepareForFeatureGeneration(); } // Generate dat file if (FLAGS_generate_features) { LOG(LINFO, ("Generating final data ...")); if (FLAGS_output.empty() || FLAGS_split_by_polygons) // do not break data path for polygons genInfo.datFilePrefix = path; else genInfo.datFilePrefix = path + FLAGS_output + (FLAGS_bucketing_level > 0 ? "-" : ""); genInfo.datFileSuffix = DATA_FILE_EXTENSION; // split data by countries polygons genInfo.splitByPolygons = FLAGS_split_by_polygons; genInfo.simplifyCountriesLevel = FLAGS_simplify_countries_level; genInfo.cellBucketingLevel = FLAGS_bucketing_level; genInfo.maxScaleForWorldFeatures = FLAGS_generate_world_scale; genInfo.mergeCoastlines = FLAGS_merge_coastlines; if (!feature::GenerateFeatures(genInfo, FLAGS_use_light_nodes)) return -1; for (size_t i = 0; i < genInfo.bucketNames.size(); ++i) genInfo.bucketNames[i] = genInfo.datFilePrefix + genInfo.bucketNames[i] + genInfo.datFileSuffix; if (FLAGS_generate_world_scale >= 0) genInfo.bucketNames.push_back(genInfo.datFilePrefix + WORLD_FILE_NAME + genInfo.datFileSuffix); } else { genInfo.bucketNames.push_back(path + FLAGS_output + DATA_FILE_EXTENSION); } // Enumerate over all dat files that were created. for (size_t i = 0; i < genInfo.bucketNames.size(); ++i) { string const & datFile = genInfo.bucketNames[i]; if (FLAGS_generate_geometry) { LOG(LINFO, ("Generating result features for ", datFile)); if (!feature::GenerateFinalFeatures(datFile, FLAGS_sort_features)) { // If error - move to next bucket without index generation continue; } } if (FLAGS_generate_index) { LOG(LINFO, ("Generating index for ", datFile)); if (!indexer::BuildIndexFromDatFile(datFile, FLAGS_intermediate_data_path + FLAGS_output)) { LOG(LCRITICAL, ("Error generating index.")); } } if (FLAGS_calc_statistics) { LOG(LINFO, ("Calculating statistics for ", datFile)); stats::FileContainerStatistic(datFile); stats::MapInfo info; stats::CalcStatistic(datFile, info); stats::PrintStatistic(info); } } // Create http update list for countries and corresponding files if (FLAGS_generate_update) { LOG(LINFO, ("Creating maps.update file...")); update::GenerateFilesList(path); } return 0; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #define TIME_TRAY_BALLOON 5000 #define PROJECT "Tsunami++" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); p_session_thread = new QThread(); sessionManager = new tsuManager(); sessionManager->moveToThread(p_session_thread); settingsPage = new settingswindow(this); searchPage = new searchwindow(this); statusLabel = new QLabel(this); statisticsPage = new statisticswindow(this); downloadPage = new downloadwindow(this); initializeScreen(); readSettings(); loadLanguage(language); statusBar()->addPermanentWidget(statusLabel, 0); statusBar()->showMessage("Welcome!"); // add from SessionManager goes to downloadPage to add tsuCard connect(sessionManager, SIGNAL(addFromSessionManager(const tsuEvents::tsuEvent &)), downloadPage, SLOT(addFromSession(const tsuEvents::tsuEvent &)));//, Qt::QueuedConnection); // update from sessionManager goes to downloadPage to manage tsuCard values connect(sessionManager, SIGNAL(updateFromSessionManager(const QVector<tsuEvents::tsuEvent> &)), downloadPage, SLOT(updateFromSession(const QVector<tsuEvents::tsuEvent> &)));//, Qt::DirectConnection); // deleted torrent from sessionManager goes to downloadPage to remove it from list connect(sessionManager, SIGNAL(torrentDeleted(std::string)), downloadPage, SLOT(torrentDeletedFromSession(std::string)));//, Qt::QueuedConnection); // requested cancel from downloadPage (emitted from a tsucard) goes to sessionManager to remove torrent from libtorrent connect(downloadPage, SIGNAL(sendRequestedCancelToSession(std::string,bool)), sessionManager, SLOT(getCancelRequest(std::string,bool)));//, Qt::QueuedConnection); // requested pause from downloadPage (emitted from a tsucard) goes to sessionManager to pause torrent connect(downloadPage, SIGNAL(sendRequestedPauseToSession(std::string)), sessionManager, SLOT(getPauseRequest(std::string)));//, Qt::QueuedConnection); // requested resume from downloadPage (emitted from a tsucard) goes to sessionManager to resume torrent connect(downloadPage, SIGNAL(sendRequestedResumeToSession(std::string)), sessionManager, SLOT(getResumeRequest(std::string)));//, Qt::QueuedConnection); // update from downloadPage to statusbar text connect(downloadPage, SIGNAL(sendUpdateToStatusBar(const QString &)), this, SLOT(updateStatusBar(const QString &)));//, Qt::QueuedConnection); // update from downloadPage to statistics page connect(downloadPage, SIGNAL(sendStatisticsUpdate(const QPair<int,int> &)), statisticsPage, SLOT(updateStats(const QPair<int,int> &)));//, Qt::QueuedConnection); // popup message from downloadPage connect(downloadPage, SIGNAL(sendPopupInfo(QString)), this, SLOT(popupInfo(QString)));//, Qt::QueuedConnection); // update from downloadPage to gauge connect(downloadPage, SIGNAL(sendUpdateGauge(double)), this, SLOT(updateGauge(double)));//, Qt::QueuedConnection); connect(p_session_thread, SIGNAL(started()), sessionManager, SLOT(startManager())); connect(this, SIGNAL(stopSessionManager()), sessionManager, SLOT(stopManager()), Qt::BlockingQueuedConnection); connect(sessionManager, SIGNAL(finished()), p_session_thread, SLOT(quit())); connect(sessionManager, SIGNAL(finished()), sessionManager, SLOT(deleteLater())); // connect(p_session_thread, SIGNAL(finished()), p_session_thread, SLOT(deleteLater())); p_session_thread->start(); } MainWindow::~MainWindow() { qDebug("starting destroy"); // p_session_thread->wait(); // qDebug("session thread waited"); p_session_thread->deleteLater(); qDebug("session thread executed deleteLater"); delete ui; qDebug("ui deleted"); } void MainWindow::updateStatusBar(const QString &msg) { statusLabel->setText(msg); } void MainWindow::updateGauge(const double &value) { p_scaleGauge->setValue(value); } void MainWindow::initializeScreen() { setWindowIcon(QIcon(":/images/logo_tsunami_tiny.ico")); setWindowTitle(PROJECT " " VERSION); // setWindowFlags(Qt::FramelessWindowHint); createTrayIcon(); QFontDatabase::addApplicationFont(":/font/BEBAS___.TTF"); connect(ui->btnSettings, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnUser, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnSearch, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnDownload, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnArchive, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnStreaming, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnStatistics, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnChat, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnAdd, SIGNAL(released()), this, SLOT(btnAddClick())); ui->btnSettings->show(); ui->btnUser->show(); ui->btnSearch->show(); ui->btnDownload->show(); ui->btnArchive->show(); ui->btnStreaming->show(); ui->btnStatistics->show(); ui->btnSettings_on->hide(); ui->btnUser_on->hide(); ui->btnSearch_on->hide(); ui->btnDownload_on->hide(); ui->btnArchive_on->hide(); ui->btnStreaming_on->hide(); ui->btnStatistics_on->hide(); settingsPage->hide(); searchPage->hide(); downloadPage->hide(); statisticsPage->hide(); ui->content->addWidget(settingsPage); ui->content->addWidget(searchPage); ui->content->addWidget(statisticsPage); ui->content->addWidget(downloadPage); p_scaleGauge = new QScale(this); p_scaleGauge->setInvertedAppearance(true); ui->contentGauge->addWidget(p_scaleGauge); } void MainWindow::readSettings() { QSettings settings(settingsPage->settingsFileName, QSettings::IniFormat); settings.beginGroup("MainWindow"); resize(settings.value("size", QSize(840, 670)).toSize()); move(settings.value("pos", QPoint(200, 200)).toPoint()); if ( settings.value("fullScreen", false).toBool() ) setWindowState(Qt::WindowFullScreen); settings.endGroup(); language = settings.value("Language").toString(); } void MainWindow::writeSettings() { QSettings settings(settingsPage->settingsFileName, QSettings::IniFormat); settings.beginGroup("MainWindow"); settings.setValue("size", size()); settings.setValue("pos", pos()); settings.setValue("fullScreen", isFullScreen()); settings.endGroup(); } void MainWindow::updateTsunami() { QProcess process; QString dir = QCoreApplication::applicationDirPath() + "/../"; //qDebug() << dir + "Update.exe"; process.start(dir+"/"+"Update.exe --checkForUpdate=tsunami.adunanza.net/releases/Releases/"); process.waitForFinished(); if(process.error() != QProcess::UnknownError) { qDebug() << "Error checking for updates"; return; } QProcess::startDetached(dir+"Update.exe --update=tsunami.adunanza.net/releases/Releases/"); } void MainWindow::loadLanguage(QString l) { if(l == "Italian") { bool load = t.load(":/languages/italian.qm"); qDebug() << "Load: " << load; } if(l != "English") { bool response = QCoreApplication::installTranslator(&t); qDebug() << "Response: " << response; } } void MainWindow::createTrayIcon() { // Tray icon m_systrayIcon = new QSystemTrayIcon(QIcon(":/images/logo_tsunami_tiny.ico"), this); //m_systrayIcon->setContextMenu(trayIconMenu()); connect(m_systrayIcon, SIGNAL(messageClicked()), this, SLOT(balloonClicked())); // End of Icon Menu connect(m_systrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(toggleVisibility(QSystemTrayIcon::ActivationReason))); m_systrayIcon->setToolTip(PROJECT " " VERSION); m_systrayIcon->show(); // m_systrayIcon->showMessage(PROJECT, "Welcome to the future!", QSystemTrayIcon::Information, TIME_TRAY_BALLOON); popupInfo("Welcome to the future!"); qDebug("started"); } void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) { qDebug("entered toggleVisibility"); if ((e == QSystemTrayIcon::Trigger) || (e == QSystemTrayIcon::DoubleClick)) { if (isHidden()) { /*if (m_uiLocked) { // Ask for UI lock password if (!unlockUI()) return; }*/ // Make sure the window is not minimized setWindowState(windowState() & (~Qt::WindowMinimized | Qt::WindowActive)); // Then show it show(); raise(); activateWindow(); } else { hide(); } } } void MainWindow::balloonClicked() { if (isHidden()) { /*if (m_uiLocked) { // Ask for UI lock password if (!unlockUI()) return; }*/ show(); if (isMinimized()) showNormal(); } raise(); activateWindow(); } void MainWindow::btnMenuClick() { QString btn = sender()->objectName(); ui->btnSettings->setHidden(btn == ui->btnSettings->objectName()); ui->btnUser->setHidden(btn == ui->btnUser->objectName()); ui->btnSearch->setHidden(btn == ui->btnSearch->objectName()); ui->btnDownload->setHidden(btn == ui->btnDownload->objectName()); ui->btnArchive->setHidden(btn == ui->btnArchive->objectName()); ui->btnStreaming->setHidden(btn == ui->btnStreaming->objectName()); ui->btnStatistics->setHidden(btn == ui->btnStatistics->objectName()); ui->btnSettings_on->setHidden(btn != ui->btnSettings->objectName()); ui->btnUser_on->setHidden(btn != ui->btnUser->objectName()); ui->btnSearch_on->setHidden(btn != ui->btnSearch->objectName()); ui->btnDownload_on->setHidden(btn != ui->btnDownload->objectName()); ui->btnArchive_on->setHidden(btn != ui->btnArchive->objectName()); ui->btnStreaming_on->setHidden(btn != ui->btnStreaming->objectName()); ui->btnStatistics_on->setHidden(btn != ui->btnStatistics->objectName()); settingsPage->setHidden(btn != ui->btnSettings->objectName()); searchPage->setHidden(btn != ui->btnSearch->objectName()); statisticsPage->setHidden(btn != ui->btnStatistics->objectName()); downloadPage->setHidden(btn != ui->btnDownload->objectName()); if (btn == ui->btnChat->objectName()) { QString link = "https://discordapp.com/invite/0pfzTOXuEjt9ifvF"; QDesktopServices::openUrl(QUrl(link)); } } void MainWindow::btnAddClick() { QFileDialog fd(this, tr("Select torrent"), settingsPage->getLastBrowsedDir(), tr("Torrents (*.torrent)")); QStringList fileNames = fd.getOpenFileNames(); if (fileNames.isEmpty()) return; settingsPage->setLastBrowsedDir(QFileInfo(fileNames.first()).absolutePath()); sessionManager->addItems(std::move(fileNames), settingsPage->getDownloadPath()); ui->btnDownload->released(); // switch to downloadpage } void MainWindow::popupInfo(const QString &msg) { m_systrayIcon->showMessage(PROJECT, msg, QSystemTrayIcon::Information, TIME_TRAY_BALLOON); } void MainWindow::closeEvent(QCloseEvent *event) { qDebug("closing"); statusLabel->setText("Saving resume data. Please wait."); writeSettings(); updateTsunami(); emit stopSessionManager(); event->accept(); } void MainWindow::changeEvent(QEvent *e) { if(e->type() == QEvent::LanguageChange) { qDebug() << "Intercepted LanguageChange event by MainWindow"; ui->retranslateUi(this); } QMainWindow::changeEvent(e); } <commit_msg>AutoUpdate FixBug<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #define TIME_TRAY_BALLOON 5000 #define PROJECT "Tsunami++" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); p_session_thread = new QThread(); sessionManager = new tsuManager(); sessionManager->moveToThread(p_session_thread); settingsPage = new settingswindow(this); searchPage = new searchwindow(this); statusLabel = new QLabel(this); statisticsPage = new statisticswindow(this); downloadPage = new downloadwindow(this); initializeScreen(); readSettings(); loadLanguage(language); statusBar()->addPermanentWidget(statusLabel, 0); statusBar()->showMessage("Welcome!"); // add from SessionManager goes to downloadPage to add tsuCard connect(sessionManager, SIGNAL(addFromSessionManager(const tsuEvents::tsuEvent &)), downloadPage, SLOT(addFromSession(const tsuEvents::tsuEvent &)));//, Qt::QueuedConnection); // update from sessionManager goes to downloadPage to manage tsuCard values connect(sessionManager, SIGNAL(updateFromSessionManager(const QVector<tsuEvents::tsuEvent> &)), downloadPage, SLOT(updateFromSession(const QVector<tsuEvents::tsuEvent> &)));//, Qt::DirectConnection); // deleted torrent from sessionManager goes to downloadPage to remove it from list connect(sessionManager, SIGNAL(torrentDeleted(std::string)), downloadPage, SLOT(torrentDeletedFromSession(std::string)));//, Qt::QueuedConnection); // requested cancel from downloadPage (emitted from a tsucard) goes to sessionManager to remove torrent from libtorrent connect(downloadPage, SIGNAL(sendRequestedCancelToSession(std::string,bool)), sessionManager, SLOT(getCancelRequest(std::string,bool)));//, Qt::QueuedConnection); // requested pause from downloadPage (emitted from a tsucard) goes to sessionManager to pause torrent connect(downloadPage, SIGNAL(sendRequestedPauseToSession(std::string)), sessionManager, SLOT(getPauseRequest(std::string)));//, Qt::QueuedConnection); // requested resume from downloadPage (emitted from a tsucard) goes to sessionManager to resume torrent connect(downloadPage, SIGNAL(sendRequestedResumeToSession(std::string)), sessionManager, SLOT(getResumeRequest(std::string)));//, Qt::QueuedConnection); // update from downloadPage to statusbar text connect(downloadPage, SIGNAL(sendUpdateToStatusBar(const QString &)), this, SLOT(updateStatusBar(const QString &)));//, Qt::QueuedConnection); // update from downloadPage to statistics page connect(downloadPage, SIGNAL(sendStatisticsUpdate(const QPair<int,int> &)), statisticsPage, SLOT(updateStats(const QPair<int,int> &)));//, Qt::QueuedConnection); // popup message from downloadPage connect(downloadPage, SIGNAL(sendPopupInfo(QString)), this, SLOT(popupInfo(QString)));//, Qt::QueuedConnection); // update from downloadPage to gauge connect(downloadPage, SIGNAL(sendUpdateGauge(double)), this, SLOT(updateGauge(double)));//, Qt::QueuedConnection); connect(p_session_thread, SIGNAL(started()), sessionManager, SLOT(startManager())); connect(this, SIGNAL(stopSessionManager()), sessionManager, SLOT(stopManager()), Qt::BlockingQueuedConnection); connect(sessionManager, SIGNAL(finished()), p_session_thread, SLOT(quit())); connect(sessionManager, SIGNAL(finished()), sessionManager, SLOT(deleteLater())); // connect(p_session_thread, SIGNAL(finished()), p_session_thread, SLOT(deleteLater())); p_session_thread->start(); } MainWindow::~MainWindow() { qDebug("starting destroy"); // p_session_thread->wait(); // qDebug("session thread waited"); p_session_thread->deleteLater(); qDebug("session thread executed deleteLater"); delete ui; qDebug("ui deleted"); } void MainWindow::updateStatusBar(const QString &msg) { statusLabel->setText(msg); } void MainWindow::updateGauge(const double &value) { p_scaleGauge->setValue(value); } void MainWindow::initializeScreen() { setWindowIcon(QIcon(":/images/logo_tsunami_tiny.ico")); setWindowTitle(PROJECT " " VERSION); // setWindowFlags(Qt::FramelessWindowHint); createTrayIcon(); QFontDatabase::addApplicationFont(":/font/BEBAS___.TTF"); connect(ui->btnSettings, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnUser, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnSearch, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnDownload, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnArchive, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnStreaming, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnStatistics, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnChat, SIGNAL(released()), this, SLOT(btnMenuClick())); connect(ui->btnAdd, SIGNAL(released()), this, SLOT(btnAddClick())); ui->btnSettings->show(); ui->btnUser->show(); ui->btnSearch->show(); ui->btnDownload->show(); ui->btnArchive->show(); ui->btnStreaming->show(); ui->btnStatistics->show(); ui->btnSettings_on->hide(); ui->btnUser_on->hide(); ui->btnSearch_on->hide(); ui->btnDownload_on->hide(); ui->btnArchive_on->hide(); ui->btnStreaming_on->hide(); ui->btnStatistics_on->hide(); settingsPage->hide(); searchPage->hide(); downloadPage->hide(); statisticsPage->hide(); ui->content->addWidget(settingsPage); ui->content->addWidget(searchPage); ui->content->addWidget(statisticsPage); ui->content->addWidget(downloadPage); p_scaleGauge = new QScale(this); p_scaleGauge->setInvertedAppearance(true); ui->contentGauge->addWidget(p_scaleGauge); } void MainWindow::readSettings() { QSettings settings(settingsPage->settingsFileName, QSettings::IniFormat); settings.beginGroup("MainWindow"); resize(settings.value("size", QSize(840, 670)).toSize()); move(settings.value("pos", QPoint(200, 200)).toPoint()); if ( settings.value("fullScreen", false).toBool() ) setWindowState(Qt::WindowFullScreen); settings.endGroup(); language = settings.value("Language").toString(); } void MainWindow::writeSettings() { QSettings settings(settingsPage->settingsFileName, QSettings::IniFormat); settings.beginGroup("MainWindow"); settings.setValue("size", size()); settings.setValue("pos", pos()); settings.setValue("fullScreen", isFullScreen()); settings.endGroup(); } void MainWindow::updateTsunami() { QProcess process; QString dir = QCoreApplication::applicationDirPath() + "/../"; process.start(dir+"/"+"Update.exe --checkForUpdate=https://tsunami.adunanza.net/releases/Releases/"); process.waitForFinished(); if(process.error() != QProcess::UnknownError) { qDebug() << "Error checking for updates"; return; } QProcess::startDetached(dir+"Update.exe --update=https://tsunami.adunanza.net/releases/Releases/"); } void MainWindow::loadLanguage(QString l) { if(l == "Italian") { bool load = t.load(":/languages/italian.qm"); qDebug() << "Load: " << load; } if(l != "English") { bool response = QCoreApplication::installTranslator(&t); qDebug() << "Response: " << response; } } void MainWindow::createTrayIcon() { // Tray icon m_systrayIcon = new QSystemTrayIcon(QIcon(":/images/logo_tsunami_tiny.ico"), this); //m_systrayIcon->setContextMenu(trayIconMenu()); connect(m_systrayIcon, SIGNAL(messageClicked()), this, SLOT(balloonClicked())); // End of Icon Menu connect(m_systrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(toggleVisibility(QSystemTrayIcon::ActivationReason))); m_systrayIcon->setToolTip(PROJECT " " VERSION); m_systrayIcon->show(); // m_systrayIcon->showMessage(PROJECT, "Welcome to the future!", QSystemTrayIcon::Information, TIME_TRAY_BALLOON); popupInfo("Welcome to the future!"); qDebug("started"); } void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) { qDebug("entered toggleVisibility"); if ((e == QSystemTrayIcon::Trigger) || (e == QSystemTrayIcon::DoubleClick)) { if (isHidden()) { /*if (m_uiLocked) { // Ask for UI lock password if (!unlockUI()) return; }*/ // Make sure the window is not minimized setWindowState(windowState() & (~Qt::WindowMinimized | Qt::WindowActive)); // Then show it show(); raise(); activateWindow(); } else { hide(); } } } void MainWindow::balloonClicked() { if (isHidden()) { /*if (m_uiLocked) { // Ask for UI lock password if (!unlockUI()) return; }*/ show(); if (isMinimized()) showNormal(); } raise(); activateWindow(); } void MainWindow::btnMenuClick() { QString btn = sender()->objectName(); ui->btnSettings->setHidden(btn == ui->btnSettings->objectName()); ui->btnUser->setHidden(btn == ui->btnUser->objectName()); ui->btnSearch->setHidden(btn == ui->btnSearch->objectName()); ui->btnDownload->setHidden(btn == ui->btnDownload->objectName()); ui->btnArchive->setHidden(btn == ui->btnArchive->objectName()); ui->btnStreaming->setHidden(btn == ui->btnStreaming->objectName()); ui->btnStatistics->setHidden(btn == ui->btnStatistics->objectName()); ui->btnSettings_on->setHidden(btn != ui->btnSettings->objectName()); ui->btnUser_on->setHidden(btn != ui->btnUser->objectName()); ui->btnSearch_on->setHidden(btn != ui->btnSearch->objectName()); ui->btnDownload_on->setHidden(btn != ui->btnDownload->objectName()); ui->btnArchive_on->setHidden(btn != ui->btnArchive->objectName()); ui->btnStreaming_on->setHidden(btn != ui->btnStreaming->objectName()); ui->btnStatistics_on->setHidden(btn != ui->btnStatistics->objectName()); settingsPage->setHidden(btn != ui->btnSettings->objectName()); searchPage->setHidden(btn != ui->btnSearch->objectName()); statisticsPage->setHidden(btn != ui->btnStatistics->objectName()); downloadPage->setHidden(btn != ui->btnDownload->objectName()); if (btn == ui->btnChat->objectName()) { QString link = "https://discordapp.com/invite/0pfzTOXuEjt9ifvF"; QDesktopServices::openUrl(QUrl(link)); } } void MainWindow::btnAddClick() { QFileDialog fd(this, tr("Select torrent"), settingsPage->getLastBrowsedDir(), tr("Torrents (*.torrent)")); QStringList fileNames = fd.getOpenFileNames(); if (fileNames.isEmpty()) return; settingsPage->setLastBrowsedDir(QFileInfo(fileNames.first()).absolutePath()); sessionManager->addItems(std::move(fileNames), settingsPage->getDownloadPath()); ui->btnDownload->released(); // switch to downloadpage } void MainWindow::popupInfo(const QString &msg) { m_systrayIcon->showMessage(PROJECT, msg, QSystemTrayIcon::Information, TIME_TRAY_BALLOON); } void MainWindow::closeEvent(QCloseEvent *event) { qDebug("closing"); statusLabel->setText("Saving resume data. Please wait."); writeSettings(); updateTsunami(); emit stopSessionManager(); event->accept(); } void MainWindow::changeEvent(QEvent *e) { if(e->type() == QEvent::LanguageChange) { qDebug() << "Intercepted LanguageChange event by MainWindow"; ui->retranslateUi(this); } QMainWindow::changeEvent(e); } <|endoftext|>
<commit_before>/** * @file LLNearbyChatHandler.cpp * @brief Nearby chat notification managment * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnearbychathandler.h" #include "llbottomtray.h" #include "llchatitemscontainerctrl.h" #include "llnearbychat.h" #include "llrecentpeople.h" #include "llviewercontrol.h" #include "llfloaterreg.h"//for LLFloaterReg::getTypedInstance #include "llviewerwindow.h"//for screen channel position //add LLNearbyChatHandler to LLNotificationsUI namespace using namespace LLNotificationsUI; //----------------------------------------------------------------------------------------------- //LLNearbyChatScreenChannel //----------------------------------------------------------------------------------------------- LLToastPanelBase* createToastPanel() { LLNearbyChatToastPanel* item = LLNearbyChatToastPanel::createInstance(); return item; } class LLNearbyChatScreenChannel: public LLScreenChannelBase { public: LLNearbyChatScreenChannel(const LLUUID& id):LLScreenChannelBase(id) { mStopProcessing = false;}; void addNotification (LLSD& notification); void arrangeToasts (); void showToastsBottom (); typedef boost::function<LLToastPanelBase* (void )> create_toast_panel_callback_t; void setCreatePanelCallback(create_toast_panel_callback_t value) { m_create_toast_panel_callback_t = value;} void onToastDestroyed (LLToast* toast); void onToastFade (LLToast* toast); void reshape (S32 width, S32 height, BOOL called_from_parent); void redrawToasts() { arrangeToasts(); } // hide all toasts from screen, but not remove them from a channel virtual void hideToastsFromScreen() { }; // removes all toasts from a channel virtual void removeToastsFromChannel() { for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { addToToastPool((*it)); } m_active_toasts.clear(); }; virtual void deleteAllChildren() { m_toast_pool.clear(); m_active_toasts.clear(); LLScreenChannelBase::deleteAllChildren(); } protected: void addToToastPool(LLToast* toast) { toast->setVisible(FALSE); toast->stopTimer(); toast->setIsHidden(true); m_toast_pool.push_back(toast); } void createOverflowToast(S32 bottom, F32 timer); create_toast_panel_callback_t m_create_toast_panel_callback_t; bool createPoolToast(); std::vector<LLToast*> m_active_toasts; std::list<LLToast*> m_toast_pool; bool mStopProcessing; }; void LLNearbyChatScreenChannel::createOverflowToast(S32 bottom, F32 timer) { //we don't need overflow toast in nearby chat } void LLNearbyChatScreenChannel::onToastDestroyed(LLToast* toast) { mStopProcessing = true; } void LLNearbyChatScreenChannel::onToastFade(LLToast* toast) { //fade mean we put toast to toast pool if(!toast) return; std::vector<LLToast*>::iterator pos = std::find(m_active_toasts.begin(),m_active_toasts.end(),toast); if(pos!=m_active_toasts.end()) m_active_toasts.erase(pos); addToToastPool(toast); arrangeToasts(); } bool LLNearbyChatScreenChannel::createPoolToast() { LLToastPanelBase* panel= m_create_toast_panel_callback_t(); if(!panel) return false; LLToast::Params p; p.panel = panel; p.lifetime_secs = gSavedSettings.getS32("NearbyToastLifeTime"); p.fading_time_secs = gSavedSettings.getS32("NearbyToastFadingTime"); LLToast* toast = new LLToast(p); toast->setOnFadeCallback(boost::bind(&LLNearbyChatScreenChannel::onToastFade, this, _1)); toast->setOnToastDestroyedCallback(boost::bind(&LLNearbyChatScreenChannel::onToastDestroyed, this, _1)); m_toast_pool.push_back(toast); return true; } void LLNearbyChatScreenChannel::addNotification(LLSD& notification) { //look in pool. if there is any message if(mStopProcessing) return; /* find last toast and check ID */ if(m_active_toasts.size()) { LLUUID fromID = notification["from_id"].asUUID(); // agent id or object id std::string from = notification["from"].asString(); LLToast* toast = m_active_toasts[0]; LLNearbyChatToastPanel* panel = dynamic_cast<LLNearbyChatToastPanel*>(toast->getPanel()); if(panel && panel->messageID() == fromID && panel->getFromName() == from && panel->canAddText()) { panel->addMessage(notification); toast->reshapeToPanel(); toast->resetTimer(); arrangeToasts(); return; } } if(m_toast_pool.empty()) { //"pool" is empty - create one more panel if(!createPoolToast())//created toast will go to pool. so next call will find it return; addNotification(notification); return; } int chat_type = notification["chat_type"].asInteger(); if( ((EChatType)chat_type == CHAT_TYPE_DEBUG_MSG)) { if(gSavedSettings.getBOOL("ShowScriptErrors") == FALSE) return; if(gSavedSettings.getS32("ShowScriptErrorsLocation")== 1) return; } //take 1st element from pool, (re)initialize it, put it in active toasts LLToast* toast = m_toast_pool.back(); m_toast_pool.pop_back(); LLToastPanelBase* panel = dynamic_cast<LLToastPanelBase*>(toast->getPanel()); if(!panel) return; panel->init(notification); toast->reshapeToPanel(); toast->resetTimer(); m_active_toasts.push_back(toast); arrangeToasts(); } void LLNearbyChatScreenChannel::arrangeToasts() { if(m_active_toasts.size() == 0 || isHovering()) return; hideToastsFromScreen(); showToastsBottom(); } int sort_toasts_predicate(LLToast* first,LLToast* second) { F32 v1 = first->getTimer()->getEventTimer().getElapsedTimeF32(); F32 v2 = second->getTimer()->getEventTimer().getElapsedTimeF32(); return v1 < v2; } void LLNearbyChatScreenChannel::showToastsBottom() { if(mStopProcessing) return; LLRect toast_rect; S32 bottom = getRect().mBottom; S32 margin = gSavedSettings.getS32("ToastGap"); //sort active toasts std::sort(m_active_toasts.begin(),m_active_toasts.end(),sort_toasts_predicate); //calc max visible item and hide other toasts. for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { S32 toast_top = bottom + (*it)->getRect().getHeight() + margin; if(toast_top > gFloaterView->getRect().getHeight()) { while(it!=m_active_toasts.end()) { addToToastPool((*it)); it=m_active_toasts.erase(it); } break; } LLToast* toast = (*it); toast_rect = toast->getRect(); toast_rect.setLeftTopAndSize(getRect().mLeft , bottom + toast_rect.getHeight(), toast_rect.getWidth() ,toast_rect.getHeight()); toast->setRect(toast_rect); bottom += toast_rect.getHeight() + margin; } // use reverse order to provide correct z-order and avoid toast blinking for(std::vector<LLToast*>::reverse_iterator it = m_active_toasts.rbegin(); it != m_active_toasts.rend(); ++it) { LLToast* toast = (*it); toast->setIsHidden(false); toast->setVisible(TRUE); } } void LLNearbyChatScreenChannel::reshape (S32 width, S32 height, BOOL called_from_parent) { LLScreenChannelBase::reshape(width, height, called_from_parent); arrangeToasts(); } //----------------------------------------------------------------------------------------------- //LLNearbyChatHandler //----------------------------------------------------------------------------------------------- LLNearbyChatHandler::LLNearbyChatHandler(e_notification_type type, const LLSD& id) { mType = type; // Getting a Channel for our notifications LLNearbyChatScreenChannel* channel = new LLNearbyChatScreenChannel(LLUUID(gSavedSettings.getString("NearByChatChannelUUID"))); LLNearbyChatScreenChannel::create_toast_panel_callback_t callback = createToastPanel; channel->setCreatePanelCallback(callback); mChannel = LLChannelManager::getInstance()->addChannel(channel); } LLNearbyChatHandler::~LLNearbyChatHandler() { } void LLNearbyChatHandler::initChannel() { LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); LLView* chat_box = LLBottomTray::getInstance()->getChildView("chat_box"); S32 channel_right_bound = nearby_chat->getRect().mRight; mChannel->init(chat_box->getRect().mLeft, channel_right_bound); } void LLNearbyChatHandler::processChat(const LLChat& chat_msg, const LLSD &args) { if(chat_msg.mMuted == TRUE) return; if(chat_msg.mSourceType == CHAT_SOURCE_AGENT && chat_msg.mFromID.notNull()) LLRecentPeople::instance().add(chat_msg.mFromID); if(chat_msg.mText.empty()) return;//don't process empty messages LLChat& tmp_chat = const_cast<LLChat&>(chat_msg); LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); { //sometimes its usefull to have no name at all... //if(tmp_chat.mFromName.empty() && tmp_chat.mFromID!= LLUUID::null) // tmp_chat.mFromName = tmp_chat.mFromID.asString(); } nearby_chat->addMessage(chat_msg, true, args); if( nearby_chat->getVisible() || ( chat_msg.mSourceType == CHAT_SOURCE_AGENT && gSavedSettings.getBOOL("UseChatBubbles") ) ) return;//no need in toast if chat is visible or if bubble chat is enabled // Handle irc styled messages for toast panel if (tmp_chat.mChatStyle == CHAT_STYLE_IRC) { if(!tmp_chat.mFromName.empty()) tmp_chat.mText = tmp_chat.mFromName + tmp_chat.mText.substr(3); else tmp_chat.mText = tmp_chat.mText.substr(3); } // arrange a channel on a screen if(!mChannel->getVisible()) { initChannel(); } /* //comment all this due to EXT-4432 ..may clean up after some time... //only messages from AGENTS if(CHAT_SOURCE_OBJECT == chat_msg.mSourceType) { if(chat_msg.mChatType == CHAT_TYPE_DEBUG_MSG) return;//ok for now we don't skip messeges from object, so skip only debug messages } */ LLUUID id; id.generate(); LLNearbyChatScreenChannel* channel = dynamic_cast<LLNearbyChatScreenChannel*>(mChannel); if(channel) { LLSD notification; notification["id"] = id; notification["message"] = chat_msg.mText; notification["from"] = chat_msg.mFromName; notification["from_id"] = chat_msg.mFromID; notification["time"] = chat_msg.mTime; notification["source"] = (S32)chat_msg.mSourceType; notification["chat_type"] = (S32)chat_msg.mChatType; notification["chat_style"] = (S32)chat_msg.mChatStyle; std::string r_color_name = "White"; F32 r_color_alpha = 1.0f; LLViewerChat::getChatColor( chat_msg, r_color_name, r_color_alpha); notification["text_color"] = r_color_name; notification["color_alpha"] = r_color_alpha; notification["font_size"] = (S32)LLViewerChat::getChatFontSize() ; channel->addNotification(notification); } } void LLNearbyChatHandler::onDeleteToast(LLToast* toast) { } <commit_msg>EXT-7534 FIX add toast wrapping pannel padding<commit_after>/** * @file LLNearbyChatHandler.cpp * @brief Nearby chat notification managment * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnearbychathandler.h" #include "llbottomtray.h" #include "llchatitemscontainerctrl.h" #include "llnearbychat.h" #include "llrecentpeople.h" #include "llviewercontrol.h" #include "llfloaterreg.h"//for LLFloaterReg::getTypedInstance #include "llviewerwindow.h"//for screen channel position //add LLNearbyChatHandler to LLNotificationsUI namespace using namespace LLNotificationsUI; //----------------------------------------------------------------------------------------------- //LLNearbyChatScreenChannel //----------------------------------------------------------------------------------------------- LLToastPanelBase* createToastPanel() { LLNearbyChatToastPanel* item = LLNearbyChatToastPanel::createInstance(); return item; } class LLNearbyChatScreenChannel: public LLScreenChannelBase { public: LLNearbyChatScreenChannel(const LLUUID& id):LLScreenChannelBase(id) { mStopProcessing = false;}; void addNotification (LLSD& notification); void arrangeToasts (); void showToastsBottom (); typedef boost::function<LLToastPanelBase* (void )> create_toast_panel_callback_t; void setCreatePanelCallback(create_toast_panel_callback_t value) { m_create_toast_panel_callback_t = value;} void onToastDestroyed (LLToast* toast); void onToastFade (LLToast* toast); void reshape (S32 width, S32 height, BOOL called_from_parent); void redrawToasts() { arrangeToasts(); } // hide all toasts from screen, but not remove them from a channel virtual void hideToastsFromScreen() { }; // removes all toasts from a channel virtual void removeToastsFromChannel() { for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { addToToastPool((*it)); } m_active_toasts.clear(); }; virtual void deleteAllChildren() { m_toast_pool.clear(); m_active_toasts.clear(); LLScreenChannelBase::deleteAllChildren(); } protected: void addToToastPool(LLToast* toast) { toast->setVisible(FALSE); toast->stopTimer(); toast->setIsHidden(true); m_toast_pool.push_back(toast); } void createOverflowToast(S32 bottom, F32 timer); create_toast_panel_callback_t m_create_toast_panel_callback_t; bool createPoolToast(); std::vector<LLToast*> m_active_toasts; std::list<LLToast*> m_toast_pool; bool mStopProcessing; }; void LLNearbyChatScreenChannel::createOverflowToast(S32 bottom, F32 timer) { //we don't need overflow toast in nearby chat } void LLNearbyChatScreenChannel::onToastDestroyed(LLToast* toast) { mStopProcessing = true; } void LLNearbyChatScreenChannel::onToastFade(LLToast* toast) { //fade mean we put toast to toast pool if(!toast) return; std::vector<LLToast*>::iterator pos = std::find(m_active_toasts.begin(),m_active_toasts.end(),toast); if(pos!=m_active_toasts.end()) m_active_toasts.erase(pos); addToToastPool(toast); arrangeToasts(); } bool LLNearbyChatScreenChannel::createPoolToast() { LLToastPanelBase* panel= m_create_toast_panel_callback_t(); if(!panel) return false; LLToast::Params p; p.panel = panel; p.lifetime_secs = gSavedSettings.getS32("NearbyToastLifeTime"); p.fading_time_secs = gSavedSettings.getS32("NearbyToastFadingTime"); LLToast* toast = new LLToast(p); toast->setOnFadeCallback(boost::bind(&LLNearbyChatScreenChannel::onToastFade, this, _1)); toast->setOnToastDestroyedCallback(boost::bind(&LLNearbyChatScreenChannel::onToastDestroyed, this, _1)); m_toast_pool.push_back(toast); return true; } void LLNearbyChatScreenChannel::addNotification(LLSD& notification) { //look in pool. if there is any message if(mStopProcessing) return; /* find last toast and check ID */ if(m_active_toasts.size()) { LLUUID fromID = notification["from_id"].asUUID(); // agent id or object id std::string from = notification["from"].asString(); LLToast* toast = m_active_toasts[0]; LLNearbyChatToastPanel* panel = dynamic_cast<LLNearbyChatToastPanel*>(toast->getPanel()); if(panel && panel->messageID() == fromID && panel->getFromName() == from && panel->canAddText()) { panel->addMessage(notification); toast->reshapeToPanel(); toast->resetTimer(); arrangeToasts(); return; } } if(m_toast_pool.empty()) { //"pool" is empty - create one more panel if(!createPoolToast())//created toast will go to pool. so next call will find it return; addNotification(notification); return; } int chat_type = notification["chat_type"].asInteger(); if( ((EChatType)chat_type == CHAT_TYPE_DEBUG_MSG)) { if(gSavedSettings.getBOOL("ShowScriptErrors") == FALSE) return; if(gSavedSettings.getS32("ShowScriptErrorsLocation")== 1) return; } //take 1st element from pool, (re)initialize it, put it in active toasts LLToast* toast = m_toast_pool.back(); m_toast_pool.pop_back(); LLToastPanelBase* panel = dynamic_cast<LLToastPanelBase*>(toast->getPanel()); if(!panel) return; panel->init(notification); toast->reshapeToPanel(); toast->resetTimer(); m_active_toasts.push_back(toast); arrangeToasts(); } void LLNearbyChatScreenChannel::arrangeToasts() { if(m_active_toasts.size() == 0 || isHovering()) return; hideToastsFromScreen(); showToastsBottom(); } int sort_toasts_predicate(LLToast* first,LLToast* second) { F32 v1 = first->getTimer()->getEventTimer().getElapsedTimeF32(); F32 v2 = second->getTimer()->getEventTimer().getElapsedTimeF32(); return v1 < v2; } void LLNearbyChatScreenChannel::showToastsBottom() { if(mStopProcessing) return; LLRect toast_rect; S32 bottom = getRect().mBottom; S32 margin = gSavedSettings.getS32("ToastGap"); //sort active toasts std::sort(m_active_toasts.begin(),m_active_toasts.end(),sort_toasts_predicate); //calc max visible item and hide other toasts. for(std::vector<LLToast*>::iterator it = m_active_toasts.begin(); it != m_active_toasts.end(); ++it) { S32 toast_top = bottom + (*it)->getRect().getHeight() + margin; if(toast_top > gFloaterView->getRect().getHeight()) { while(it!=m_active_toasts.end()) { addToToastPool((*it)); it=m_active_toasts.erase(it); } break; } LLToast* toast = (*it); toast_rect = toast->getRect(); toast_rect.setLeftTopAndSize(getRect().mLeft , bottom + toast_rect.getHeight(), toast_rect.getWidth() ,toast_rect.getHeight()); toast->setRect(toast_rect); bottom += toast_rect.getHeight() - toast->getTopPad() + margin; } // use reverse order to provide correct z-order and avoid toast blinking for(std::vector<LLToast*>::reverse_iterator it = m_active_toasts.rbegin(); it != m_active_toasts.rend(); ++it) { LLToast* toast = (*it); toast->setIsHidden(false); toast->setVisible(TRUE); } } void LLNearbyChatScreenChannel::reshape (S32 width, S32 height, BOOL called_from_parent) { LLScreenChannelBase::reshape(width, height, called_from_parent); arrangeToasts(); } //----------------------------------------------------------------------------------------------- //LLNearbyChatHandler //----------------------------------------------------------------------------------------------- LLNearbyChatHandler::LLNearbyChatHandler(e_notification_type type, const LLSD& id) { mType = type; // Getting a Channel for our notifications LLNearbyChatScreenChannel* channel = new LLNearbyChatScreenChannel(LLUUID(gSavedSettings.getString("NearByChatChannelUUID"))); LLNearbyChatScreenChannel::create_toast_panel_callback_t callback = createToastPanel; channel->setCreatePanelCallback(callback); mChannel = LLChannelManager::getInstance()->addChannel(channel); } LLNearbyChatHandler::~LLNearbyChatHandler() { } void LLNearbyChatHandler::initChannel() { LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); LLView* chat_box = LLBottomTray::getInstance()->getChildView("chat_box"); S32 channel_right_bound = nearby_chat->getRect().mRight; mChannel->init(chat_box->getRect().mLeft, channel_right_bound); } void LLNearbyChatHandler::processChat(const LLChat& chat_msg, const LLSD &args) { if(chat_msg.mMuted == TRUE) return; if(chat_msg.mSourceType == CHAT_SOURCE_AGENT && chat_msg.mFromID.notNull()) LLRecentPeople::instance().add(chat_msg.mFromID); if(chat_msg.mText.empty()) return;//don't process empty messages LLChat& tmp_chat = const_cast<LLChat&>(chat_msg); LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD()); { //sometimes its usefull to have no name at all... //if(tmp_chat.mFromName.empty() && tmp_chat.mFromID!= LLUUID::null) // tmp_chat.mFromName = tmp_chat.mFromID.asString(); } nearby_chat->addMessage(chat_msg, true, args); if( nearby_chat->getVisible() || ( chat_msg.mSourceType == CHAT_SOURCE_AGENT && gSavedSettings.getBOOL("UseChatBubbles") ) ) return;//no need in toast if chat is visible or if bubble chat is enabled // Handle irc styled messages for toast panel if (tmp_chat.mChatStyle == CHAT_STYLE_IRC) { if(!tmp_chat.mFromName.empty()) tmp_chat.mText = tmp_chat.mFromName + tmp_chat.mText.substr(3); else tmp_chat.mText = tmp_chat.mText.substr(3); } // arrange a channel on a screen if(!mChannel->getVisible()) { initChannel(); } /* //comment all this due to EXT-4432 ..may clean up after some time... //only messages from AGENTS if(CHAT_SOURCE_OBJECT == chat_msg.mSourceType) { if(chat_msg.mChatType == CHAT_TYPE_DEBUG_MSG) return;//ok for now we don't skip messeges from object, so skip only debug messages } */ LLUUID id; id.generate(); LLNearbyChatScreenChannel* channel = dynamic_cast<LLNearbyChatScreenChannel*>(mChannel); if(channel) { LLSD notification; notification["id"] = id; notification["message"] = chat_msg.mText; notification["from"] = chat_msg.mFromName; notification["from_id"] = chat_msg.mFromID; notification["time"] = chat_msg.mTime; notification["source"] = (S32)chat_msg.mSourceType; notification["chat_type"] = (S32)chat_msg.mChatType; notification["chat_style"] = (S32)chat_msg.mChatStyle; std::string r_color_name = "White"; F32 r_color_alpha = 1.0f; LLViewerChat::getChatColor( chat_msg, r_color_name, r_color_alpha); notification["text_color"] = r_color_name; notification["color_alpha"] = r_color_alpha; notification["font_size"] = (S32)LLViewerChat::getChatFontSize() ; channel->addNotification(notification); } } void LLNearbyChatHandler::onDeleteToast(LLToast* toast) { } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QObject> #include <QtWidgets> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), mainWindowIcon(":/Resources/icons/mainWindowIcon.jpg"), isPlaying(false), prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"), playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"), playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"), nextButtonIcon(":/Resources/icons/Button-Next-icon.png"), _player(0), _playlist(this) { ui->setupUi(this); setWindowIcon(mainWindowIcon); setWindowTitle("Music Player"); setFixedWidth(5*72); setFixedHeight(3*72); /****************SETTING UP MENUS*********************/ QWidget *topFiller = new QWidget; topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); #ifdef Q_OS_SYMBIAN infoLabel = new QLabel(tr("<i>Choose a menu option</i>")); #else infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to " "invoke a context menu</i>")); #endif infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); infoLabel->setAlignment(Qt::AlignCenter); QWidget *bottomFiller = new QWidget; bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(5); layout->addWidget(topFiller); layout->addWidget(infoLabel); layout->addWidget(bottomFiller); createActions(); createMenus(); /************SETTING UP STATUS BAR********************/ #ifndef Q_OS_SYMBIAN QString message = tr("A context menu is available by right-clicking"); statusBar()->showMessage(message); #endif /*****************SETTING UP BUTTONS******************/ const int mediaButtonYCoordinate = ( (height() + layout->geometry().height())- ((width()/5) + statusBar()->geometry().height() - 8) ); /*************SETTING UP PREV BUTTON******************/ connect(&prevButton, SIGNAL(clicked()), this, SLOT(prevButtonIsPressed())); prevButton.setParent(this); prevButton.setGeometry ( 0, mediaButtonYCoordinate, width()/5, width()/5 ); prevButton.setIcon(prevButtonIcon); prevButton.setIconSize(QSize(prevButton.height(),prevButton.height())); prevButton.show(); /*************SETTING UP PLAY BUTTON******************/ connect(&playButton, SIGNAL(clicked()), this, SLOT(playButtonIsPressed())); playButton.setParent(this); playButton.setGeometry ( prevButton.width()*2, mediaButtonYCoordinate, width()/5, width()/5 ); playButton.setIcon(playButtonPlayIcon); playButton.setIconSize(QSize(playButton.height(),playButton.height())); playButton.show(); /*************SETTING UP NEXT BUTTON******************/ connect(&nextButton, SIGNAL(clicked()), this, SLOT(nextButtonIsPressed())); nextButton.setParent(this); nextButton.setGeometry ( playButton.width()*4, mediaButtonYCoordinate, width()/5, width()/5 ); nextButton.setIcon(nextButtonIcon); nextButton.setIconSize(QSize(nextButton.height(),nextButton.height())); nextButton.show(); /*************SETTING UP VOLUME SLIDER******************/ volumeLabel = new QLabel; volumeLabel->setText(tr("<b>Volume:</b>")); volumeLabel->setParent(this); volumeSlider = new QSlider(Qt::Horizontal); volumeSlider->setParent(this); volumeSlider->setMinimum(0); volumeSlider->setMaximum(100); volumeSlider->setSingleStep(10); volumeSlider->setGeometry ( nextButton.geometry().x(), mediaButtonYCoordinate-20, playButton.width(), 20 ); volumeLabel->setGeometry ( volumeSlider->geometry().x()-60, volumeSlider->geometry().y(), 60, volumeSlider->height() ); volumeLabel->show(); volumeSlider->show(); /******************SOUND CODE******************/ _player = new QMediaPlayer; _player->setMedia(QUrl::fromLocalFile("/home/dustin/CS/MusicPlayer/cs372-FinalProject/test.mp3")); _player->setVolume(100); } MainWindow::~MainWindow() { delete ui; } void MainWindow::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(playAct); menu.addAction(nextSongAct); menu.addAction(previousSongAct); menu.exec(event->globalPos()); } void MainWindow::play() { playButtonIsPressed(); } void MainWindow::nextSong() { nextButtonIsPressed(); } void MainWindow::previousSong() { prevButtonIsPressed(); } void MainWindow::open() { QFileDialog openFileDialog(this); openFileDialog.setNameFilter(tr("Audio (*.mp3 *.mp4 *.wav *.flac *.ogg)")); openFileDialog.setViewMode(QFileDialog::List); openFileDialog.setFileMode(QFileDialog::ExistingFiles); QStringList fileNames; if(openFileDialog.exec()) fileNames = openFileDialog.selectedFiles(); QList<QMediaContent> playListFiles; for(QStringList::iterator file = fileNames.begin(); file < fileNames.end(); file++) playListFiles.append(QMediaContent(QUrl::fromLocalFile(*file))); _playlist.clear(); _playlist.addMedia(playListFiles); _player->stop(); _player->setPlaylist(&_playlist); _player->setPosition(1); } void MainWindow::about() { infoLabel->setText(tr("Invoked <b>Help|About</b>")); QMessageBox::about(this, tr("About Menu"), tr("Hit Play to Play Mooxzikz. " "Open to Open More Moozikz.")); //TODO: docoomentimgz } void MainWindow::aboutQt() { infoLabel->setText(tr("Invoked <b>Help|About Qt</b>")); } void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setStatusTip(tr("Open an existing file")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); exitAct = new QAction(tr("E&xit"), this); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); playAct = new QAction(tr("&Play/Pause"), this); playAct->setStatusTip(tr("Play a song")); connect(playAct, SIGNAL(triggered()), this, SLOT(play())); nextSongAct = new QAction(tr("&Next Song"), this); nextSongAct->setStatusTip(tr("Switches to the Next Song")); connect(nextSongAct, SIGNAL(triggered()), this, SLOT(nextSong())); previousSongAct = new QAction(tr("&Previous Song"), this); previousSongAct->setStatusTip(tr("Switches to the Previous Song")); connect(previousSongAct, SIGNAL(triggered()), this, SLOT(previousSong())); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); playMenu = menuBar()->addMenu(tr("&Play")); playMenu->addSeparator(); playMenu->addAction(playAct); playMenu->addAction(nextSongAct); playMenu->addAction(previousSongAct); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } <commit_msg>Took out hard path so no more changing<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QObject> #include <QtWidgets> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), mainWindowIcon(":/Resources/icons/mainWindowIcon.jpg"), isPlaying(false), prevButtonIcon(":/Resources/icons/Button-Prev-icon.png"), playButtonPlayIcon(":/Resources/icons/Button-Play-icon.png"), playButtonPauseIcon(":/Resources/icons/Button-Pause-icon.png"), nextButtonIcon(":/Resources/icons/Button-Next-icon.png"), _player(0), _playlist(this) { ui->setupUi(this); setWindowIcon(mainWindowIcon); setWindowTitle("Music Player"); setFixedWidth(5*72); setFixedHeight(3*72); /****************SETTING UP MENUS*********************/ QWidget *topFiller = new QWidget; topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); #ifdef Q_OS_SYMBIAN infoLabel = new QLabel(tr("<i>Choose a menu option</i>")); #else infoLabel = new QLabel(tr("<i>Choose a menu option, or right-click to " "invoke a context menu</i>")); #endif infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); infoLabel->setAlignment(Qt::AlignCenter); QWidget *bottomFiller = new QWidget; bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(5); layout->addWidget(topFiller); layout->addWidget(infoLabel); layout->addWidget(bottomFiller); createActions(); createMenus(); /************SETTING UP STATUS BAR********************/ #ifndef Q_OS_SYMBIAN QString message = tr("A context menu is available by right-clicking"); statusBar()->showMessage(message); #endif /*****************SETTING UP BUTTONS******************/ const int mediaButtonYCoordinate = ( (height() + layout->geometry().height())- ((width()/5) + statusBar()->geometry().height() - 8) ); /*************SETTING UP PREV BUTTON******************/ connect(&prevButton, SIGNAL(clicked()), this, SLOT(prevButtonIsPressed())); prevButton.setParent(this); prevButton.setGeometry ( 0, mediaButtonYCoordinate, width()/5, width()/5 ); prevButton.setIcon(prevButtonIcon); prevButton.setIconSize(QSize(prevButton.height(),prevButton.height())); prevButton.show(); /*************SETTING UP PLAY BUTTON******************/ connect(&playButton, SIGNAL(clicked()), this, SLOT(playButtonIsPressed())); playButton.setParent(this); playButton.setGeometry ( prevButton.width()*2, mediaButtonYCoordinate, width()/5, width()/5 ); playButton.setIcon(playButtonPlayIcon); playButton.setIconSize(QSize(playButton.height(),playButton.height())); playButton.show(); /*************SETTING UP NEXT BUTTON******************/ connect(&nextButton, SIGNAL(clicked()), this, SLOT(nextButtonIsPressed())); nextButton.setParent(this); nextButton.setGeometry ( playButton.width()*4, mediaButtonYCoordinate, width()/5, width()/5 ); nextButton.setIcon(nextButtonIcon); nextButton.setIconSize(QSize(nextButton.height(),nextButton.height())); nextButton.show(); /*************SETTING UP VOLUME SLIDER******************/ volumeLabel = new QLabel; volumeLabel->setText(tr("<b>Volume:</b>")); volumeLabel->setParent(this); volumeSlider = new QSlider(Qt::Horizontal); volumeSlider->setParent(this); volumeSlider->setMinimum(0); volumeSlider->setMaximum(100); volumeSlider->setSingleStep(10); volumeSlider->setGeometry ( nextButton.geometry().x(), mediaButtonYCoordinate-20, playButton.width(), 20 ); volumeLabel->setGeometry ( volumeSlider->geometry().x()-60, volumeSlider->geometry().y(), 60, volumeSlider->height() ); volumeLabel->show(); volumeSlider->show(); /******************SOUND CODE******************/ _player = new QMediaPlayer; // _player->setMedia(QUrl::fromLocalFile()); _player->setVolume(100); } MainWindow::~MainWindow() { delete ui; } void MainWindow::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(playAct); menu.addAction(nextSongAct); menu.addAction(previousSongAct); menu.exec(event->globalPos()); } void MainWindow::play() { playButtonIsPressed(); } void MainWindow::nextSong() { nextButtonIsPressed(); } void MainWindow::previousSong() { prevButtonIsPressed(); } void MainWindow::open() { QFileDialog openFileDialog(this); openFileDialog.setNameFilter(tr("Audio (*.mp3 *.mp4 *.wav *.flac *.ogg)")); openFileDialog.setViewMode(QFileDialog::List); openFileDialog.setFileMode(QFileDialog::ExistingFiles); QStringList fileNames; if(openFileDialog.exec()) fileNames = openFileDialog.selectedFiles(); QList<QMediaContent> playListFiles; for(QStringList::iterator file = fileNames.begin(); file < fileNames.end(); file++) playListFiles.append(QMediaContent(QUrl::fromLocalFile(*file))); _playlist.clear(); _playlist.addMedia(playListFiles); _player->stop(); _player->setPlaylist(&_playlist); _player->setPosition(1); } void MainWindow::about() { infoLabel->setText(tr("Invoked <b>Help|About</b>")); QMessageBox::about(this, tr("About Menu"), tr("Hit Play to Play Mooxzikz. " "Open to Open More Moozikz.")); //TODO: docoomentimgz } void MainWindow::aboutQt() { infoLabel->setText(tr("Invoked <b>Help|About Qt</b>")); } void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setStatusTip(tr("Open an existing file")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); exitAct = new QAction(tr("E&xit"), this); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); playAct = new QAction(tr("&Play/Pause"), this); playAct->setStatusTip(tr("Play a song")); connect(playAct, SIGNAL(triggered()), this, SLOT(play())); nextSongAct = new QAction(tr("&Next Song"), this); nextSongAct->setStatusTip(tr("Switches to the Next Song")); connect(nextSongAct, SIGNAL(triggered()), this, SLOT(nextSong())); previousSongAct = new QAction(tr("&Previous Song"), this); previousSongAct->setStatusTip(tr("Switches to the Previous Song")); connect(previousSongAct, SIGNAL(triggered()), this, SLOT(previousSong())); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(aboutQtAct, SIGNAL(triggered()), this, SLOT(aboutQt())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); playMenu = menuBar()->addMenu(tr("&Play")); playMenu->addSeparator(); playMenu->addAction(playAct); playMenu->addAction(nextSongAct); playMenu->addAction(previousSongAct); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } <|endoftext|>
<commit_before>#include <iterator> #include <stdexcept> #include <string> #include <vector> #include <QByteArray> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QRegExp> #include <QSettings> #include <QString> #include <QStringList> #include <QTableWidgetItem> #include <QTextStream> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkCookie> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> #include <QUrl> #include <QVariant> #include "mainwindow.hpp" #include "sfcsv/sfcsv.h" #include "ui_mainwindow.h" static QString parseImdbId(const QString& text) { static const QRegExp imdbIdRx("ur([0-9]{7,8})"); if(imdbIdRx.indexIn(text) == -1) { return {}; } return imdbIdRx.cap(1); } static QString parseListId(const QString& text) { static const QRegExp listIdRx("ls([0-9]{9})"); if(listIdRx.indexIn(text) == -1) { return {}; } return listIdRx.cap(1); } static QStringList parseCsv(const QString& in) { QStringList result; std::vector<std::string> parsed; const std::string line = in.toStdString(); sfcsv::parse_line(line, std::back_inserter(parsed), ','); for(auto&& res : parsed) { result.append(QString::fromStdString(res)); } return result; } static QList<QNetworkCookie> parseCookies(const QString& cookies) { QList<QNetworkCookie> result; const QStringList pairs = cookies.split("; "); if(pairs.size() == 1) { return {}; } for(const QString& pair : pairs) { const QStringList kv = pair.split("="); if(kv.size() == 1) { return {}; } QByteArray key, value; key.append(kv.at(0)); value.append(kv.at(1)); const QNetworkCookie cookie(key, value); result.append(cookie); } return result; } static QStringList parseFile(const QString& in) { QStringList results; QFile inFile(in); if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) { throw std::runtime_error("Unable to open file"); } QTextStream stream(&inFile); stream.setCodec("UTF-8"); while(!stream.atEnd()) { const QString line = stream.readLine().remove("\n"); results << line; } return results; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), netManager(new QNetworkAccessManager), config("IMDbDownloaderConfig.ini", QSettings::IniFormat) { ui->setupUi(this); connect(netManager.get(), SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply*))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionOpen_triggered() { const QString openedFile = QFileDialog::getOpenFileName(this, tr("Open..."), config.value("last_csv").toString()); if(openedFile.isEmpty()) { return; } config.setValue("last_csv", openedFile); const QStringList lines = parseFile(openedFile); const QString header = lines.first(); const QStringList headerParsed = parseCsv(header); ui->plainTextLog->clear(); ui->tableCsv->clear(); ui->tableCsv->setColumnCount(headerParsed.size() + 1); ui->tableCsv->setHorizontalHeaderLabels(QStringList() << "List Name" << "URL" << "Status"); ui->tableCsv->setRowCount(lines.size()); for(int row = 0; row < lines.size(); ++row) { const QStringList columns = parseCsv(lines.at(row)); const QString username = columns.at(0); const QString url = columns.at(1); ui->tableCsv->setItem(row, 0, new QTableWidgetItem(username)); ui->tableCsv->setItem(row, 1, new QTableWidgetItem(url)); ui->tableCsv->setItem(row, 2, new QTableWidgetItem("Waiting")); const QString urlId = parseUrlId(url); QString requestUrl; if(ui->radioRatings->isChecked()) { // IMDb ratings requestUrl = QString("http://www.imdb.com/list/export?list_id=ratings&author_id=ur%1").arg(urlId); } else { // IMDb lists requestUrl = QString("http://www.imdb.com/list/export?list_id=ls%1&author_id=ur27588704").arg(urlId); } if(!requestUrl.isEmpty()) { requests.append(QNetworkRequest(requestUrl)); } qDebug() << "Added" << username << url << requestUrl; } ui->plainTextLog->appendPlainText(tr("Enqueued %1 URLs").arg(requests.size())); } void MainWindow::networkReplyFinished(QNetworkReply *reply) { // Remove highlight from current const int row = findItemRow(parseUrlId(reply->url().toDisplayString())); if(reply->error()) { setRowColor(row, QColor(Qt::red)); setRowStatus(row, tr("Failed. Retrying...")); // Enqueue the request requests.append(QNetworkRequest(reply->url())); // Start another request nextRequest(); return; } setRowStatus(row, tr("Saved")); setRowColor(row, QColor(Qt::green)); const QString url = reply->url().toDisplayString(); const QString data = reply->readAll(); // Find who this imdb id belongs to const QString imdbId = parseUrlId(url); if(row != -1) { const QString username = ui->tableCsv->item(row, 0)->text().trimmed(); QFile out(QString("%1/%2.csv").arg(config.value("save_to").toString()).arg(username)); out.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream stream(&out); stream.setCodec("UTF-8"); stream << data; } reply->deleteLater(); // Start another request nextRequest(); } void MainWindow::on_buttonDownload_clicked() { const QString savePath = QFileDialog::getExistingDirectory(this, tr("Save to..."), config.value("save_to").toString()); if(savePath.isEmpty()) { return; } config.setValue("save_to", savePath); for(int i = 0, last = ui->spinBoxSimReqs->value(); i < last; ++i) { nextRequest(); } } void MainWindow::on_buttonLoadCookies_clicked() { const QString openedFile = QFileDialog::getOpenFileName(this, tr("Cookies"), config.value("last_cookies").toString()); if(openedFile.isEmpty()) { return; } config.setValue("last_cookies", openedFile); QFile in(openedFile); if(!in.open(QIODevice::ReadOnly | QIODevice::Text)) { ui->plainTextLog->appendPlainText(tr("Failed to open cookies file. Insufficient permissions?")); return; } const QString cookies = in.readAll(); netCookies = parseCookies(cookies); if(netCookies.empty()) { ui->plainTextLog->appendPlainText(tr("Invalid cookie format")); return; } ui->plainTextLog->appendPlainText(tr("Loaded cookies.")); } void MainWindow::nextRequest() { if(requests.empty()) { return; } QVariant cookieVar; cookieVar.setValue(netCookies); // Makes sure files are only overwritten if explicitly specified // or to request files that do not exist while(!requests.empty()) { QNetworkRequest req = requests.takeFirst(); req.setHeader(QNetworkRequest::CookieHeader, cookieVar); const QUrl url = req.url(); const int row = findItemRow(parseUrlId(url.toDisplayString())); const QString username = ui->tableCsv->item(row, 0)->text(); const QString savePath = QString("%1/%2.csv").arg(config.value("save_to").toString()).arg(username); if(ui->checkBoxOverwrite->isChecked() || !QFile::exists(savePath)) { // Highlight current setRowColor(row, QColor(Qt::yellow)); setRowStatus(row, tr("Downloading")); netManager->get(req); break; } else { setRowStatus(row, tr("Skipped")); } } } int MainWindow::findItemRow(const QString& imdbId) const { int foundRow = -1; const auto users = ui->tableCsv->rowCount(); for(int row = 0; row < users; ++row) { auto current = ui->tableCsv->item(row, 1); const QString imdbUrl = current->text(); const QString userImdbId = parseUrlId(imdbUrl); if(imdbId == userImdbId) { foundRow = ui->tableCsv->row(current); break; } } return foundRow; } QString MainWindow::parseUrlId(const QString& url) const { QString id; if(ui->radioRatings->isChecked()) { id = parseImdbId(url); } else { id = parseListId(url); } return id; } void MainWindow::setRowStatus(const int row, const QString& status) { ui->tableCsv->item(row, 2)->setText(status); } void MainWindow::setRowColor(const int row, const QColor& color) { const QBrush brush(color); for(int column = 0, last = ui->tableCsv->columnCount(); column < last; ++column) { ui->tableCsv->item(row, column)->setBackground(brush); } } <commit_msg>Newlines (minor refactoring)<commit_after>#include <iterator> #include <stdexcept> #include <string> #include <vector> #include <QByteArray> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QRegExp> #include <QSettings> #include <QString> #include <QStringList> #include <QTableWidgetItem> #include <QTextStream> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkCookie> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> #include <QUrl> #include <QVariant> #include "mainwindow.hpp" #include "sfcsv/sfcsv.h" #include "ui_mainwindow.h" static QString parseImdbId(const QString& text) { static const QRegExp imdbIdRx("ur([0-9]{7,8})"); if(imdbIdRx.indexIn(text) == -1) { return {}; } return imdbIdRx.cap(1); } static QString parseListId(const QString& text) { static const QRegExp listIdRx("ls([0-9]{9})"); if(listIdRx.indexIn(text) == -1) { return {}; } return listIdRx.cap(1); } static QStringList parseCsv(const QString& in) { QStringList result; std::vector<std::string> parsed; const std::string line = in.toStdString(); sfcsv::parse_line(line, std::back_inserter(parsed), ','); for(auto&& res : parsed) { result.append(QString::fromStdString(res)); } return result; } static QList<QNetworkCookie> parseCookies(const QString& cookies) { QList<QNetworkCookie> result; const QStringList pairs = cookies.split("; "); if(pairs.size() == 1) { return {}; } for(const QString& pair : pairs) { const QStringList kv = pair.split("="); if(kv.size() == 1) { return {}; } QByteArray key, value; key.append(kv.at(0)); value.append(kv.at(1)); const QNetworkCookie cookie(key, value); result.append(cookie); } return result; } static QStringList parseFile(const QString& in) { QStringList results; QFile inFile(in); if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) { throw std::runtime_error("Unable to open file"); } QTextStream stream(&inFile); stream.setCodec("UTF-8"); while(!stream.atEnd()) { const QString line = stream.readLine().remove("\n"); results << line; } return results; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), netManager(new QNetworkAccessManager), config("IMDbDownloaderConfig.ini", QSettings::IniFormat) { ui->setupUi(this); connect(netManager.get(), SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply*))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionOpen_triggered() { const QString openedFile = QFileDialog::getOpenFileName(this, tr("Open..."), config.value("last_csv").toString()); if(openedFile.isEmpty()) { return; } config.setValue("last_csv", openedFile); const QStringList lines = parseFile(openedFile); const QString header = lines.first(); const QStringList headerParsed = parseCsv(header); ui->plainTextLog->clear(); ui->tableCsv->clear(); ui->tableCsv->setColumnCount(headerParsed.size() + 1); ui->tableCsv->setHorizontalHeaderLabels(QStringList() << "List Name" << "URL" << "Status"); ui->tableCsv->setRowCount(lines.size()); for(int row = 0; row < lines.size(); ++row) { const QStringList columns = parseCsv(lines.at(row)); const QString username = columns.at(0); const QString url = columns.at(1); ui->tableCsv->setItem(row, 0, new QTableWidgetItem(username)); ui->tableCsv->setItem(row, 1, new QTableWidgetItem(url)); ui->tableCsv->setItem(row, 2, new QTableWidgetItem("Waiting")); const QString urlId = parseUrlId(url); QString requestUrl; if(ui->radioRatings->isChecked()) { // IMDb ratings requestUrl = QString("http://www.imdb.com/list/export?list_id=ratings&author_id=ur%1").arg(urlId); } else { // IMDb lists requestUrl = QString("http://www.imdb.com/list/export?list_id=ls%1&author_id=ur27588704").arg(urlId); } if(!requestUrl.isEmpty()) { requests.append(QNetworkRequest(requestUrl)); } qDebug() << "Added" << username << url << requestUrl; } ui->plainTextLog->appendPlainText(tr("Enqueued %1 URLs").arg(requests.size())); } void MainWindow::networkReplyFinished(QNetworkReply *reply) { // Remove highlight from current const int row = findItemRow(parseUrlId(reply->url().toDisplayString())); if(reply->error()) { setRowColor(row, QColor(Qt::red)); setRowStatus(row, tr("Failed. Retrying...")); // Enqueue the request requests.append(QNetworkRequest(reply->url())); // Start another request nextRequest(); return; } setRowStatus(row, tr("Saved")); setRowColor(row, QColor(Qt::green)); const QString url = reply->url().toDisplayString(); const QString data = reply->readAll(); // Find who this imdb id belongs to const QString imdbId = parseUrlId(url); if(row != -1) { const QString username = ui->tableCsv->item(row, 0)->text().trimmed(); QFile out(QString("%1/%2.csv").arg(config.value("save_to").toString()).arg(username)); out.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream stream(&out); stream.setCodec("UTF-8"); stream << data; } reply->deleteLater(); // Start another request nextRequest(); } void MainWindow::on_buttonDownload_clicked() { const QString savePath = QFileDialog::getExistingDirectory(this, tr("Save to..."), config.value("save_to").toString()); if(savePath.isEmpty()) { return; } config.setValue("save_to", savePath); for(int i = 0, last = ui->spinBoxSimReqs->value(); i < last; ++i) { nextRequest(); } } void MainWindow::on_buttonLoadCookies_clicked() { const QString openedFile = QFileDialog::getOpenFileName(this, tr("Cookies"), config.value("last_cookies").toString()); if(openedFile.isEmpty()) { return; } config.setValue("last_cookies", openedFile); QFile in(openedFile); if(!in.open(QIODevice::ReadOnly | QIODevice::Text)) { ui->plainTextLog->appendPlainText(tr("Failed to open cookies file. Insufficient permissions?")); return; } const QString cookies = in.readAll(); netCookies = parseCookies(cookies); if(netCookies.empty()) { ui->plainTextLog->appendPlainText(tr("Invalid cookie format")); return; } ui->plainTextLog->appendPlainText(tr("Loaded cookies.")); } void MainWindow::nextRequest() { if(requests.empty()) { return; } QVariant cookieVar; cookieVar.setValue(netCookies); // Makes sure files are only overwritten if explicitly specified // or to request files that do not exist while(!requests.empty()) { QNetworkRequest req = requests.takeFirst(); req.setHeader(QNetworkRequest::CookieHeader, cookieVar); const QUrl url = req.url(); const int row = findItemRow(parseUrlId(url.toDisplayString())); const QString username = ui->tableCsv->item(row, 0)->text(); const QString savePath = QString("%1/%2.csv").arg(config.value("save_to").toString()).arg(username); if(ui->checkBoxOverwrite->isChecked() || !QFile::exists(savePath)) { // Highlight current setRowColor(row, QColor(Qt::yellow)); setRowStatus(row, tr("Downloading")); netManager->get(req); break; } else { setRowStatus(row, tr("Skipped")); } } } int MainWindow::findItemRow(const QString& imdbId) const { int foundRow = -1; const auto users = ui->tableCsv->rowCount(); for(int row = 0; row < users; ++row) { auto current = ui->tableCsv->item(row, 1); const QString imdbUrl = current->text(); const QString userImdbId = parseUrlId(imdbUrl); if(imdbId == userImdbId) { foundRow = ui->tableCsv->row(current); break; } } return foundRow; } QString MainWindow::parseUrlId(const QString& url) const { QString id; if(ui->radioRatings->isChecked()) { id = parseImdbId(url); } else { id = parseListId(url); } return id; } void MainWindow::setRowStatus(const int row, const QString& status) { ui->tableCsv->item(row, 2)->setText(status); } void MainWindow::setRowColor(const int row, const QColor& color) { const QBrush brush(color); for(int column = 0, last = ui->tableCsv->columnCount(); column < last; ++column) { ui->tableCsv->item(row, column)->setBackground(brush); } } <|endoftext|>
<commit_before>AliAnalysisTask *AddTask_dsekihat_lowmass_PbPb( Bool_t getFromAlien = kFALSE, TString cFileName = "Config_dsekihat_lowmass_PbPb.C", TString lFileName = "LMEECutLib_dsekihat.C", TString calibFileName = "", UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral, const Int_t CenMin = 0, const Int_t CenMax = 10, const Int_t Nmix = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const TString outname = "LMEE.root" ) { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_dsekihat_lowmass_PbPb", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; //TString configBasePath= "./"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",lFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + cFileName); TString libFilePath(configBasePath + lFileName); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; //create task and add it to the manager (MB) AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_Cen%d_%d_%s",CenMin,CenMax,triggername.Data())); task->UsePhysicsSelection(kTRUE); task->SetTriggerMask(trigger); //add dielectron analysis with different cuts to the task gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); //const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") ); const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()")); const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") ); THnF *hs_mean_TPC_El = 0x0; THnF *hs_width_TPC_El = 0x0; THnF *hs_mean_ITS_El = 0x0; THnF *hs_width_ITS_El = 0x0; THnF *hs_mean_TOF_El = 0x0; THnF *hs_width_TOF_El = 0x0; THnF *hs_mean_TPC_Pi = 0x0; THnF *hs_width_TPC_Pi = 0x0; TFile *rootfile = 0x0; if(calibFileName != ""){ printf("reading : %s for PID calibration\n",calibFileName.Data()); rootfile = TFile::Open(calibFileName,"READ"); hs_mean_TPC_El = (THnF*)rootfile->Get("hs_mean_TPC_El"); hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El"); hs_mean_ITS_El = (THnF*)rootfile->Get("hs_mean_ITS_El"); hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El"); hs_mean_TOF_El = (THnF*)rootfile->Get("hs_mean_TOF_El"); hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El"); hs_mean_TPC_Pi = (THnF*)rootfile->Get("hs_mean_TPC_Pi"); hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi"); } for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipid=0; ipid<nPID; ++ipid){ for (Int_t ipf=0; ipf<nPF; ++ipf){ AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_dsekihat_lowmass_PbPb(%d,%d,%d,%f,%f,%f,%f)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax))); if(!diel) continue; //AliDielectronVarCuts* centCuts = new AliDielectronVarCuts("centCuts",Form("kPbPb%02d%02d",CenMin,CenMax)); //centCuts->AddCut(AliDielectronVarManager::kCentralityNew, (Float_t)CenMin, (Float_t)CenMax); //diel->GetEventFilter().AddCuts(centCuts); //if(calibFileName!=""){ if(rootfile && rootfile->IsOpen()){ diel->SetPIDCaibinPU(kTRUE); //for electron diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); //for pion diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); } TString name = diel->GetName(); if(name.Contains("PIDCalib",TString::kIgnoreCase) || name.Contains("noPID",TString::kIgnoreCase)){ printf("No event mixing handler for post PID calibration/noPID\n"); } else{ printf("Add event mixing handler\n"); AliDielectronMixingHandler *mix = new AliDielectronMixingHandler; mix->SetMixType(AliDielectronMixingHandler::kAll); mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10."); mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101"); mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000"); mix->SetDepth(Nmix); diel->SetMixingHandler(mix); } task->AddDielectron(diel); }//pre-filter loop }//PID loop }//track cut loop //if(rootfile && rootfile->IsOpen()) rootfile->Close(); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 mgr->AddTask(task); //const TString outputFileName = AliAnalysisManager::GetCommonFileName(); const TString outputFileName = outname; //const TString dirname = Form("PWGDQ_LMEE_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()); //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("Tree_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TTree::Class(), AliAnalysisManager::kExchangeContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer(Form("Histos_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer(Form("CF_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer(Form("EventStat_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TH1D::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; } <commit_msg>update AddTask for MC<commit_after>AliAnalysisTask *AddTask_dsekihat_lowmass_PbPb( Bool_t getFromAlien = kFALSE, TString cFileName = "Config_dsekihat_lowmass_PbPb.C", TString lFileName = "LMEECutLib_dsekihat.C", TString calibFileName = "", UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral, const Int_t CenMin = 0, const Int_t CenMax = 10, const Int_t Nmix = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const TString outname = "LMEE.root", const Bool_t isMC = kFALSE ) { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_dsekihat_lowmass_PbPb", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; //TString configBasePath= "./"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",lFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + cFileName); TString libFilePath(configBasePath + lFileName); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; //create task and add it to the manager (MB) AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_Cen%d_%d_%s",CenMin,CenMax,triggername.Data())); task->UsePhysicsSelection(kTRUE); task->SetTriggerMask(trigger); //add dielectron analysis with different cuts to the task gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); //const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") ); const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()")); const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") ); THnF *hs_mean_TPC_El = 0x0; THnF *hs_width_TPC_El = 0x0; THnF *hs_mean_ITS_El = 0x0; THnF *hs_width_ITS_El = 0x0; THnF *hs_mean_TOF_El = 0x0; THnF *hs_width_TOF_El = 0x0; THnF *hs_mean_TPC_Pi = 0x0; THnF *hs_width_TPC_Pi = 0x0; TFile *rootfile = 0x0; if(calibFileName != ""){ printf("reading : %s for PID calibration\n",calibFileName.Data()); rootfile = TFile::Open(calibFileName,"READ"); hs_mean_TPC_El = (THnF*)rootfile->Get("hs_mean_TPC_El"); hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El"); hs_mean_ITS_El = (THnF*)rootfile->Get("hs_mean_ITS_El"); hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El"); hs_mean_TOF_El = (THnF*)rootfile->Get("hs_mean_TOF_El"); hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El"); hs_mean_TPC_Pi = (THnF*)rootfile->Get("hs_mean_TPC_Pi"); hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi"); } for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipid=0; ipid<nPID; ++ipid){ for (Int_t ipf=0; ipf<nPF; ++ipf){ AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_dsekihat_lowmass_PbPb(%d,%d,%d,%f,%f,%f,%f,%d)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax,isMC))); if(!diel) continue; TString name = diel->GetName(); //if(calibFileName!=""){ if(rootfile && rootfile->IsOpen()){ diel->SetPIDCaibinPU(kTRUE); //for electron diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); //for pion diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta,AliDielectronVarManager::kNclsITS1,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM); } if(name.Contains("PIDCalib",TString::kIgnoreCase) || name.Contains("noPID",TString::kIgnoreCase)){ printf("No event mixing handler for post PID calibration/noPID\n"); } else{ printf("Add event mixing handler\n"); AliDielectronMixingHandler *mix = new AliDielectronMixingHandler; mix->SetMixType(AliDielectronMixingHandler::kAll); mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10."); mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101"); mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000"); mix->SetDepth(Nmix); if(!isMC) diel->SetMixingHandler(mix); } task->AddDielectron(diel); }//pre-filter loop }//PID loop }//track cut loop //if(rootfile && rootfile->IsOpen()) rootfile->Close(); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 mgr->AddTask(task); //const TString outputFileName = AliAnalysisManager::GetCommonFileName(); const TString outputFileName = outname; //const TString dirname = Form("PWGDQ_LMEE_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()); //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("Tree_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TTree::Class(), AliAnalysisManager::kExchangeContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer(Form("Histos_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer(Form("CF_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer(Form("EventStat_dsekihat_Cen%d_%d_%s",CenMin,CenMax,triggername.Data()), TH1D::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; } <|endoftext|>
<commit_before>// // Copyright (C) 2015 Greg Landrum and NextMove Software // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <string.h> #include <string> #include <GraphMol/RDKitBase.h> #include <GraphMol/GraphMol.h> #include <GraphMol/MonomerInfo.h> namespace RDKit { static char getOneLetterCode(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': if (!strcmp(ptr,"ALA")) return 'A'; if (!strcmp(ptr,"ARG")) return 'R'; if (!strcmp(ptr,"ASN")) return 'N'; if (!strcmp(ptr,"ASP")) return 'D'; break; case 'C': if (!strcmp(ptr,"CYS")) return 'C'; break; case 'D': if (!strcmp(ptr,"DAL")) return 'a'; if (!strcmp(ptr,"DAR")) return 'r'; if (!strcmp(ptr,"DAS")) return 'd'; if (!strcmp(ptr,"DCY")) return 'c'; if (!strcmp(ptr,"DGL")) return 'e'; if (!strcmp(ptr,"DGN")) return 'q'; if (!strcmp(ptr,"DHI")) return 'h'; if (!strcmp(ptr,"DIL")) return 'i'; if (!strcmp(ptr,"DLE")) return 'l'; if (!strcmp(ptr,"DLY")) return 'k'; if (!strcmp(ptr,"DPN")) return 'f'; if (!strcmp(ptr,"DPR")) return 'p'; if (!strcmp(ptr,"DSG")) return 'n'; if (!strcmp(ptr,"DSN")) return 's'; if (!strcmp(ptr,"DTH")) return 't'; if (!strcmp(ptr,"DTR")) return 'w'; if (!strcmp(ptr,"DTY")) return 'y'; if (!strcmp(ptr,"DVA")) return 'v'; break; case 'G': if (!strcmp(ptr,"GLU")) return 'E'; if (!strcmp(ptr,"GLN")) return 'Q'; if (!strcmp(ptr,"GLY")) return 'G'; break; case 'H': if (!strcmp(ptr,"HIS")) return 'H'; break; case 'I': if (!strcmp(ptr,"ILE")) return 'I'; break; case 'L': if (!strcmp(ptr,"LEU")) return 'L'; if (!strcmp(ptr,"LYS")) return 'K'; break; case 'M': if (!strcmp(ptr,"MET")) return 'M'; if (!strcmp(ptr,"MED")) return 'm'; break; case 'P': if (!strcmp(ptr,"PHE")) return 'F'; if (!strcmp(ptr,"PRO")) return 'P'; break; case 'S': if (!strcmp(ptr,"SER")) return 'S'; break; case 'T': if (!strcmp(ptr,"THR")) return 'T'; if (!strcmp(ptr,"TRP")) return 'W'; if (!strcmp(ptr,"TYR")) return 'Y'; break; case 'V': if (!strcmp(ptr,"VAL")) return 'V'; break; } return 'X'; } std::string MolToSequence(const ROMol &mol) { std::string result; for (ROMol::ConstAtomIterator atomIt=mol.beginAtoms(); atomIt!=mol.endAtoms();++atomIt){ const Atom *atom = *atomIt; AtomPDBResidueInfo *info = (AtomPDBResidueInfo*)(atom->getMonomerInfo()); if (info && info->getMonomerType()==AtomMonomerInfo::PDBRESIDUE && info->getName() == " CA ") { result += getOneLetterCode(info); } } return result; } std::string MolToFASTA(const ROMol &mol) { std::string seq = MolToSequence(mol); if (seq.empty()) return ""; std::string result = ">"; std::string name; if (mol.getPropIfPresent(common_properties::_Name,name)) result += name; result += '\n'; result += seq; result += '\n'; return result; } static const char *getHELMMonomer(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': if (!strcmp(ptr,"ALA")) return "A"; if (!strcmp(ptr,"ARG")) return "R"; if (!strcmp(ptr,"ASN")) return "N"; if (!strcmp(ptr,"ASP")) return "D"; break; case 'C': if (!strcmp(ptr,"CYS")) return "C"; break; case 'D': if (!strcmp(ptr,"DAL")) return "[dA]"; if (!strcmp(ptr,"DAR")) return "[dR]"; if (!strcmp(ptr,"DAS")) return "[dD]"; if (!strcmp(ptr,"DCY")) return "[dC]"; if (!strcmp(ptr,"DGL")) return "[dE]"; if (!strcmp(ptr,"DGN")) return "[dQ]"; if (!strcmp(ptr,"DHI")) return "[dH]"; if (!strcmp(ptr,"DLE")) return "[dL]"; if (!strcmp(ptr,"DLY")) return "[dK]"; if (!strcmp(ptr,"DPN")) return "[dF]"; if (!strcmp(ptr,"DPR")) return "[dP]"; if (!strcmp(ptr,"DSG")) return "[dN]"; if (!strcmp(ptr,"DSN")) return "[dS]"; if (!strcmp(ptr,"DTR")) return "[dW]"; if (!strcmp(ptr,"DTY")) return "[dY]"; if (!strcmp(ptr,"DVA")) return "[dV]"; break; case 'G': if (!strcmp(ptr,"GLU")) return "E"; if (!strcmp(ptr,"GLN")) return "Q"; if (!strcmp(ptr,"GLY")) return "G"; break; case 'H': if (!strcmp(ptr,"HIS")) return "H"; break; case 'I': if (!strcmp(ptr,"ILE")) return "I"; break; case 'L': if (!strcmp(ptr,"LEU")) return "L"; if (!strcmp(ptr,"LYS")) return "K"; break; case 'M': if (!strcmp(ptr,"MET")) return "M"; if (!strcmp(ptr,"MED")) return "[dM]"; if (!strcmp(ptr,"MSE")) return "[seC]"; break; case 'N': if (!strcmp(ptr,"NLE")) return "[Nle]"; if (!strcmp(ptr,"NVA")) return "[Nva]"; break; case 'O': if (!strcmp(ptr,"ORN")) return "[Orn]"; break; case 'P': if (!strcmp(ptr,"PHE")) return "F"; if (!strcmp(ptr,"PRO")) return "P"; break; case 'S': if (!strcmp(ptr,"SER")) return "S"; break; case 'T': if (!strcmp(ptr,"THR")) return "T"; if (!strcmp(ptr,"TRP")) return "W"; if (!strcmp(ptr,"TYR")) return "Y"; break; case 'V': if (!strcmp(ptr,"VAL")) return "V"; break; } return (const char*)0; } static bool IsEupeptideBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { if (src->getChainId() != dst->getChainId()) return false; int sresno = src->getResidueNumber(); int dresno = dst->getResidueNumber(); if (src->getName() == " C " && dst->getName() == " N ") { if (sresno != dresno) return dresno > sresno; return dst->getInsertionCode() > src->getInsertionCode(); } if (src->getName() == " N " && dst->getName() == " C ") { if (sresno != dresno) return dresno < sresno; return dst->getInsertionCode() < src->getInsertionCode(); } return false; } static bool IsSupportedHELMBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { if (src->getName()==" SG " && dst->getName()==" SG ") { if ((src->getResidueName()=="CYS" || src->getResidueName()=="DCY") && (dst->getResidueName()=="CYS" || dst->getResidueName()=="DCY")) return true; } if (src->getName()==" N " && dst->getName()==" C ") return true; if (src->getName()==" C " && dst->getName()==" N ") return true; #if 0 printf("%s%d%s.%s - %s%d%s.%s\n", src->getResidueName().c_str(),src->getResidueNumber(), src->getChainId().c_str(),src->getName().c_str(), dst->getResidueName().c_str(),dst->getResidueNumber(), dst->getChainId().c_str(),dst->getName().c_str()); #endif return false; } static bool FindHELMAtom(std::vector<AtomPDBResidueInfo*> *seq, AtomPDBResidueInfo *info, std::string &id, std::string &pos) { char buffer[32]; char ch; const char *ptr = info->getName().c_str(); if (ptr[0]==' ' && ptr[1]=='S' && ptr[2]=='G' && ptr[3]==' ') ch = '3'; else if (ptr[0]==' ' && ptr[1]=='N' && ptr[2]==' ' && ptr[3]==' ') ch = '1'; else if (ptr[0]==' ' && ptr[1]=='C' && ptr[2]==' ' && ptr[3]==' ') ch = '2'; else return false; int resno = info->getResidueNumber(); for (unsigned int i=1; i<10; i++) { unsigned int len = (unsigned int)seq[i].size(); for (unsigned int j=0; j<len; j++) { AtomPDBResidueInfo *targ = seq[i][j]; if (targ->getResidueNumber() == resno && targ->getResidueName() == info->getResidueName() && targ->getChainId() == info->getChainId() && targ->getInsertionCode() == info->getInsertionCode()) { id = "PEPTIDE"; id += (char)(i+'0'); sprintf(buffer,"%u:R%c",j+1,ch); pos = buffer; return true; } } } return false; } static std::string NameHELMBond(std::vector<AtomPDBResidueInfo*> *seq, AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { std::string id1,pos1; if (!FindHELMAtom(seq,src,id1,pos1)) return ""; std::string id2,pos2; if (!FindHELMAtom(seq,dst,id2,pos2)) return ""; std::string result = id1; result += ','; result += id2; result += ','; result += pos1; result += '-'; result += pos2; return result; } std::string MolToHELM(const ROMol &mol) { std::vector<AtomPDBResidueInfo*> seq[10]; std::string result; bool first = true; std::string chain; int id = 1; /* First pass: Monomers */ for (ROMol::ConstAtomIterator atomIt=mol.beginAtoms(); atomIt!=mol.endAtoms();++atomIt){ const Atom *atom = *atomIt; AtomPDBResidueInfo *info = (AtomPDBResidueInfo*)(atom->getMonomerInfo()); // We can only write HELM if all atoms have PDB residue information if (!info || info->getMonomerType()!=AtomMonomerInfo::PDBRESIDUE) return ""; if (info->getName() == " CA ") { const char *mono = getHELMMonomer(info); if (!mono) return ""; if (first) { chain = info->getChainId(); result = "PEPTIDE1{"; first = false; } else if (info->getChainId() != chain) { // Nine chains should be enough? if (id == 9) return ""; id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id+'0'); result += "{"; } else result += "."; result += mono; seq[id].push_back(info); } else if (info->getResidueName() == "NH2" && info->getName() == " N ") { if (first) return ""; result += ".[am]"; } else if (info->getResidueName() == "ACE" && info->getName() == " C ") { if (first) { chain = info->getChainId(); result = "PEPTIDE1{[ac]"; first = false; } else if (info->getChainId() != chain) { // Nine chains should be enough? if (id == 9) return ""; id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id+'0'); result += "{[ac]"; } else return ""; seq[id].push_back(info); } } if (first) return ""; result += "}$"; first = true; for (ROMol::ConstBondIterator bondIt=mol.beginBonds(); bondIt!=mol.endBonds(); ++bondIt){ const Bond *bond = *bondIt; Atom *beg = bond->getBeginAtom(); Atom *end = bond->getEndAtom(); if (!beg || !end) continue; AtomPDBResidueInfo *binfo = (AtomPDBResidueInfo*)(beg->getMonomerInfo()); AtomPDBResidueInfo *einfo = (AtomPDBResidueInfo*)(end->getMonomerInfo()); if (!binfo || !einfo) continue; // Test if this is an uninteresting intra-residue bond if (binfo->getResidueNumber() == einfo->getResidueNumber() && binfo->getResidueName() == einfo->getResidueName() && binfo->getChainId() == einfo->getChainId() && binfo->getInsertionCode() == einfo->getInsertionCode()) continue; if (bond->getBondType() != Bond::SINGLE) return ""; if (IsEupeptideBond(binfo,einfo)) continue; if (!IsSupportedHELMBond(binfo,einfo)) return ""; std::string tmp = NameHELMBond(seq,binfo,einfo); if (tmp.empty()) return ""; if (!first) result += "|"; else first = false; result += tmp; } result += "$$$"; return result; } } // namespace RDKit <commit_msg>Fixes sprintf not found on some gcc compiles<commit_after>// // Copyright (C) 2015 Greg Landrum and NextMove Software // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <string.h> #include <stdio.h> #include <string> #include <GraphMol/RDKitBase.h> #include <GraphMol/GraphMol.h> #include <GraphMol/MonomerInfo.h> namespace RDKit { static char getOneLetterCode(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': if (!strcmp(ptr,"ALA")) return 'A'; if (!strcmp(ptr,"ARG")) return 'R'; if (!strcmp(ptr,"ASN")) return 'N'; if (!strcmp(ptr,"ASP")) return 'D'; break; case 'C': if (!strcmp(ptr,"CYS")) return 'C'; break; case 'D': if (!strcmp(ptr,"DAL")) return 'a'; if (!strcmp(ptr,"DAR")) return 'r'; if (!strcmp(ptr,"DAS")) return 'd'; if (!strcmp(ptr,"DCY")) return 'c'; if (!strcmp(ptr,"DGL")) return 'e'; if (!strcmp(ptr,"DGN")) return 'q'; if (!strcmp(ptr,"DHI")) return 'h'; if (!strcmp(ptr,"DIL")) return 'i'; if (!strcmp(ptr,"DLE")) return 'l'; if (!strcmp(ptr,"DLY")) return 'k'; if (!strcmp(ptr,"DPN")) return 'f'; if (!strcmp(ptr,"DPR")) return 'p'; if (!strcmp(ptr,"DSG")) return 'n'; if (!strcmp(ptr,"DSN")) return 's'; if (!strcmp(ptr,"DTH")) return 't'; if (!strcmp(ptr,"DTR")) return 'w'; if (!strcmp(ptr,"DTY")) return 'y'; if (!strcmp(ptr,"DVA")) return 'v'; break; case 'G': if (!strcmp(ptr,"GLU")) return 'E'; if (!strcmp(ptr,"GLN")) return 'Q'; if (!strcmp(ptr,"GLY")) return 'G'; break; case 'H': if (!strcmp(ptr,"HIS")) return 'H'; break; case 'I': if (!strcmp(ptr,"ILE")) return 'I'; break; case 'L': if (!strcmp(ptr,"LEU")) return 'L'; if (!strcmp(ptr,"LYS")) return 'K'; break; case 'M': if (!strcmp(ptr,"MET")) return 'M'; if (!strcmp(ptr,"MED")) return 'm'; break; case 'P': if (!strcmp(ptr,"PHE")) return 'F'; if (!strcmp(ptr,"PRO")) return 'P'; break; case 'S': if (!strcmp(ptr,"SER")) return 'S'; break; case 'T': if (!strcmp(ptr,"THR")) return 'T'; if (!strcmp(ptr,"TRP")) return 'W'; if (!strcmp(ptr,"TYR")) return 'Y'; break; case 'V': if (!strcmp(ptr,"VAL")) return 'V'; break; } return 'X'; } std::string MolToSequence(const ROMol &mol) { std::string result; for (ROMol::ConstAtomIterator atomIt=mol.beginAtoms(); atomIt!=mol.endAtoms();++atomIt){ const Atom *atom = *atomIt; AtomPDBResidueInfo *info = (AtomPDBResidueInfo*)(atom->getMonomerInfo()); if (info && info->getMonomerType()==AtomMonomerInfo::PDBRESIDUE && info->getName() == " CA ") { result += getOneLetterCode(info); } } return result; } std::string MolToFASTA(const ROMol &mol) { std::string seq = MolToSequence(mol); if (seq.empty()) return ""; std::string result = ">"; std::string name; if (mol.getPropIfPresent(common_properties::_Name,name)) result += name; result += '\n'; result += seq; result += '\n'; return result; } static const char *getHELMMonomer(const AtomPDBResidueInfo *info) { const char *ptr = info->getResidueName().c_str(); switch (ptr[0]) { case 'A': if (!strcmp(ptr,"ALA")) return "A"; if (!strcmp(ptr,"ARG")) return "R"; if (!strcmp(ptr,"ASN")) return "N"; if (!strcmp(ptr,"ASP")) return "D"; break; case 'C': if (!strcmp(ptr,"CYS")) return "C"; break; case 'D': if (!strcmp(ptr,"DAL")) return "[dA]"; if (!strcmp(ptr,"DAR")) return "[dR]"; if (!strcmp(ptr,"DAS")) return "[dD]"; if (!strcmp(ptr,"DCY")) return "[dC]"; if (!strcmp(ptr,"DGL")) return "[dE]"; if (!strcmp(ptr,"DGN")) return "[dQ]"; if (!strcmp(ptr,"DHI")) return "[dH]"; if (!strcmp(ptr,"DLE")) return "[dL]"; if (!strcmp(ptr,"DLY")) return "[dK]"; if (!strcmp(ptr,"DPN")) return "[dF]"; if (!strcmp(ptr,"DPR")) return "[dP]"; if (!strcmp(ptr,"DSG")) return "[dN]"; if (!strcmp(ptr,"DSN")) return "[dS]"; if (!strcmp(ptr,"DTR")) return "[dW]"; if (!strcmp(ptr,"DTY")) return "[dY]"; if (!strcmp(ptr,"DVA")) return "[dV]"; break; case 'G': if (!strcmp(ptr,"GLU")) return "E"; if (!strcmp(ptr,"GLN")) return "Q"; if (!strcmp(ptr,"GLY")) return "G"; break; case 'H': if (!strcmp(ptr,"HIS")) return "H"; break; case 'I': if (!strcmp(ptr,"ILE")) return "I"; break; case 'L': if (!strcmp(ptr,"LEU")) return "L"; if (!strcmp(ptr,"LYS")) return "K"; break; case 'M': if (!strcmp(ptr,"MET")) return "M"; if (!strcmp(ptr,"MED")) return "[dM]"; if (!strcmp(ptr,"MSE")) return "[seC]"; break; case 'N': if (!strcmp(ptr,"NLE")) return "[Nle]"; if (!strcmp(ptr,"NVA")) return "[Nva]"; break; case 'O': if (!strcmp(ptr,"ORN")) return "[Orn]"; break; case 'P': if (!strcmp(ptr,"PHE")) return "F"; if (!strcmp(ptr,"PRO")) return "P"; break; case 'S': if (!strcmp(ptr,"SER")) return "S"; break; case 'T': if (!strcmp(ptr,"THR")) return "T"; if (!strcmp(ptr,"TRP")) return "W"; if (!strcmp(ptr,"TYR")) return "Y"; break; case 'V': if (!strcmp(ptr,"VAL")) return "V"; break; } return (const char*)0; } static bool IsEupeptideBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { if (src->getChainId() != dst->getChainId()) return false; int sresno = src->getResidueNumber(); int dresno = dst->getResidueNumber(); if (src->getName() == " C " && dst->getName() == " N ") { if (sresno != dresno) return dresno > sresno; return dst->getInsertionCode() > src->getInsertionCode(); } if (src->getName() == " N " && dst->getName() == " C ") { if (sresno != dresno) return dresno < sresno; return dst->getInsertionCode() < src->getInsertionCode(); } return false; } static bool IsSupportedHELMBond(AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { if (src->getName()==" SG " && dst->getName()==" SG ") { if ((src->getResidueName()=="CYS" || src->getResidueName()=="DCY") && (dst->getResidueName()=="CYS" || dst->getResidueName()=="DCY")) return true; } if (src->getName()==" N " && dst->getName()==" C ") return true; if (src->getName()==" C " && dst->getName()==" N ") return true; #if 0 printf("%s%d%s.%s - %s%d%s.%s\n", src->getResidueName().c_str(),src->getResidueNumber(), src->getChainId().c_str(),src->getName().c_str(), dst->getResidueName().c_str(),dst->getResidueNumber(), dst->getChainId().c_str(),dst->getName().c_str()); #endif return false; } static bool FindHELMAtom(std::vector<AtomPDBResidueInfo*> *seq, AtomPDBResidueInfo *info, std::string &id, std::string &pos) { char buffer[32]; char ch; const char *ptr = info->getName().c_str(); if (ptr[0]==' ' && ptr[1]=='S' && ptr[2]=='G' && ptr[3]==' ') ch = '3'; else if (ptr[0]==' ' && ptr[1]=='N' && ptr[2]==' ' && ptr[3]==' ') ch = '1'; else if (ptr[0]==' ' && ptr[1]=='C' && ptr[2]==' ' && ptr[3]==' ') ch = '2'; else return false; int resno = info->getResidueNumber(); for (unsigned int i=1; i<10; i++) { unsigned int len = (unsigned int)seq[i].size(); for (unsigned int j=0; j<len; j++) { AtomPDBResidueInfo *targ = seq[i][j]; if (targ->getResidueNumber() == resno && targ->getResidueName() == info->getResidueName() && targ->getChainId() == info->getChainId() && targ->getInsertionCode() == info->getInsertionCode()) { id = "PEPTIDE"; id += (char)(i+'0'); sprintf(buffer,"%u:R%c",j+1,ch); pos = buffer; return true; } } } return false; } static std::string NameHELMBond(std::vector<AtomPDBResidueInfo*> *seq, AtomPDBResidueInfo *src, AtomPDBResidueInfo *dst) { std::string id1,pos1; if (!FindHELMAtom(seq,src,id1,pos1)) return ""; std::string id2,pos2; if (!FindHELMAtom(seq,dst,id2,pos2)) return ""; std::string result = id1; result += ','; result += id2; result += ','; result += pos1; result += '-'; result += pos2; return result; } std::string MolToHELM(const ROMol &mol) { std::vector<AtomPDBResidueInfo*> seq[10]; std::string result; bool first = true; std::string chain; int id = 1; /* First pass: Monomers */ for (ROMol::ConstAtomIterator atomIt=mol.beginAtoms(); atomIt!=mol.endAtoms();++atomIt){ const Atom *atom = *atomIt; AtomPDBResidueInfo *info = (AtomPDBResidueInfo*)(atom->getMonomerInfo()); // We can only write HELM if all atoms have PDB residue information if (!info || info->getMonomerType()!=AtomMonomerInfo::PDBRESIDUE) return ""; if (info->getName() == " CA ") { const char *mono = getHELMMonomer(info); if (!mono) return ""; if (first) { chain = info->getChainId(); result = "PEPTIDE1{"; first = false; } else if (info->getChainId() != chain) { // Nine chains should be enough? if (id == 9) return ""; id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id+'0'); result += "{"; } else result += "."; result += mono; seq[id].push_back(info); } else if (info->getResidueName() == "NH2" && info->getName() == " N ") { if (first) return ""; result += ".[am]"; } else if (info->getResidueName() == "ACE" && info->getName() == " C ") { if (first) { chain = info->getChainId(); result = "PEPTIDE1{[ac]"; first = false; } else if (info->getChainId() != chain) { // Nine chains should be enough? if (id == 9) return ""; id++; chain = info->getChainId(); result += "}|PEPTIDE"; result += (char)(id+'0'); result += "{[ac]"; } else return ""; seq[id].push_back(info); } } if (first) return ""; result += "}$"; first = true; for (ROMol::ConstBondIterator bondIt=mol.beginBonds(); bondIt!=mol.endBonds(); ++bondIt){ const Bond *bond = *bondIt; Atom *beg = bond->getBeginAtom(); Atom *end = bond->getEndAtom(); if (!beg || !end) continue; AtomPDBResidueInfo *binfo = (AtomPDBResidueInfo*)(beg->getMonomerInfo()); AtomPDBResidueInfo *einfo = (AtomPDBResidueInfo*)(end->getMonomerInfo()); if (!binfo || !einfo) continue; // Test if this is an uninteresting intra-residue bond if (binfo->getResidueNumber() == einfo->getResidueNumber() && binfo->getResidueName() == einfo->getResidueName() && binfo->getChainId() == einfo->getChainId() && binfo->getInsertionCode() == einfo->getInsertionCode()) continue; if (bond->getBondType() != Bond::SINGLE) return ""; if (IsEupeptideBond(binfo,einfo)) continue; if (!IsSupportedHELMBond(binfo,einfo)) return ""; std::string tmp = NameHELMBond(seq,binfo,einfo); if (tmp.empty()) return ""; if (!first) result += "|"; else first = false; result += tmp; } result += "$$$"; return result; } } // namespace RDKit <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <iterator> #include <vector> #define Iterator typename #define Functor typename template <Iterator Iterator_t, Functor Functor_t> class ConditionalIterator { public: bool operator==(ConditionalIterator<Iterator_t, Functor_t> that) const { return iterator_ == that.iterator_; } bool operator!=(ConditionalIterator<Iterator_t, Functor_t> that) const { return iterator_ != that.iterator_; } ConditionalIterator<Iterator_t, Functor_t>& operator++() { if (iterator_ == end_) return *this; ++iterator_; while (iterator_ != end_ && !f_(*(iterator_))) { ++iterator_; } return *this; } ConditionalIterator(Iterator_t iterator, Iterator_t end, Functor_t f) : iterator_(iterator), end_(end), f_(f) { while (iterator_ != end_ && !f_(*iterator_)) { ++iterator_; } } private: Iterator_t iterator_; Iterator_t end_; Functor_t f_; public: auto operator*() const -> decltype(*iterator_) { return *iterator_; } }; template <Iterator Iterator_t, Functor Functor_t> std::pair<ConditionalIterator<Iterator_t, Functor_t>, ConditionalIterator<Iterator_t, Functor_t>> make_conditional_begin_and_end(Iterator_t begin, Iterator_t end, Functor_t condition) { return {ConditionalIterator<Iterator_t, Functor_t>(begin, end, condition), ConditionalIterator<Iterator_t, Functor_t>(end, end, condition)}; } int main(int argc, char* argv[]) { std::vector<int> numbers = {1, 2, 3, 5, 6, 7, 5, 4, 3, 2, 3, 4, 5, 7, 9, 2, 1, 3, 4, 5, 7, 3}; auto isThree = [](int x) { return x == 3; }; auto conditional_begin_end = make_conditional_begin_and_end(numbers.begin(), numbers.end(), isThree); std::ostream_iterator<int> osi(std::cout, " "); std::copy(numbers.begin(), numbers.end(), osi); std::cout << "\n3 appears in the list " << std::count_if(numbers.begin(), numbers.end(), isThree) << " times" << std::endl; std::copy(conditional_begin_end.first, conditional_begin_end.second, osi); std::cout << std::endl; } <commit_msg>remove check to get closer to raw loop performance<commit_after>#include <iostream> #include <algorithm> #include <iterator> #include <vector> #define Iterator typename #define FunctionObject typename template <Iterator Iterator_t, FunctionObject FunctionObject_t> class ConditionalIterator { public: bool operator==(ConditionalIterator<Iterator_t, FunctionObject_t> that) const { return iterator_ == that.iterator_; } bool operator!=(ConditionalIterator<Iterator_t, FunctionObject_t> that) const { return iterator_ != that.iterator_; } ConditionalIterator<Iterator_t, FunctionObject_t>& operator++() { // NB this is unsafe if called when an iterator is already equal to end ++iterator_; while (iterator_ != end_ && !f_(*(iterator_))) { ++iterator_; } return *this; } ConditionalIterator(Iterator_t iterator, Iterator_t end, FunctionObject_t f) : iterator_(iterator), end_(end), f_(f) { while (iterator_ != end_ && !f_(*iterator_)) { ++iterator_; } } private: Iterator_t iterator_; Iterator_t end_; FunctionObject_t f_; public: auto operator*() const { return *iterator_; } }; template <Iterator Iterator_t, FunctionObject FunctionObject_t> std::pair<ConditionalIterator<Iterator_t, FunctionObject_t>, ConditionalIterator<Iterator_t, FunctionObject_t>> make_conditional_begin_and_end(Iterator_t begin, Iterator_t end, FunctionObject_t condition) { return {ConditionalIterator<Iterator_t, FunctionObject_t>(begin, end, condition), ConditionalIterator<Iterator_t, FunctionObject_t>(end, end, condition)}; } int main(int argc, char* argv[]) { std::vector<int> numbers = {1, 2, 3, 5, 6, 7, 5, 4, 3, 2, 3, 4, 5, 7, 9, 2, 1, 3, 4, 5, 7, 3}; auto isThree = [](int x) { return x == 3; }; auto conditional_begin_end = make_conditional_begin_and_end(numbers.begin(), numbers.end(), isThree); std::ostream_iterator<int> osi(std::cout, " "); std::copy(numbers.begin(), numbers.end(), osi); std::cout << "\n3 appears in the list " << std::count_if(numbers.begin(), numbers.end(), isThree) << " times" << std::endl; std::copy(conditional_begin_end.first, conditional_begin_end.second, osi); std::cout << std::endl; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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. =========================================================================*/ #include "mitkOrganTypeProperty.h" mitk::OrganTypeProperty::OrganTypeProperty() { AddEnumerationTypes(); } mitk::OrganTypeProperty::OrganTypeProperty( const IdType& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetValue( 0 ); } } mitk::OrganTypeProperty::OrganTypeProperty( const std::string& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( "undefined" ); } } mitk::OrganTypeProperty::~OrganTypeProperty() { } void mitk::OrganTypeProperty::AddEnumerationTypes() { IdType newId = EnumerationProperty::Size(); // On changes, please also change mitk::DataTreeNodeFactory::DefaultColorForOrgan() AddEnum( "undefined", newId++ ); AddEnum( "Ankle", newId++ ); AddEnum( "Appendix", newId++ ); AddEnum( "Blood vessels", newId++ ); AddEnum( "Bone", newId++ ); AddEnum( "Brain", newId++ ); AddEnum( "Bronchial tree", newId++ ); AddEnum( "Coccyx", newId++ ); AddEnum( "Colon", newId++ ); AddEnum( "Cyst", newId++ ); AddEnum( "Elbow", newId++ ); AddEnum( "Eye", newId++ ); AddEnum( "Fallopian tube", newId++ ); AddEnum( "Gall bladder", newId++ ); AddEnum( "Hand", newId++ ); AddEnum( "Heart", newId++ ); AddEnum( "Hip", newId++ ); AddEnum( "Kidney", newId++ ); AddEnum( "Knee", newId++ ); AddEnum( "Larynx", newId++ ); AddEnum( "Liver", newId++ ); AddEnum( "Lung", newId++ ); AddEnum( "Lymph node", newId++ ); AddEnum( "Muscle", newId++ ); AddEnum( "Nerve", newId++ ); AddEnum( "Nose", newId++ ); AddEnum( "Oesophagus", newId++ ); AddEnum( "Ovaries", newId++ ); AddEnum( "Pancreas", newId++ ); AddEnum( "Pelvis", newId++ ); AddEnum( "Penis", newId++ ); AddEnum( "Pharynx", newId++ ); AddEnum( "Prostate", newId++ ); AddEnum( "Rectum", newId++ ); AddEnum( "Sacrum", newId++ ); AddEnum( "Seminal vesicle", newId++ ); AddEnum( "Shoulder", newId++ ); AddEnum( "Spinal cord", newId++ ); AddEnum( "Spleen", newId++ ); AddEnum( "Stomach", newId++ ); AddEnum( "Teeth", newId++ ); AddEnum( "Testicles", newId++ ); AddEnum( "Thyroid", newId++ ); AddEnum( "Tongue", newId++ ); AddEnum( "Tumor", newId++ ); AddEnum( "Urethra", newId++ ); AddEnum( "Urinary bladder", newId++ ); AddEnum( "Uterus", newId++ ); AddEnum( "Vagina", newId++ ); AddEnum( "Vertebra", newId++ ); AddEnum( "Wrist", newId++ ); } <commit_msg>CHG (#1891): add Enumeration Type for FAT<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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. =========================================================================*/ #include "mitkOrganTypeProperty.h" mitk::OrganTypeProperty::OrganTypeProperty() { AddEnumerationTypes(); } mitk::OrganTypeProperty::OrganTypeProperty( const IdType& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetValue( 0 ); } } mitk::OrganTypeProperty::OrganTypeProperty( const std::string& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( "undefined" ); } } mitk::OrganTypeProperty::~OrganTypeProperty() { } void mitk::OrganTypeProperty::AddEnumerationTypes() { IdType newId = EnumerationProperty::Size(); // On changes, please also change mitk::DataTreeNodeFactory::DefaultColorForOrgan() AddEnum( "undefined", newId++ ); AddEnum( "Ankle", newId++ ); AddEnum( "Appendix", newId++ ); AddEnum( "Blood vessels", newId++ ); AddEnum( "Bone", newId++ ); AddEnum( "Brain", newId++ ); AddEnum( "Bronchial tree", newId++ ); AddEnum( "Coccyx", newId++ ); AddEnum( "Colon", newId++ ); AddEnum( "Cyst", newId++ ); AddEnum( "Elbow", newId++ ); AddEnum( "Eye", newId++ ); AddEnum( "Fallopian tube", newId++ ); AddEnum( "Fat", newId++ ); AddEnum( "Gall bladder", newId++ ); AddEnum( "Hand", newId++ ); AddEnum( "Heart", newId++ ); AddEnum( "Hip", newId++ ); AddEnum( "Kidney", newId++ ); AddEnum( "Knee", newId++ ); AddEnum( "Larynx", newId++ ); AddEnum( "Liver", newId++ ); AddEnum( "Lung", newId++ ); AddEnum( "Lymph node", newId++ ); AddEnum( "Muscle", newId++ ); AddEnum( "Nerve", newId++ ); AddEnum( "Nose", newId++ ); AddEnum( "Oesophagus", newId++ ); AddEnum( "Ovaries", newId++ ); AddEnum( "Pancreas", newId++ ); AddEnum( "Pelvis", newId++ ); AddEnum( "Penis", newId++ ); AddEnum( "Pharynx", newId++ ); AddEnum( "Prostate", newId++ ); AddEnum( "Rectum", newId++ ); AddEnum( "Sacrum", newId++ ); AddEnum( "Seminal vesicle", newId++ ); AddEnum( "Shoulder", newId++ ); AddEnum( "Spinal cord", newId++ ); AddEnum( "Spleen", newId++ ); AddEnum( "Stomach", newId++ ); AddEnum( "Teeth", newId++ ); AddEnum( "Testicles", newId++ ); AddEnum( "Thyroid", newId++ ); AddEnum( "Tongue", newId++ ); AddEnum( "Tumor", newId++ ); AddEnum( "Urethra", newId++ ); AddEnum( "Urinary bladder", newId++ ); AddEnum( "Uterus", newId++ ); AddEnum( "Vagina", newId++ ); AddEnum( "Vertebra", newId++ ); AddEnum( "Wrist", newId++ ); } <|endoftext|>
<commit_before>#include <chrono> #include <cstring> #include <ctime> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <thread> #include <unistd.h> #include "libs/exceptionpp/exception.h" #include "src/msg_node.h" msgpp::Message::Message(size_t id, std::string ip, std::string hostname, std::string message) : id(id), ip(ip), hostname(hostname), message(message) {} size_t msgpp::Message::get_identifier() { return(this->id); } std::string msgpp::Message::get_ip() { return(this->ip); } std::string msgpp::Message::get_hostname() { return(this->hostname); } std::string msgpp::Message::get_message() { return(this->message); } std::vector<std::shared_ptr<msgpp::MessageNode>> msgpp::MessageNode::instances; std::recursive_mutex msgpp::MessageNode::l; std::chrono::milliseconds msgpp::MessageNode::increment = std::chrono::milliseconds(100); sighandler_t msgpp::MessageNode::handler; msgpp::MessageNode::MessageNode(size_t port, uint8_t protocol, size_t timeout, size_t max_conn) : protocol(protocol), port(port), timeout(timeout), max_conn(max_conn) { this->flag = std::shared_ptr<std::atomic<bool>> (new std::atomic<bool> (0)); } uint8_t msgpp::MessageNode::get_protocol() { return(this->protocol); } size_t msgpp::MessageNode::get_port() { return(this->port); } size_t msgpp::MessageNode::get_timeout() { return(this->timeout); } size_t msgpp::MessageNode::get_max_conn() { return(this->max_conn); } bool msgpp::MessageNode::get_status() { return(*(this->flag)); } void msgpp::MessageNode::set_timeout(size_t timeout) { this->timeout = timeout; } void msgpp::MessageNode::up() { { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); if(*flag == 1) { return; } if(msgpp::MessageNode::instances.size() == 0) { msgpp::MessageNode::handler = signal(SIGINT, msgpp::MessageNode::term); } *flag = 1; msgpp::MessageNode::instances.push_back(this->shared_from_this()); } std::stringstream port; port << this->port; int server_sock, status; struct addrinfo info; struct addrinfo *list; memset(&info, 0, sizeof(info)); if(this->protocol & msgpp::MessageNode::ipv6) { info.ai_family = AF_INET6; } else if(this->protocol & msgpp::MessageNode::ipv4) { info.ai_family = AF_INET; } else { info.ai_family = AF_UNSPEC; } info.ai_socktype = SOCK_STREAM; info.ai_flags = AI_PASSIVE; status = getaddrinfo(NULL, port.str().c_str(), &info, &list); if(list == NULL) { throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot find address")); } server_sock = socket(list->ai_family, list->ai_socktype, list->ai_protocol); if(server_sock == -1) { freeaddrinfo(list); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot open socket")); } int yes = 1; status = setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); status = bind(server_sock, list->ai_addr, list->ai_addrlen); if(status == -1) { freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot bind server-side socket")); } status = listen(server_sock, this->get_max_conn()); if(status == -1) { freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot listen on server-side socket")); } // set as non-blocking // cf. http://bit.ly/1tse7i3 fcntl(server_sock, F_SETFL, O_NONBLOCK); this->threads.clear(); // use sockaddr_storage for protocol-agnostic IP storage // cf. http://bit.ly/1ukHOQ8 struct sockaddr_storage client_addr; memset(&client_addr, sizeof(struct sockaddr_storage), sizeof(char)); socklen_t client_size = 0; while(*(this->flag)) { // dispatch any incoming clients int client_sock = accept(server_sock, (sockaddr *) &client_addr, &client_size); if(client_sock != -1) { std::shared_ptr<std::thread> t (new std::thread(&msgpp::MessageNode::dispatch, this, client_sock, client_addr, client_size)); this->threads.push_back(t); } } // clean up client connections for(size_t i = 0; i < this->threads.size(); ++i) { this->threads.at(i)->join(); } freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); return; } void msgpp::MessageNode::dispatch(int client_sock, struct sockaddr_storage client_addr, socklen_t client_size) { char host[NI_MAXHOST] = ""; char ip[NI_MAXHOST] = ""; getnameinfo((struct sockaddr *) &client_addr, client_size, host, NI_MAXHOST, NULL, 0, 0); getnameinfo((struct sockaddr *) &client_addr, client_size, ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); fcntl(client_sock, F_SETFL, O_NONBLOCK); std::stringstream len_buf; std::stringstream msg_buf; bool is_done = 0; size_t size = 0; while(!is_done) { char tmp_buf[msgpp::MessageNode::size]; memset(&tmp_buf, 0, msgpp::MessageNode::size); int n_bytes = 0; time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { n_bytes = recv(client_sock, &tmp_buf, msgpp::MessageNode::size, 0); if(n_bytes == -1) { if(errno != EAGAIN) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } else { break; } } if(n_bytes == 0 || n_bytes == -1) { // client closed unexpectedly // as the message queue is atomically set (i.e., no half-assed data), we will roll back changes and not touch the queue break; } std::string tmp = std::string(tmp_buf, n_bytes); if(size == 0) { size_t pos = tmp.find(':'); if(pos == std::string::npos) { pos = tmp.size(); } len_buf << tmp.substr(0, pos); if(pos != tmp.size()) { size = std::stoll(len_buf.str()); msg_buf << tmp.substr(pos + 1); } } else { msg_buf << tmp; } if(size != 0) { is_done = (msg_buf.str().length() >= size); } } if(is_done && (msg_buf.str().length() >= size)) { std::lock_guard<std::mutex> lock(this->messages_l); this->messages.push_back(msgpp::Message(++this->count, ip, host, msg_buf.str().substr(0, size))); } shutdown(client_sock, SHUT_RDWR); close(client_sock); } void msgpp::MessageNode::dn() { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); if(*(this->flag) == 0) { return; } *(this->flag) = 0; // restore signal handler if no more instances are running if(msgpp::MessageNode::instances.size() == 0) { signal(SIGINT, msgpp::MessageNode::handler); } } size_t msgpp::MessageNode::query() { std::lock_guard<std::mutex> lock(this->messages_l); return(this->messages.size()); } size_t msgpp::MessageNode::push(std::string message, std::string hostname, size_t port, bool silent_fail) { std::stringstream port_buf, msg_buf; port_buf << port; msg_buf << message.length() << ":" << message; int client_sock, status; struct addrinfo info; struct addrinfo *list; memset(&info, 0, sizeof(info)); info.ai_family = AF_UNSPEC; info.ai_socktype = SOCK_STREAM; getaddrinfo(hostname.c_str(), port_buf.str().c_str(), &info, &list); if(list == NULL) { if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot find endpoint")); } client_sock = socket(list->ai_family, list->ai_socktype, list->ai_protocol); if(client_sock == -1) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot open socket")); } int yes = 1; status = setsockopt(client_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); fcntl(client_sock, F_SETFL, O_NONBLOCK); time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { status = connect(client_sock, list->ai_addr, list->ai_addrlen); if(status != -1) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } if(status == -1) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot connect to destination")); } int result = -1; size_t n_bytes = 0; start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { result = send(client_sock, msg_buf.str().c_str(), msg_buf.str().length(), 0); if(result != -1) { n_bytes += result; if(n_bytes == msg_buf.str().length()) { break; } } else { if(errno == EWOULDBLOCK) { std::this_thread::sleep_for(msgpp::MessageNode::increment); } else { break; } } } if(result == -1 || n_bytes != msg_buf.str().length()) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::send", "could not send data")); } freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); return(result - (msg_buf.str().length() - message.length())); } std::string msgpp::MessageNode::pull(std::string hostname, bool silent_fail) { size_t target = 0; bool is_found = 0; time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { // lock during iteration, but unlock during sleep to give the queue an opportunity to fill up again { std::lock_guard<std::mutex> lock(this->messages_l); if(!this->messages.empty()) { for(std::vector<msgpp::Message>::iterator it = this->messages.begin(); it != this->messages.end(); ++it) { msgpp::Message instance = *it; bool match_h = (instance.get_hostname().compare("") == 0) || (instance.get_ip().compare("") == 0) || (hostname.compare("") == 0) || (hostname.compare(instance.get_hostname()) == 0) || (hostname.compare(instance.get_ip()) == 0); if(match_h) { target = it->get_identifier(); is_found = 1; break; } } } } if(is_found) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } if(!is_found) { if(silent_fail) { return(""); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::pull", "message does not exist")); } std::string message; { std::lock_guard<std::mutex> lock(this->messages_l); auto index = this->messages.end(); for(std::vector<msgpp::Message>::iterator it = this->messages.begin(); it != this->messages.end(); ++it) { msgpp::Message instance = *it; if(it->get_identifier() == target) { index = it; message = it->get_message(); } } this->messages.erase(index); } return(message); } /** * SIGINT handler -- terminate all running MessageNode instances */ void msgpp::MessageNode::term(int p) { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); for(std::vector<std::shared_ptr<msgpp::MessageNode>>::iterator it = msgpp::MessageNode::instances.begin(); it != msgpp::MessageNode::instances.end(); ++it) { (*it)->dn(); } msgpp::MessageNode::instances.clear(); // install old sighandler // cf. http://bit.ly/1unilFS signal(SIGINT, msgpp::MessageNode::handler); } <commit_msg>fixed uninitialized value bug<commit_after>#include <chrono> #include <cstring> #include <ctime> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <sstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <thread> #include <unistd.h> #include "libs/exceptionpp/exception.h" #include "src/msg_node.h" msgpp::Message::Message(size_t id, std::string ip, std::string hostname, std::string message) : id(id), ip(ip), hostname(hostname), message(message) {} size_t msgpp::Message::get_identifier() { return(this->id); } std::string msgpp::Message::get_ip() { return(this->ip); } std::string msgpp::Message::get_hostname() { return(this->hostname); } std::string msgpp::Message::get_message() { return(this->message); } std::vector<std::shared_ptr<msgpp::MessageNode>> msgpp::MessageNode::instances; std::recursive_mutex msgpp::MessageNode::l; std::chrono::milliseconds msgpp::MessageNode::increment = std::chrono::milliseconds(100); sighandler_t msgpp::MessageNode::handler; msgpp::MessageNode::MessageNode(size_t port, uint8_t protocol, size_t timeout, size_t max_conn) : protocol(protocol), port(port), timeout(timeout), max_conn(max_conn) { this->flag = std::shared_ptr<std::atomic<bool>> (new std::atomic<bool> (0)); this->count = 0; this->threads = std::vector<std::shared_ptr<std::thread>> (); this->messages = std::vector<msgpp::Message> (); } uint8_t msgpp::MessageNode::get_protocol() { return(this->protocol); } size_t msgpp::MessageNode::get_port() { return(this->port); } size_t msgpp::MessageNode::get_timeout() { return(this->timeout); } size_t msgpp::MessageNode::get_max_conn() { return(this->max_conn); } bool msgpp::MessageNode::get_status() { return(*(this->flag)); } void msgpp::MessageNode::set_timeout(size_t timeout) { this->timeout = timeout; } void msgpp::MessageNode::up() { { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); if(*flag == 1) { return; } if(msgpp::MessageNode::instances.size() == 0) { msgpp::MessageNode::handler = signal(SIGINT, msgpp::MessageNode::term); } *flag = 1; msgpp::MessageNode::instances.push_back(this->shared_from_this()); } std::stringstream port; port << this->port; int server_sock, status; struct addrinfo info; struct addrinfo *list; memset(&info, 0, sizeof(info)); if(this->protocol & msgpp::MessageNode::ipv6) { info.ai_family = AF_INET6; } else if(this->protocol & msgpp::MessageNode::ipv4) { info.ai_family = AF_INET; } else { info.ai_family = AF_UNSPEC; } info.ai_socktype = SOCK_STREAM; info.ai_flags = AI_PASSIVE; status = getaddrinfo(NULL, port.str().c_str(), &info, &list); if(list == NULL) { throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot find address")); } server_sock = socket(list->ai_family, list->ai_socktype, list->ai_protocol); if(server_sock == -1) { freeaddrinfo(list); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot open socket")); } int yes = 1; status = setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); status = bind(server_sock, list->ai_addr, list->ai_addrlen); if(status == -1) { freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot bind server-side socket")); } status = listen(server_sock, this->get_max_conn()); if(status == -1) { freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); throw(exceptionpp::RuntimeError("msgpp::MessageNode::up", "cannot listen on server-side socket")); } // set as non-blocking // cf. http://bit.ly/1tse7i3 fcntl(server_sock, F_SETFL, O_NONBLOCK); this->threads.clear(); // use sockaddr_storage for protocol-agnostic IP storage // cf. http://bit.ly/1ukHOQ8 struct sockaddr_storage client_addr; memset(&client_addr, sizeof(struct sockaddr_storage), sizeof(char)); socklen_t client_size = 0; while(*(this->flag)) { // dispatch any incoming clients int client_sock = accept(server_sock, (sockaddr *) &client_addr, &client_size); if(client_sock != -1) { std::shared_ptr<std::thread> t (new std::thread(&msgpp::MessageNode::dispatch, this, client_sock, client_addr, client_size)); this->threads.push_back(t); } } // clean up client connections for(size_t i = 0; i < this->threads.size(); ++i) { this->threads.at(i)->join(); } freeaddrinfo(list); shutdown(server_sock, SHUT_RDWR); close(server_sock); return; } void msgpp::MessageNode::dispatch(int client_sock, struct sockaddr_storage client_addr, socklen_t client_size) { char host[NI_MAXHOST] = ""; char ip[NI_MAXHOST] = ""; getnameinfo((struct sockaddr *) &client_addr, client_size, host, NI_MAXHOST, NULL, 0, 0); getnameinfo((struct sockaddr *) &client_addr, client_size, ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); fcntl(client_sock, F_SETFL, O_NONBLOCK); std::stringstream len_buf; std::stringstream msg_buf; bool is_done = 0; size_t size = 0; while(!is_done) { char tmp_buf[msgpp::MessageNode::size]; memset(&tmp_buf, 0, msgpp::MessageNode::size); int n_bytes = 0; time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { n_bytes = recv(client_sock, &tmp_buf, msgpp::MessageNode::size, 0); if(n_bytes == -1) { if(errno != EAGAIN) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } else { break; } } if(n_bytes == 0 || n_bytes == -1) { // client closed unexpectedly // as the message queue is atomically set (i.e., no half-assed data), we will roll back changes and not touch the queue break; } std::string tmp = std::string(tmp_buf, n_bytes); if(size == 0) { size_t pos = tmp.find(':'); if(pos == std::string::npos) { pos = tmp.size(); } len_buf << tmp.substr(0, pos); if(pos != tmp.size()) { size = std::stoll(len_buf.str()); msg_buf << tmp.substr(pos + 1); } } else { msg_buf << tmp; } if(size != 0) { is_done = (msg_buf.str().length() >= size); } } if(is_done && (msg_buf.str().length() >= size)) { std::lock_guard<std::mutex> lock(this->messages_l); this->messages.push_back(msgpp::Message(++this->count, ip, host, msg_buf.str().substr(0, size))); } shutdown(client_sock, SHUT_RDWR); close(client_sock); } void msgpp::MessageNode::dn() { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); if(*(this->flag) == 0) { return; } *(this->flag) = 0; // restore signal handler if no more instances are running if(msgpp::MessageNode::instances.size() == 0) { signal(SIGINT, msgpp::MessageNode::handler); } } size_t msgpp::MessageNode::query() { std::lock_guard<std::mutex> lock(this->messages_l); return(this->messages.size()); } size_t msgpp::MessageNode::push(std::string message, std::string hostname, size_t port, bool silent_fail) { std::stringstream port_buf, msg_buf; port_buf << port; msg_buf << message.length() << ":" << message; int client_sock, status; struct addrinfo info; struct addrinfo *list; memset(&info, 0, sizeof(info)); info.ai_family = AF_UNSPEC; info.ai_socktype = SOCK_STREAM; getaddrinfo(hostname.c_str(), port_buf.str().c_str(), &info, &list); if(list == NULL) { if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot find endpoint")); } client_sock = socket(list->ai_family, list->ai_socktype, list->ai_protocol); if(client_sock == -1) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot open socket")); } int yes = 1; status = setsockopt(client_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); fcntl(client_sock, F_SETFL, O_NONBLOCK); time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { status = connect(client_sock, list->ai_addr, list->ai_addrlen); if(status != -1) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } if(status == -1) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::push", "cannot connect to destination")); } int result = -1; size_t n_bytes = 0; start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { result = send(client_sock, msg_buf.str().c_str(), msg_buf.str().length(), 0); if(result != -1) { n_bytes += result; if(n_bytes == msg_buf.str().length()) { break; } } else { if(errno == EWOULDBLOCK) { std::this_thread::sleep_for(msgpp::MessageNode::increment); } else { break; } } } if(result == -1 || n_bytes != msg_buf.str().length()) { freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); if(silent_fail) { return(0); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::send", "could not send data")); } freeaddrinfo(list); shutdown(client_sock, SHUT_RDWR); close(client_sock); return(result - (msg_buf.str().length() - message.length())); } std::string msgpp::MessageNode::pull(std::string hostname, bool silent_fail) { size_t target = 0; bool is_found = 0; time_t start = time(NULL); while(((size_t) time(NULL) - start) < this->timeout) { // lock during iteration, but unlock during sleep to give the queue an opportunity to fill up again { std::lock_guard<std::mutex> lock(this->messages_l); if(!this->messages.empty()) { for(std::vector<msgpp::Message>::iterator it = this->messages.begin(); it != this->messages.end(); ++it) { msgpp::Message instance = *it; bool match_h = (instance.get_hostname().compare("") == 0) || (instance.get_ip().compare("") == 0) || (hostname.compare("") == 0) || (hostname.compare(instance.get_hostname()) == 0) || (hostname.compare(instance.get_ip()) == 0); if(match_h) { target = it->get_identifier(); is_found = 1; break; } } } } if(is_found) { break; } std::this_thread::sleep_for(msgpp::MessageNode::increment); } if(!is_found) { if(silent_fail) { return(""); } throw(exceptionpp::RuntimeError("msgpp::MessageNode::pull", "message does not exist")); } std::string message = ""; { std::lock_guard<std::mutex> lock(this->messages_l); auto index = this->messages.end(); for(std::vector<msgpp::Message>::iterator it = this->messages.begin(); it != this->messages.end(); ++it) { msgpp::Message instance = *it; if(instance.get_identifier() == target) { index = it; message = instance.get_message(); } } this->messages.erase(index); } return(message); } /** * SIGINT handler -- terminate all running MessageNode instances */ void msgpp::MessageNode::term(int p) { std::lock_guard<std::recursive_mutex> lock(msgpp::MessageNode::l); for(std::vector<std::shared_ptr<msgpp::MessageNode>>::iterator it = msgpp::MessageNode::instances.begin(); it != msgpp::MessageNode::instances.end(); ++it) { (*it)->dn(); } msgpp::MessageNode::instances.clear(); // install old sighandler // cf. http://bit.ly/1unilFS signal(SIGINT, msgpp::MessageNode::handler); } <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 Flowgrammable.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. #include <iostream> #include <fstream> #include <iterator> #include <string> #include <vector> #include <assert.h> #include <freeflow/sys/socket.hpp> #include <freeflow/sys/json.hpp> using namespace std; using namespace freeflow; struct CLI_parser_exception { CLI_parser_exception(string err); }; CLI_parser_exception::CLI_parser_exception(string err) { cout << "CLI parser exception: " << err << endl; } struct CLI_parser_rule { string format; bool match(string & str,vector<pair<string,string> > & args); CLI_parser_rule(string rule); }; // Constructor for CLI_parser_rule // Currently, it just checks to make sure that all square brackets are closed CLI_parser_rule::CLI_parser_rule(string rule) : format(rule) { // Make sure all square brackets are closed bool in_bracket = false; for (char c : format) { if (c == '[') { if (not in_bracket) { in_bracket = true; } else { throw CLI_parser_exception("Too many opening square brackets ('[')" " in parser rule: " + format); } } else if (c == ']') { if (in_bracket) { in_bracket = false; } else { throw CLI_parser_exception("Too many closing square brackets (']')" " in parser rule: " + format); } } } if (in_bracket){ throw CLI_parser_exception("Expected closing square bracket (']')" " in parser rule: " + format); } } // Performs basic, greedy "pattern matching" between a rule and a string. // // If it matches the pattern, it returns true and populates args with // pairs of variable names and their values. Otherwise, it returns // false and clears args. bool CLI_parser_rule::match(string & str,vector<pair<string,string> > & args) { int pos_f = 0; // Position in the formate string (i.e. rule) int pos_s = 0; // Position in the string to be matched string var_name; // Name of the current variable string var_value; // Value of the current variable bool var = false; // Whether we're currently matching a variable while (pos_s < (int)str.length()) { if (!var) { if (format[pos_f] == '[') { pos_f++; var_name = ""; var_value = ""; var = true; bool matched = false; // Extract the name of the variable while (pos_f < (int)format.length()) { if (format[pos_f] == ']') { matched = true; pos_f++; break; } else{ var_name += format[pos_f++]; } } // Should never happen because this is checked for in the constructor if (!matched) { throw CLI_parser_exception("Impossible unmatched bracket in: "+format); } } } if (var) { // Peek ahead and see if the current character matches the current // format character. If so, assume we're done matching the variable // (this works because the algorithm is greedy) if (str[pos_s] == format[pos_f]) { var = false; args.push_back(pair<string,string>(var_name,var_value)); } else { var_value += str[pos_s++]; } } else { if (format[pos_f] != str[pos_s]) { args.clear(); return false; } pos_f++; pos_s++; } } if (var){ args.push_back(pair<string,string>(var_name,var_value)); } if (pos_f < (int)format.length()) { args.clear(); return false; } else return true; } struct CLI_parser { vector<CLI_parser_rule> rules; vector<string> args; int arg_pos; void parse(int argc,char *argv[]); string & get_arg(); bool next_arg(); void set_arg_pos(int pos); }; void CLI_parser::parse(int argc,char *argv[]) { // Probably a good idea to clear the args vector if this is called more than once args.clear(); for (int i = 0; i < argc; i++) { args.push_back(argv[i]); } set_arg_pos(0); } // Gets the current argument string & CLI_parser::get_arg() { assert(arg_pos < (int)args.size()); return args[arg_pos]; } // Advances to the next argument // Returns whether there is another argument bool CLI_parser::next_arg() { return ++arg_pos < (int)args.size(); } // Sets the position of the current argument void CLI_parser::set_arg_pos(int pos) { if (pos < (int)args.size()) arg_pos = pos; else arg_pos = args.size(); } int main(int argc,char *argv[]){ CLI_parser parser; CLI_parser_rule("--[flag]=[value]"); parser.parse(argc,argv); do{ cout << parser.get_arg() << endl; } while(parser.next_arg()); } <commit_msg>Put function return types on separate lines to conform to coding style<commit_after>// Copyright (c) 2013-2014 Flowgrammable.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. #include <iostream> #include <fstream> #include <iterator> #include <string> #include <vector> #include <assert.h> #include <freeflow/sys/socket.hpp> #include <freeflow/sys/json.hpp> using namespace std; using namespace freeflow; // Very simple CLI exception handling class // TODO: redirect output to stderr struct CLI_parser_exception { CLI_parser_exception(string err); }; CLI_parser_exception::CLI_parser_exception(string err) { cout << "CLI parser exception: " << err << endl; } // A rule which control how the parser parses command line arguments struct CLI_parser_rule { string format; bool match(string & str,vector<pair<string,string> > & args); CLI_parser_rule(string rule); }; // Constructor for CLI_parser_rule // Currently, it just checks to make sure that all square brackets are closed CLI_parser_rule::CLI_parser_rule(string rule) : format(rule) { // Make sure all square brackets are closed bool in_bracket = false; for (char c : format) { if (c == '[') { if (not in_bracket) { in_bracket = true; } else { throw CLI_parser_exception("Too many opening square brackets ('[')" " in parser rule: " + format); } } else if (c == ']') { if (in_bracket) { in_bracket = false; } else { throw CLI_parser_exception("Too many closing square brackets (']')" " in parser rule: " + format); } } } if (in_bracket){ throw CLI_parser_exception("Expected closing square bracket (']')" " in parser rule: " + format); } } // Performs basic, greedy "pattern matching" between a rule and a string. // // If it matches the pattern, it returns true and populates args with // pairs of variable names and their values. Otherwise, it returns // false and clears args. bool CLI_parser_rule::match(string & str,vector<pair<string,string> > & args) { int pos_f = 0; // Position in the formate string (i.e. rule) int pos_s = 0; // Position in the string to be matched string var_name; // Name of the current variable string var_value; // Value of the current variable bool var = false; // Whether we're currently matching a variable while (pos_s < (int)str.length()) { if (!var) { if (format[pos_f] == '[') { pos_f++; var_name = ""; var_value = ""; var = true; bool matched = false; // Extract the name of the variable while (pos_f < (int)format.length()) { if (format[pos_f] == ']') { matched = true; pos_f++; break; } else{ var_name += format[pos_f++]; } } // Should never happen because this is checked for in the constructor if (!matched) { throw CLI_parser_exception("Impossible unmatched bracket in: "+format); } } } if (var) { // Peek ahead and see if the current character matches the current // format character. If so, assume we're done matching the variable // (this works because the algorithm is greedy) if (str[pos_s] == format[pos_f]) { var = false; args.push_back(pair<string,string>(var_name,var_value)); } else { var_value += str[pos_s++]; } } else { if (format[pos_f] != str[pos_s]) { args.clear(); return false; } pos_f++; pos_s++; } } if (var){ args.push_back(pair<string,string>(var_name,var_value)); } if (pos_f < (int)format.length()) { args.clear(); return false; } else return true; } struct CLI_parser { vector<CLI_parser_rule> rules; vector<string> args; int arg_pos; void parse(int argc,char *argv[]); string & get_arg(); bool next_arg(); void set_arg_pos(int pos); }; // Actual parsing function // TODO: implement actual parsing void CLI_parser::parse(int argc,char *argv[]) { // Probably a good idea to clear the args vector if this is called more than once args.clear(); for (int i = 0; i < argc; i++) { args.push_back(argv[i]); } set_arg_pos(0); } // Gets the current argument string & CLI_parser::get_arg() { assert(arg_pos < (int)args.size()); return args[arg_pos]; } // Advances to the next argument // Returns whether there is another argument bool CLI_parser::next_arg() { return ++arg_pos < (int)args.size(); } // Sets the position of the current argument void CLI_parser::set_arg_pos(int pos) { if (pos < (int)args.size()) arg_pos = pos; else arg_pos = args.size(); } int main(int argc,char *argv[]) { CLI_parser parser; CLI_parser_rule("--[flag]=[value]"); parser.parse(argc,argv); do{ cout << parser.get_arg() << endl; } while(parser.next_arg()); } <|endoftext|>
<commit_before>#include "command.hh" #include "hash.hh" #include "legacy.hh" #include "shared.hh" #include "references.hh" #include "archive.hh" using namespace nix; struct CmdHash : Command { enum Mode { mFile, mPath }; Mode mode; Base base = SRI; bool truncate = false; HashType ht = htSHA256; std::vector<std::string> paths; std::optional<std::string> modulus; CmdHash(Mode mode) : mode(mode) { mkFlag(0, "sri", "print hash in SRI format", &base, SRI); mkFlag(0, "base64", "print hash in base-64", &base, Base64); mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32); mkFlag(0, "base16", "print hash in base-16", &base, Base16); mkFlag() .longName("type") .mkHashTypeFlag(&ht); mkFlag() .longName("modulo") .description("compute hash modulo specified string") .labels({"modulus"}) .dest(&modulus); expectArgs("paths", &paths); } std::string name() override { return mode == mFile ? "hash-file" : "hash-path"; } std::string description() override { return mode == mFile ? "print cryptographic hash of a regular file" : "print cryptographic hash of the NAR serialisation of a path"; } void run() override { for (auto path : paths) { std::unique_ptr<AbstractHashSink> hashSink; if (modulus) hashSink = std::make_unique<HashModuloSink>(ht, *modulus); else hashSink = std::make_unique<HashSink>(ht); if (mode == mFile) readFile(path, *hashSink); else dumpPath(path, *hashSink); Hash h = hashSink->finish().first; if (truncate && h.hashSize > 20) h = compressHash(h, 20); std::cout << format("%1%\n") % h.to_string(base, base == SRI); } } }; static RegisterCommand r1(make_ref<CmdHash>(CmdHash::mFile)); static RegisterCommand r2(make_ref<CmdHash>(CmdHash::mPath)); struct CmdToBase : Command { Base base; HashType ht = htUnknown; std::vector<std::string> args; CmdToBase(Base base) : base(base) { mkFlag() .longName("type") .mkHashTypeFlag(&ht); expectArgs("strings", &args); } std::string name() override { return base == Base16 ? "to-base16" : base == Base32 ? "to-base32" : base == Base64 ? "to-base64" : "to-sri"; } std::string description() override { return fmt("convert a hash to %s representation", base == Base16 ? "base-16" : base == Base32 ? "base-32" : base == Base64 ? "base-64" : "SRI"); } void run() override { for (auto s : args) std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI)); } }; static RegisterCommand r3(make_ref<CmdToBase>(Base16)); static RegisterCommand r4(make_ref<CmdToBase>(Base32)); static RegisterCommand r5(make_ref<CmdToBase>(Base64)); static RegisterCommand r6(make_ref<CmdToBase>(SRI)); /* Legacy nix-hash command. */ static int compatNixHash(int argc, char * * argv) { HashType ht = htMD5; bool flat = false; bool base32 = false; bool truncate = false; enum { opHash, opTo32, opTo16 } op = opHash; std::vector<std::string> ss; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-hash"); else if (*arg == "--version") printVersion("nix-hash"); else if (*arg == "--flat") flat = true; else if (*arg == "--base32") base32 = true; else if (*arg == "--truncate") truncate = true; else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--to-base16") op = opTo16; else if (*arg == "--to-base32") op = opTo32; else if (*arg != "" && arg->at(0) == '-') return false; else ss.push_back(*arg); return true; }); if (op == opHash) { CmdHash cmd(flat ? CmdHash::mFile : CmdHash::mPath); cmd.ht = ht; cmd.base = base32 ? Base32 : Base16; cmd.truncate = truncate; cmd.paths = ss; cmd.run(); } else { CmdToBase cmd(op == opTo32 ? Base32 : Base16); cmd.args = ss; cmd.ht = ht; cmd.run(); } return 0; } static RegisterLegacyCommand s1("nix-hash", compatNixHash); <commit_msg>Revert "Fix build"<commit_after>#include "command.hh" #include "hash.hh" #include "legacy.hh" #include "shared.hh" #include "references.hh" #include "archive.hh" using namespace nix; struct CmdHash : Command { enum Mode { mFile, mPath }; Mode mode; Base base = SRI; bool truncate = false; HashType ht = htSHA256; std::vector<std::string> paths; std::experimental::optional<std::string> modulus; CmdHash(Mode mode) : mode(mode) { mkFlag(0, "sri", "print hash in SRI format", &base, SRI); mkFlag(0, "base64", "print hash in base-64", &base, Base64); mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32); mkFlag(0, "base16", "print hash in base-16", &base, Base16); mkFlag() .longName("type") .mkHashTypeFlag(&ht); mkFlag() .longName("modulo") .description("compute hash modulo specified string") .labels({"modulus"}) .dest(&modulus); expectArgs("paths", &paths); } std::string name() override { return mode == mFile ? "hash-file" : "hash-path"; } std::string description() override { return mode == mFile ? "print cryptographic hash of a regular file" : "print cryptographic hash of the NAR serialisation of a path"; } void run() override { for (auto path : paths) { std::unique_ptr<AbstractHashSink> hashSink; if (modulus) hashSink = std::make_unique<HashModuloSink>(ht, *modulus); else hashSink = std::make_unique<HashSink>(ht); if (mode == mFile) readFile(path, *hashSink); else dumpPath(path, *hashSink); Hash h = hashSink->finish().first; if (truncate && h.hashSize > 20) h = compressHash(h, 20); std::cout << format("%1%\n") % h.to_string(base, base == SRI); } } }; static RegisterCommand r1(make_ref<CmdHash>(CmdHash::mFile)); static RegisterCommand r2(make_ref<CmdHash>(CmdHash::mPath)); struct CmdToBase : Command { Base base; HashType ht = htUnknown; std::vector<std::string> args; CmdToBase(Base base) : base(base) { mkFlag() .longName("type") .mkHashTypeFlag(&ht); expectArgs("strings", &args); } std::string name() override { return base == Base16 ? "to-base16" : base == Base32 ? "to-base32" : base == Base64 ? "to-base64" : "to-sri"; } std::string description() override { return fmt("convert a hash to %s representation", base == Base16 ? "base-16" : base == Base32 ? "base-32" : base == Base64 ? "base-64" : "SRI"); } void run() override { for (auto s : args) std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI)); } }; static RegisterCommand r3(make_ref<CmdToBase>(Base16)); static RegisterCommand r4(make_ref<CmdToBase>(Base32)); static RegisterCommand r5(make_ref<CmdToBase>(Base64)); static RegisterCommand r6(make_ref<CmdToBase>(SRI)); /* Legacy nix-hash command. */ static int compatNixHash(int argc, char * * argv) { HashType ht = htMD5; bool flat = false; bool base32 = false; bool truncate = false; enum { opHash, opTo32, opTo16 } op = opHash; std::vector<std::string> ss; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-hash"); else if (*arg == "--version") printVersion("nix-hash"); else if (*arg == "--flat") flat = true; else if (*arg == "--base32") base32 = true; else if (*arg == "--truncate") truncate = true; else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--to-base16") op = opTo16; else if (*arg == "--to-base32") op = opTo32; else if (*arg != "" && arg->at(0) == '-') return false; else ss.push_back(*arg); return true; }); if (op == opHash) { CmdHash cmd(flat ? CmdHash::mFile : CmdHash::mPath); cmd.ht = ht; cmd.base = base32 ? Base32 : Base16; cmd.truncate = truncate; cmd.paths = ss; cmd.run(); } else { CmdToBase cmd(op == opTo32 ? Base32 : Base16); cmd.args = ss; cmd.ht = ht; cmd.run(); } return 0; } static RegisterLegacyCommand s1("nix-hash", compatNixHash); <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "iterator_pack.h" #include "termwise_helper.h" #include <vespa/searchlib/fef/matchdata.h> namespace search::queryeval { SearchIteratorPack::~SearchIteratorPack() { } SearchIteratorPack::SearchIteratorPack() : _children(), _childMatch(), _md() {} SearchIteratorPack::SearchIteratorPack(SearchIteratorPack &&rhs) : _children(std::move(rhs._children)), _childMatch(std::move(rhs._childMatch)), _md(std::move(rhs._md)) {} SearchIteratorPack & SearchIteratorPack::operator=(SearchIteratorPack &&rhs) { _children = std::move(rhs._children); _childMatch = std::move(rhs._childMatch); _md = std::move(rhs._md); return *this; } SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, const std::vector<fef::TermFieldMatchData*> &childMatch, MatchDataUP md) : _children(), _childMatch(childMatch), _md(std::move(md)) { _children.reserve(children.size()); for (auto child: children) { _children.emplace_back(child); } assert((_children.size() == _childMatch.size()) || _childMatch.empty()); } SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, MatchDataUP md) : SearchIteratorPack(children, std::vector<fef::TermFieldMatchData*>(), MatchDataUP(std::move(md))) { } std::unique_ptr<BitVector> SearchIteratorPack::get_hits(uint32_t begin_id, uint32_t end_id) const { BitVector::UP result = TermwiseHelper::orChildren(_children.begin(), _children.end(), begin_id); if (! result ) { result = BitVector::create(begin_id, end_id); } return result; } void SearchIteratorPack::or_hits_into(BitVector &result, uint32_t begin_id) const { TermwiseHelper::orChildren(result, _children.begin(), _children.end(), begin_id); } } <commit_msg>= default<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "iterator_pack.h" #include "termwise_helper.h" #include <vespa/searchlib/fef/matchdata.h> namespace search::queryeval { SearchIteratorPack::~SearchIteratorPack() = default; SearchIteratorPack::SearchIteratorPack() : _children(), _childMatch(), _md() {} SearchIteratorPack::SearchIteratorPack(SearchIteratorPack &&rhs) : _children(std::move(rhs._children)), _childMatch(std::move(rhs._childMatch)), _md(std::move(rhs._md)) {} SearchIteratorPack & SearchIteratorPack::operator=(SearchIteratorPack &&rhs) { _children = std::move(rhs._children); _childMatch = std::move(rhs._childMatch); _md = std::move(rhs._md); return *this; } SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, const std::vector<fef::TermFieldMatchData*> &childMatch, MatchDataUP md) : _children(), _childMatch(childMatch), _md(std::move(md)) { _children.reserve(children.size()); for (auto child: children) { _children.emplace_back(child); } assert((_children.size() == _childMatch.size()) || _childMatch.empty()); } SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, MatchDataUP md) : SearchIteratorPack(children, std::vector<fef::TermFieldMatchData*>(), MatchDataUP(std::move(md))) { } std::unique_ptr<BitVector> SearchIteratorPack::get_hits(uint32_t begin_id, uint32_t end_id) const { BitVector::UP result = TermwiseHelper::orChildren(_children.begin(), _children.end(), begin_id); if (! result ) { result = BitVector::create(begin_id, end_id); } return result; } void SearchIteratorPack::or_hits_into(BitVector &result, uint32_t begin_id) const { TermwiseHelper::orChildren(result, _children.begin(), _children.end(), begin_id); } } <|endoftext|>
<commit_before>#include "types.h" #include "amd64.h" #include "kernel.hh" void* memset(void *dst, int c, size_t n) { stosb(dst, c, n); return dst; } int memcmp(const void *v1, const void *v2, size_t n) { const u8 *s1, *s2; s1 = (const u8*) v1; s2 = (const u8*) v2; while(n-- > 0){ if(*s1 != *s2) return *s1 - *s2; s1++, s2++; } return 0; } void* memmove(void *dst, const void *src, size_t n) { const char *s; char *d; s = (const char*) src; d = (char*) dst; if(s < d && s + n > d){ s += n; d += n; while(n-- > 0) *--d = *--s; } else while(n-- > 0) *d++ = *s++; return dst; } // memcpy exists to placate GCC. Use memmove. void* memcpy(void *dst, const void *src, size_t n) { return memmove(dst, src, n); } int strncmp(const char *p, const char *q, size_t n) { while(n > 0 && *p && *p == *q) n--, p++, q++; if(n == 0) return 0; return (u8)*p - (u8)*q; } char* strncpy(char *s, const char *t, size_t n) { char *os; os = s; while(n-- > 0 && (*s++ = *t++) != 0) ; while(n-- > 0) *s++ = 0; return os; } // Like strncpy but guaranteed to NUL-terminate. char* safestrcpy(char *s, const char *t, size_t n) { char *os; os = s; if(n <= 0) return os; while(--n > 0 && (*s++ = *t++) != 0) ; *s = 0; return os; } unsigned int strlen(const char *s) { int n; for(n = 0; s[n]; n++) ; return n; } int strcmp(const char *p, const char *q) { while(*p && *p == *q) p++, q++; return (u8)*p - (u8)*q; } <commit_msg>fix strncpy<commit_after>#include "types.h" #include "amd64.h" #include "kernel.hh" void* memset(void *dst, int c, size_t n) { stosb(dst, c, n); return dst; } int memcmp(const void *v1, const void *v2, size_t n) { const u8 *s1, *s2; s1 = (const u8*) v1; s2 = (const u8*) v2; while(n-- > 0){ if(*s1 != *s2) return *s1 - *s2; s1++, s2++; } return 0; } void* memmove(void *dst, const void *src, size_t n) { const char *s; char *d; s = (const char*) src; d = (char*) dst; if(s < d && s + n > d){ s += n; d += n; while(n-- > 0) *--d = *--s; } else while(n-- > 0) *d++ = *s++; return dst; } // memcpy exists to placate GCC. Use memmove. void* memcpy(void *dst, const void *src, size_t n) { return memmove(dst, src, n); } int strncmp(const char *p, const char *q, size_t n) { while(n > 0 && *p && *p == *q) n--, p++, q++; if(n == 0) return 0; return (u8)*p - (u8)*q; } char* strncpy(char *s, const char *t, size_t n) { char *os; os = s; while(n > 0 && (*s++ = *t++) != 0) n--; if (n > 0) *s = 0; return os; } // Like strncpy but guaranteed to NUL-terminate. char* safestrcpy(char *s, const char *t, size_t n) { char *os; os = s; if(n <= 0) return os; while(--n > 0 && (*s++ = *t++) != 0) ; *s = 0; return os; } unsigned int strlen(const char *s) { int n; for(n = 0; s[n]; n++) ; return n; } int strcmp(const char *p, const char *q) { while(*p && *p == *q) p++, q++; return (u8)*p - (u8)*q; } <|endoftext|>
<commit_before>#ifndef optional_hh_INCLUDED #define optional_hh_INCLUDED #include "assert.hh" namespace Kakoune { template<typename T> struct Optional { public: constexpr Optional() : m_valid(false) {} Optional(const T& other) : m_valid(true) { new (&m_value) T(other); } Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); } Optional(const Optional& other) : m_valid(other.m_valid) { if (m_valid) new (&m_value) T(other.m_value); } Optional(Optional&& other) noexcept(noexcept(new (nullptr) T(std::move(other.m_value)))) : m_valid(other.m_valid) { if (m_valid) new (&m_value) T(std::move(other.m_value)); } Optional& operator=(const Optional& other) { destruct_ifn(); if ((m_valid = other.m_valid)) new (&m_value) T(other.m_value); return *this; } Optional& operator=(Optional&& other) { destruct_ifn(); if ((m_valid = other.m_valid)) new (&m_value) T(std::move(other.m_value)); return *this; } ~Optional() { destruct_ifn(); } constexpr explicit operator bool() const noexcept { return m_valid; } bool operator==(const Optional& other) const { if (m_valid == other.m_valid) { if (m_valid) return m_value == other.m_value; return true; } return false; } template<typename... Args> void emplace(Args&&... args) { destruct_ifn(); new (&m_value) T{std::forward<Args>(args)...}; m_valid = true; } T& operator*() { kak_assert(m_valid); return m_value; } const T& operator*() const { return *const_cast<Optional&>(*this); } T* operator->() { kak_assert(m_valid); return &m_value; } const T* operator->() const { return const_cast<Optional&>(*this).operator->(); } template<typename U> T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; } private: void destruct_ifn() { if (m_valid) m_value.~T(); } struct Empty {}; union { Empty m_empty; // disable default construction of value T m_value; }; bool m_valid; }; } #endif // optional_hh_INCLUDED <commit_msg>Refactor Optional::operator==<commit_after>#ifndef optional_hh_INCLUDED #define optional_hh_INCLUDED #include "assert.hh" namespace Kakoune { template<typename T> struct Optional { public: constexpr Optional() : m_valid(false) {} Optional(const T& other) : m_valid(true) { new (&m_value) T(other); } Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); } Optional(const Optional& other) : m_valid(other.m_valid) { if (m_valid) new (&m_value) T(other.m_value); } Optional(Optional&& other) noexcept(noexcept(new (nullptr) T(std::move(other.m_value)))) : m_valid(other.m_valid) { if (m_valid) new (&m_value) T(std::move(other.m_value)); } Optional& operator=(const Optional& other) { destruct_ifn(); if ((m_valid = other.m_valid)) new (&m_value) T(other.m_value); return *this; } Optional& operator=(Optional&& other) { destruct_ifn(); if ((m_valid = other.m_valid)) new (&m_value) T(std::move(other.m_value)); return *this; } ~Optional() { destruct_ifn(); } constexpr explicit operator bool() const noexcept { return m_valid; } bool operator==(const Optional& other) const { return m_valid == other.m_valid and (not m_valid or m_value == other.m_value); } template<typename... Args> void emplace(Args&&... args) { destruct_ifn(); new (&m_value) T{std::forward<Args>(args)...}; m_valid = true; } T& operator*() { kak_assert(m_valid); return m_value; } const T& operator*() const { return *const_cast<Optional&>(*this); } T* operator->() { kak_assert(m_valid); return &m_value; } const T* operator->() const { return const_cast<Optional&>(*this).operator->(); } template<typename U> T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; } private: void destruct_ifn() { if (m_valid) m_value.~T(); } struct Empty {}; union { Empty m_empty; // disable default construction of value T m_value; }; bool m_valid; }; } #endif // optional_hh_INCLUDED <|endoftext|>
<commit_before>/* Optional packages. You might want to integrate this with your build system e.g. config.h from ./configure. */ #ifndef UTIL_HAVE__ #define UTIL_HAVE__ #ifndef HAVE_ICU //#define HAVE_ICU #endif #ifndef HAVE_BOOST //#define HAVE_BOOST #endif #endif // UTIL_HAVE__ <commit_msg>Get macros from config.h, break build for Chris to fix by linking libs<commit_after>/* Optional packages. You might want to integrate this with your build system e.g. config.h from ./configure. */ #ifndef UTIL_HAVE__ #define UTIL_HAVE__ #ifndef HAVE_ICU //#define HAVE_ICU #endif #ifndef HAVE_BOOST //#define HAVE_BOOST #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #endif // UTIL_HAVE__ <|endoftext|>
<commit_before>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "test-config.h" #include <syntaxrepository.h> #include <syntaxdefinition.h> #include <htmlhighlighter.h> #include <QObject> #include <QtTest/qtest.h> using namespace KateSyntax; class HighlighterBenchmark : public QObject { Q_OBJECT public: explicit HighlighterBenchmark(QObject *parent = nullptr) : QObject(parent), m_repo(nullptr) {} private: SyntaxRepository *m_repo; private slots: void initTestCase() { m_repo = new SyntaxRepository; } void cleanupTestCase() { delete m_repo; m_repo = nullptr; } void benchmarkHighlight_data() { QTest::addColumn<QString>("inFile"); QTest::addColumn<QString>("syntax"); QTest::newRow("mimedb") << QStringLiteral(":/qt-project.org/qmime/freedesktop.org.xml") << QStringLiteral("XML"); } void benchmarkHighlight() { QFETCH(QString, inFile); QFETCH(QString, syntax); QVERIFY(m_repo); HtmlHighlighter highlighter; auto def = m_repo->definitionForFileName(inFile); if (!syntax.isEmpty()) def = m_repo->definitionForName(syntax); QVERIFY(def); highlighter.setDefinition(def); highlighter.setOutputFile(QStringLiteral("/dev/null")); QBENCHMARK { highlighter.highlightFile(inFile); } } }; QTEST_MAIN(HighlighterBenchmark) #include "highlighter_benchmark.moc" <commit_msg>Improve benchmark to not measure HTML output overhead.<commit_after>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "test-config.h" #include <syntaxrepository.h> #include <syntaxdefinition.h> #include <abstracthighlighter.h> #include <QObject> #include <QtTest/qtest.h> using namespace KateSyntax; class NullHighlighter : public AbstractHighlighter { public: void highlightFile(const QString &inFileName) { QFile f(inFileName); if (!f.open(QFile::ReadOnly)) { qWarning() << "Failed to open input file" << inFileName << ":" << f.errorString(); return; } reset(); QTextStream in(&f); while (!in.atEnd()) highlightLine(in.readLine()); } protected: void setFormat(int, int, const Format&) override {} }; class HighlighterBenchmark : public QObject { Q_OBJECT public: explicit HighlighterBenchmark(QObject *parent = nullptr) : QObject(parent), m_repo(nullptr) {} private: SyntaxRepository *m_repo; private slots: void initTestCase() { m_repo = new SyntaxRepository; } void cleanupTestCase() { delete m_repo; m_repo = nullptr; } void benchmarkHighlight_data() { QTest::addColumn<QString>("inFile"); QTest::addColumn<QString>("syntax"); QTest::newRow("mimedb") << QStringLiteral(":/qt-project.org/qmime/freedesktop.org.xml") << QStringLiteral("XML"); } void benchmarkHighlight() { QFETCH(QString, inFile); QFETCH(QString, syntax); QVERIFY(m_repo); NullHighlighter highlighter; auto def = m_repo->definitionForFileName(inFile); if (!syntax.isEmpty()) def = m_repo->definitionForName(syntax); QVERIFY(def); highlighter.setDefinition(def); QBENCHMARK { highlighter.highlightFile(inFile); } } }; QTEST_MAIN(HighlighterBenchmark) #include "highlighter_benchmark.moc" <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // cache_test.cpp // // Identification: tests/common/cache_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "backend/common/thread_manager.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Thread Manager Test //===--------------------------------------------------------------------===// class ThreadManagerTests : public PelotonTest {}; TEST_F(ThreadManagerTests, BasicTest) { auto& thread_manager = ThreadManager::GetInstance(); std::shared_ptr<std::thread> t1(new std::thread); bool status = thread_manager.AttachThread(t1); EXPECT_EQ(status, true); status = thread_manager.AttachThread(t1); EXPECT_EQ(status, false); status = thread_manager.DetachThread(t1); EXPECT_EQ(status, true); status = thread_manager.DetachThread(t1); EXPECT_EQ(status, false); } } // End test namespace } // End peloton namespace <commit_msg>add thread_manager_test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // cache_test.cpp // // Identification: tests/common/cache_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "backend/common/thread_manager.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Thread Manager Test //===--------------------------------------------------------------------===// class ThreadManagerTests : public PelotonTest {}; /* this is the old test TEST_F(ThreadManagerTests, BasicTest) { auto& thread_manager = ThreadManager::GetInstance(); std::shared_ptr<std::thread> t1(new std::thread); bool status = thread_manager.AttachThread(t1); EXPECT_EQ(status, true); status = thread_manager.AttachThread(t1); EXPECT_EQ(status, false); status = thread_manager.DetachThread(t1); EXPECT_EQ(status, true); status = thread_manager.DetachThread(t1); EXPECT_EQ(status, false); } */ TEST_F(ThreadManagerTests, BasicTest) { auto& server_thread_manager1 = ThreadManager::GetServerThreadPool(); auto& server_thread_manager2 = ThreadManager::GetServerThreadPool(); bool status = (&server_thread_manager1 == &server_thread_manager2); EXPECT_EQ(status, true); auto& client_thread_manager1 = ThreadManager::GetClientThreadPool(); auto& client_thread_manager2 = ThreadManager::GetClientThreadPool(); status = (&client_thread_manager1 == &client_thread_manager2); EXPECT_EQ(status, true); status = (&server_thread_manager1 == &client_thread_manager2); EXPECT_EQ(status, false); } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <iostream> using namespace mfem; TEST_CASE("Test order of boundary integrators", "[BilinearForm]") { // Create a simple mesh int dim = 2, nx = 2, ny = 2, order = 2; Element::Type e_type = Element::QUADRILATERAL; Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type); H1_FECollection fec(order, dim); FiniteElementSpace fes(&mesh, &fec); SECTION("Order of restricted boundary integrators") { ConstantCoefficient one(1.0); ConstantCoefficient two(2.0); ConstantCoefficient three(3.0); ConstantCoefficient four(4.0); Array<int> bdr1(4); bdr1 = 0; bdr1[0] = 1; Array<int> bdr2(4); bdr2 = 0; bdr2[1] = 1; Array<int> bdr3(4); bdr3 = 0; bdr3[2] = 1; Array<int> bdr4(4); bdr4 = 0; bdr4[3] = 1; BilinearForm a1234(&fes); a1234.AddBoundaryIntegrator(new MassIntegrator(one), bdr1); a1234.AddBoundaryIntegrator(new MassIntegrator(two), bdr2); a1234.AddBoundaryIntegrator(new MassIntegrator(three), bdr3); a1234.AddBoundaryIntegrator(new MassIntegrator(four), bdr4); a1234.Assemble(0); a1234.Finalize(0); BilinearForm a4321(&fes); a4321.AddBoundaryIntegrator(new MassIntegrator(four), bdr4); a4321.AddBoundaryIntegrator(new MassIntegrator(three), bdr3); a4321.AddBoundaryIntegrator(new MassIntegrator(two), bdr2); a4321.AddBoundaryIntegrator(new MassIntegrator(one), bdr1); a4321.Assemble(0); a4321.Finalize(0); const SparseMatrix &A1234 = a1234.SpMat(); const SparseMatrix &A4321 = a4321.SpMat(); SparseMatrix *D = Add(1.0, A1234, -1.0, A4321); REQUIRE(D->MaxNorm() == MFEM_Approx(0.0)); delete D; } } TEST_CASE("FormLinearSystem/SolutionScope", "[BilinearForm]" "[CUDA]") { // Create a simple mesh and FE space int dim = 2, nx = 2, ny = 2, order = 2; Element::Type e_type = Element::QUADRILATERAL; Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type); H1_FECollection fec(order, dim); FiniteElementSpace fes(&mesh, &fec); int bdr_dof; // Solve a PDE on the conforming mesh and FE space defined above, storing the // result in 'sol'. auto SolvePDE = [&](AssemblyLevel al, GridFunction &sol) { // Linear form: rhs ConstantCoefficient f(1.0); LinearForm b(&fes); b.AddDomainIntegrator(new DomainLFIntegrator(f)); b.Assemble(); // Bilinear form: matrix BilinearForm a(&fes); a.AddDomainIntegrator(new DiffusionIntegrator); a.SetAssemblyLevel(al); a.Assemble(); // Setup b.c. Array<int> ess_tdof_list; REQUIRE(mesh.bdr_attributes.Max() > 0); Array<int> bdr_attr_is_ess(mesh.bdr_attributes.Max()); bdr_attr_is_ess = 1; fes.GetEssentialTrueDofs(bdr_attr_is_ess, ess_tdof_list); REQUIRE(ess_tdof_list.Size() > 0); // Setup (on host) solution initial guess satisfying the desired b.c. ConstantCoefficient zero(0.0); sol.ProjectCoefficient(zero); // performed on host // Setup the linear system Vector B, X; OperatorPtr A; const bool copy_interior = true; // interior(sol) --> interior(X) a.FormLinearSystem(ess_tdof_list, sol, b, A, X, B, copy_interior); // Solve the system CGSolver cg; cg.SetMaxIter(2000); cg.SetRelTol(1e-8); cg.SetAbsTol(0.0); cg.SetPrintLevel(0); cg.SetOperator(*A); cg.Mult(B, X); // Recover the solution a.RecoverFEMSolution(X, b, sol); // Initialize the bdr_dof to be checked ess_tdof_list.HostRead(); bdr_dof = AsConst(ess_tdof_list)[0]; // here, L-dof is the same T-dof }; // Legacy full assembly { GridFunction sol(&fes); SolvePDE(AssemblyLevel::LEGACYFULL, sol); // Make sure the solution is still accessible after 'X' is destoyed sol.HostRead(); REQUIRE(AsConst(sol)(bdr_dof) == 0.0); } // Partial assembly { GridFunction sol(&fes); SolvePDE(AssemblyLevel::PARTIAL, sol); // Make sure the solution is still accessible after 'X' is destoyed sol.HostRead(); REQUIRE(AsConst(sol)(bdr_dof) == 0.0); } } <commit_msg>Revert extra tests/unit/fem/test_bilinearform test<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "unit_tests.hpp" #include <iostream> using namespace mfem; TEST_CASE("Test order of boundary integrators", "[BilinearForm]") { // Create a simple mesh int dim = 2, nx = 2, ny = 2, order = 2; Element::Type e_type = Element::QUADRILATERAL; Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type); H1_FECollection fec(order, dim); FiniteElementSpace fes(&mesh, &fec); SECTION("Order of restricted boundary integrators") { ConstantCoefficient one(1.0); ConstantCoefficient two(2.0); ConstantCoefficient three(3.0); ConstantCoefficient four(4.0); Array<int> bdr1(4); bdr1 = 0; bdr1[0] = 1; Array<int> bdr2(4); bdr2 = 0; bdr2[1] = 1; Array<int> bdr3(4); bdr3 = 0; bdr3[2] = 1; Array<int> bdr4(4); bdr4 = 0; bdr4[3] = 1; BilinearForm a1234(&fes); a1234.AddBoundaryIntegrator(new MassIntegrator(one), bdr1); a1234.AddBoundaryIntegrator(new MassIntegrator(two), bdr2); a1234.AddBoundaryIntegrator(new MassIntegrator(three), bdr3); a1234.AddBoundaryIntegrator(new MassIntegrator(four), bdr4); a1234.Assemble(0); a1234.Finalize(0); BilinearForm a4321(&fes); a4321.AddBoundaryIntegrator(new MassIntegrator(four), bdr4); a4321.AddBoundaryIntegrator(new MassIntegrator(three), bdr3); a4321.AddBoundaryIntegrator(new MassIntegrator(two), bdr2); a4321.AddBoundaryIntegrator(new MassIntegrator(one), bdr1); a4321.Assemble(0); a4321.Finalize(0); const SparseMatrix &A1234 = a1234.SpMat(); const SparseMatrix &A4321 = a4321.SpMat(); SparseMatrix *D = Add(1.0, A1234, -1.0, A4321); REQUIRE(D->MaxNorm() == MFEM_Approx(0.0)); delete D; } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <stdexcept> #include <string> #include "paddle/fluid/framework/init.h" #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" namespace paddle { namespace framework { std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { argv.push_back("dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(1) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { cudaSetDevice(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitDevices(bool init_p2p) { /*Init all available devices by default */ #ifdef PADDLE_WITH_CUDA std::vector<int> devices; try { int count = platform::GetCUDADeviceCount(); for (int i = 0; i < count; ++i) { devices.push_back(i); } } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #else LOG(WARNING) << "'CUDA' is not supported, Please re-compile with WITH_GPU option"; #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; int count = 0; #ifdef PADDLE_WITH_CUDA try { count = platform::GetCUDADeviceCount(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #else LOG(WARNING) << "'CUDA' is not supported, Please re-compile with WITH_GPU option"; #endif for (size_t i = 0; i < devices.size(); ++i) { if (devices[i] >= count || devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); } void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); google::InstallFailureSignalHandler(); } } // namespace framework } // namespace paddle <commit_msg>Fix InitGflags.<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <stdexcept> #include <string> #include "paddle/fluid/framework/init.h" #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" namespace paddle { namespace framework { std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(1) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { cudaSetDevice(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitDevices(bool init_p2p) { /*Init all available devices by default */ #ifdef PADDLE_WITH_CUDA std::vector<int> devices; try { int count = platform::GetCUDADeviceCount(); for (int i = 0; i < count; ++i) { devices.push_back(i); } } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #else LOG(WARNING) << "'CUDA' is not supported, Please re-compile with WITH_GPU option"; #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; int count = 0; #ifdef PADDLE_WITH_CUDA try { count = platform::GetCUDADeviceCount(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #else LOG(WARNING) << "'CUDA' is not supported, Please re-compile with WITH_GPU option"; #endif for (size_t i = 0; i < devices.size(); ++i) { if (devices[i] >= count || devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); } void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); google::InstallFailureSignalHandler(); } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gflags/gflags.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cudnn_workspace_helper.h" #endif /** * NOTE(paddle-dev): This file is designed to define all public FLAGS. */ /* Paddle initialization related */ DEFINE_int32(paddle_num_threads, 1, "Number of threads for each paddle instance."); /* Operator related */ DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); /* CUDA related */ #ifdef PADDLE_WITH_CUDA DEFINE_bool( enable_cublas_tensor_op_math, false, "The enable_cublas_tensor_op_math indicate whether to use Tensor Core, " "but it may loss precision. Currently, There are two CUDA libraries that" " use Tensor Cores, cuBLAS and cuDNN. cuBLAS uses Tensor Cores to speed up" " GEMM computations(the matrices must be either half precision or single " "precision); cuDNN uses Tensor Cores to speed up both convolutions(the " "input and output must be half precision) and recurrent neural networks " "(RNNs)."); DEFINE_string(selected_gpus, "", "A list of device ids separated by comma, like: 0,1,2,3. " "This option is useful when doing multi process training and " "each process have only one device (GPU). If you want to use " "all visible devices, set this to empty string. NOTE: the " "reason of doing this is that we want to use P2P communication" "between GPU devices, use CUDA_VISIBLE_DEVICES can only use" "share-memory only."); #endif /* CUDNN related */ #ifdef PADDLE_WITH_CUDA DEFINE_bool(cudnn_deterministic, false, "Whether allow using an autotuning algorithm for convolution " "operator. The autotuning algorithm may be non-deterministic. If " "true, the algorithm is deterministic."); DEFINE_uint64(conv_workspace_size_limit, paddle::platform::kDefaultConvWorkspaceSizeLimitMB, "cuDNN convolution workspace limit in MB unit."); DEFINE_bool(cudnn_exhaustive_search, false, "Whether enable exhaustive search for cuDNN convolution or " "not, default is False."); DEFINE_int64(cudnn_exhaustive_search_times, -1, "Exhaustive search times for cuDNN convolution, " "default is -1, not exhaustive search"); // CUDNN_BATCHNORM_SPATIAL_PERSISTENT in batchnorm. This mode can be faster in // some tasks because an optimized path may be selected for CUDNN_DATA_FLOAT // and CUDNN_DATA_HALF data types, compute capability 6.0 or higher. The // reason we set it to false by default is that this mode may use scaled // atomic integer reduction that may cause a numerical overflow for certain // input data range. DEFINE_bool(cudnn_batchnorm_spatial_persistent, false, "Whether enable CUDNN_BATCHNORM_SPATIAL_PERSISTENT mode for cudnn " "batch_norm, default is False."); #endif /* NCCL related */ #ifdef PADDLE_WITH_CUDA // asynchronous nccl allreduce or synchronous issue: // https://github.com/PaddlePaddle/Paddle/issues/15049 // If you want to change this default value, why?(gongwb) DEFINE_bool( sync_nccl_allreduce, true, "If set true, will call `cudaStreamSynchronize(nccl_stream)`" "after allreduce, this mode can get better performance in some scenarios."); #endif /* Distributed related */ #ifdef PADDLE_WITH_DISTRIBUTE DEFINE_int32(communicator_max_merge_var_num, 20, "max var num to merge and send"); DEFINE_int32(communicator_send_queue_size, 20, "queue size to recv gradient before send"); #endif DEFINE_int32(dist_threadpool_size, 0, "number of threads used for distributed executed."); /* Garbage collector related */ // Disable gc by default when inference library is built #ifdef PADDLE_ON_INFERENCE static const double kDefaultEagerDeleteTensorGB = -1; #else static const double kDefaultEagerDeleteTensorGB = 0; #endif DEFINE_double( eager_delete_tensor_gb, kDefaultEagerDeleteTensorGB, "Memory size threshold (GB) when the garbage collector clear tensors." "Disabled when this value is less than 0"); DEFINE_bool(fast_eager_deletion_mode, true, "Fast eager deletion mode. If enabled, memory would release " "immediately without waiting GPU kernel ends."); DEFINE_double(memory_fraction_of_eager_deletion, 1.0, "Fraction of eager deletion. If less than 1.0, all variables in " "the program would be sorted according to its memory size, and " "only the FLAGS_memory_fraction_of_eager_deletion of the largest " "variables would be deleted."); /* Allocator related */ DEFINE_string(allocator_strategy, "naive_best_fit", "The allocation strategy. naive_best_fit means the original best " "fit allocator of Fluid. " "auto_growth means the experimental auto-growth allocator. " "Enum in [naive_best_fit, auto_growth]."); DEFINE_double(fraction_of_cpu_memory_to_use, 1, "Default use 100% of CPU memory for PaddlePaddle," "reserve the rest for page tables, etc"); DEFINE_uint64(initial_cpu_memory_in_mb, 500ul, "Initial CPU memory for PaddlePaddle, in MD unit."); DEFINE_double( fraction_of_cuda_pinned_memory_to_use, 0.5, "Default use 50% of CPU memory as the pinned_memory for PaddlePaddle," "reserve the rest for page tables, etc"); #ifdef PADDLE_WITH_CUDA #ifndef _WIN32 constexpr static float fraction_of_gpu_memory_to_use = 0.92f; #else // fraction_of_gpu_memory_to_use cannot be too high on windows, // since the win32 graphic sub-system can occupy some GPU memory // which may lead to insufficient memory left for paddle constexpr static float fraction_of_gpu_memory_to_use = 0.5f; #endif DEFINE_double(fraction_of_gpu_memory_to_use, fraction_of_gpu_memory_to_use, "Allocate a trunk of gpu memory that is this fraction of the " "total gpu memory size. Future memory usage will be allocated " "from the trunk. If the trunk doesn't have enough gpu memory, " "additional trunks of the same size will be requested from gpu " "until the gpu has no memory left for another trunk."); DEFINE_uint64( initial_gpu_memory_in_mb, 0ul, "Allocate a trunk of gpu memory whose byte size is specified by " "the flag. Future memory usage will be allocated from the " "trunk. If the trunk doesn't have enough gpu memory, additional " "trunks of the gpu memory will be requested from gpu with size " "specified by FLAGS_reallocate_gpu_memory_in_mb until the gpu has " "no memory left for the additional trunk. Note: if you set this " "flag, the memory size set by " "FLAGS_fraction_of_gpu_memory_to_use will be overrided by this " "flag. If you don't set this flag, PaddlePaddle will use " "FLAGS_fraction_of_gpu_memory_to_use to allocate gpu memory"); DEFINE_uint64(reallocate_gpu_memory_in_mb, 0ul, "If this flag is set, Paddle will reallocate the gpu memory with " "size specified by this flag. Else Paddle will reallocate by " "FLAGS_fraction_of_gpu_memory_to_use"); #endif <commit_msg>Add document annotations for FLAGS that need to be open to external developers test=develop (#19692)<commit_after>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gflags/gflags.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cudnn_workspace_helper.h" #endif /** * NOTE(paddle-dev): This file is designed to define all public FLAGS. */ /** * Paddle initialization related FLAG * Name: FLAGS_paddle_num_threads * Since Version: 0.15.0 * Value Range: int32, default=1 * Example: FLAGS_paddle_num_threads=2, set the maximum thread number per * instance to 2 * Note: */ DEFINE_int32(paddle_num_threads, 1, "Number of threads for each paddle instance."); /** * Operator related FLAG * Name: FLAGS_check_nan_inf * Since Version: 0.13.0 * Value Range: bool, default=false * Example: * Note: Used to debug. Checking whether operator produce NAN/INF or not. */ DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); #ifdef PADDLE_WITH_CUDA /** * CUDA related related FLAG * Name: FLAGS_enable_cublas_tensor_op_math * Since Version: 1.2.0 * Value Range: bool, default=false * Example: * Note: whether to use Tensor Core, faster but it may loss precision. */ DEFINE_bool( enable_cublas_tensor_op_math, false, "The enable_cublas_tensor_op_math indicate whether to use Tensor Core, " "but it may loss precision. Currently, There are two CUDA libraries that" " use Tensor Cores, cuBLAS and cuDNN. cuBLAS uses Tensor Cores to speed up" " GEMM computations(the matrices must be either half precision or single " "precision); cuDNN uses Tensor Cores to speed up both convolutions(the " "input and output must be half precision) and recurrent neural networks " "(RNNs)."); /** * CUDA related FLAG * Name: FLAGS_selected_gpus * Since Version: 1.3.0 * Value Range: integer list separated by comma, default empty list * Example: FLAGS_selected_gpus=0,1,2,3,4,5,6,7 to train or predict with 0~7 gpu * cards * Note: A list of device ids separated by comma, like: 0,1,2,3 */ DEFINE_string(selected_gpus, "", "A list of device ids separated by comma, like: 0,1,2,3. " "This option is useful when doing multi process training and " "each process have only one device (GPU). If you want to use " "all visible devices, set this to empty string. NOTE: the " "reason of doing this is that we want to use P2P communication" "between GPU devices, use CUDA_VISIBLE_DEVICES can only use" "share-memory only."); #endif #ifdef PADDLE_WITH_CUDA /** * CUDNN related FLAG * Name: FLAGS_cudnn_deterministic * Since Version: 0.13.0 * Value Range: bool, default=false * Example: * Note: whether to use deterministic algorithm in cudnn. * If true, it will slow down some operators such as conv and pooling. */ DEFINE_bool(cudnn_deterministic, false, "Whether allow using an autotuning algorithm for convolution " "operator. The autotuning algorithm may be non-deterministic. If " "true, the algorithm is deterministic."); /** * CUDNN related FLAG * Name: FLAGS_conv_workspace_size_limit * Since Version: 0.13.0 * Value Range: uint64, default=4096 (MB) * Example: * Note: The internal function of cuDNN obtains the fastest matching algorithm * within this memory limit. Usually, faster algorithms can be chosen in * larger workspaces, but memory space can also be significantly * increased. * Users need to balance memory and speed. */ DEFINE_uint64(conv_workspace_size_limit, paddle::platform::kDefaultConvWorkspaceSizeLimitMB, "cuDNN convolution workspace limit in MB unit."); /** * CUDNN related FLAG * Name: FLAGS_cudnn_exhaustive_search * Since Version: 1.2.0 * Value Range: bool, default=false * Example: * Note: Represents whether an exhaustive search method is used to * select a convolution algorithm. There are two search methods in cuDNN, * heuristic search and exhaustive search. Exhaustive search attempts * all cuDNN algorithms to select the fastest. This method is very * time-consuming, and the selected algorithm will be cached for a given * layer specification. Once you change the layer specifications * (such as batch size, feature map size), it will search again. */ DEFINE_bool(cudnn_exhaustive_search, false, "Whether enable exhaustive search for cuDNN convolution or " "not, default is False."); /** * CUDNN related FLAG * Name: FLAGS_cudnn_exhaustive_search_times * Since Version: * Value Range: * Example: * Note: only used to predict for advanced developer */ DEFINE_int64(cudnn_exhaustive_search_times, -1, "Exhaustive search times for cuDNN convolution, " "default is -1, not exhaustive search"); /** * CUDNN related FLAG * Name: FLAGS_cudnn_batchnorm_spatial_persistent * Since Version: 1.4.0 * Value Range: bool, default=false * Example: * Note: CUDNN_BATCHNORM_SPATIAL_PERSISTENT in batchnorm. This mode can be * faster in * some tasks because an optimized path may be selected for * CUDNN_DATA_FLOAT * and CUDNN_DATA_HALF data types, compute capability 6.0 or higher. The * reason we set it to false by default is that this mode may use scaled * atomic integer reduction that may cause a numerical overflow for * certain * input data range. */ DEFINE_bool(cudnn_batchnorm_spatial_persistent, false, "Whether enable CUDNN_BATCHNORM_SPATIAL_PERSISTENT mode for cudnn " "batch_norm, default is False."); #endif #ifdef PADDLE_WITH_CUDA /** * NCCL related FLAG * Name: FLAGS_enable_cublas_tensor_op_math * Since Version: * Value Range: * Example: * Note: asynchronous nccl allreduce or synchronous issue: * https://github.com/PaddlePaddle/Paddle/issues/15049 * If you want to change this default value, why?(gongwb) */ DEFINE_bool( sync_nccl_allreduce, true, "If set true, will call `cudaStreamSynchronize(nccl_stream)`" "after allreduce, this mode can get better performance in some scenarios."); #endif #ifdef PADDLE_WITH_DISTRIBUTE /** * Distributed related FLAG * Name: FLAGS_communicator_max_merge_var_num * Since Version: 1.5.0 * Value Range: int32, default=20 * Example: * Note: The maximum number of gradients to be merged into a gradient and * sent through the communicator. The trainer puts all the gradients * into the queue, and then the communicator takes the gradients out * of the queue and sends them after merging. */ DEFINE_int32(communicator_max_merge_var_num, 20, "max var num to merge and send"); /** * Distributed related FLAG * Name: FLAGS_communicator_send_queue_size * Since Version: 1.5.0 * Value Range: int32, default=20 * Example: * Note: Size for each gradient queue. The trainer puts the gradient into * the queue, and then the communicator takes it out of the queue and * sends it out. When the communicator is slow, the queue may be full, * and the trainer will be continuously blocked before the queue has * space. It is used to avoid training much faster than communication, * so that too many gradients are not sent out in time. */ DEFINE_int32(communicator_send_queue_size, 20, "queue size to recv gradient before send"); #endif /** * Distributed related FLAG * Name: FLAGS_dist_threadpool_size * Since Version: 1.0.0 * Value Range: int32, default=0 * Example: * Note: Control the number of threads used for distributed modules. * If it is not set, it is set to a hard thread. */ DEFINE_int32(dist_threadpool_size, 0, "number of threads used for distributed executed."); /** * Garbage collector related FLAG * Name: FLAGS_eager_delete_tensor_gb * Since Version: 1.0.0 * Value Range: double, default=kDefaultEagerDeleteTensorGB * Example: FLAGS_eager_delete_tensor_gb=0.0, Release memory garbage once it is * no longer used. * FLAGS_eager_delete_tensor_gb=1.0, Release memory garbage when * garbage occupies 1.0GB of memory. * FLAGS_eager_delete_tensor_gb=-1.0, Disable garbage collection * policy. * Note: Represents whether a garbage collection strategy is used to optimize * network memory usage. * It is recommended that users set FLAGS_eager_delete_tensor_gb=0.0 to * enable garbage collection strategy when training large networks. */ // Disable gc by default when inference library is built #ifdef PADDLE_ON_INFERENCE static const double kDefaultEagerDeleteTensorGB = -1; #else static const double kDefaultEagerDeleteTensorGB = 0; #endif DEFINE_double( eager_delete_tensor_gb, kDefaultEagerDeleteTensorGB, "Memory size threshold (GB) when the garbage collector clear tensors." "Disabled when this value is less than 0"); /** * Memory related FLAG * Name: FLAGS_fast_eager_deletion_mode * Since Version: 1.3.0 * Value Range: bool, default=true * Example: * Note: Whether to use fast garbage collection strategy. * If not set, the GPU memory is released at the end of the CUDA kernel. * Otherwise, the GPU memory will be released before the CUDA kernel * has finished, which will make the garbage collection strategy faster. * Only works when garbage collection strategy is enabled. */ DEFINE_bool(fast_eager_deletion_mode, true, "Fast eager deletion mode. If enabled, memory would release " "immediately without waiting GPU kernel ends."); /** * Memory related FLAG * Name: FLAGS_memory_fraction_of_eager_deletion * Since Version: 1.4 * Value Range: double [0.0, 1.0], default=1.0 * Example: * Note: The percentage of memory size of garbage collection policy * to release variables. * If FLAGS_memory_fraction_of_eager_deletion = 1.0, * all temporary variables in the network will be released. * If FLAGS_memory_fraction_of_eager_deletion = 0.0, * no temporary variables in the network are released. * If 0.0 < FLAGS_memory_fraction_of_eager_deletion < 1.0, * all temporary variables will be sorted in descending order * according to their memory size, and only variables with the * largest FLAGS_memory_fraction_of_eager_deletion ratio will be released. * The flag is only valid when running parallel data compilers. */ DEFINE_double(memory_fraction_of_eager_deletion, 1.0, "Fraction of eager deletion. If less than 1.0, all variables in " "the program would be sorted according to its memory size, and " "only the FLAGS_memory_fraction_of_eager_deletion of the largest " "variables would be deleted."); /** * Allocator related FLAG * Name: FLAGS_allocator_strategy * Since Version: 1.2 * Value Range: string, {naive_best_fit, auto_groth}, default=naive_best_fit * Example: * Note: Allocator policy for selecting Paddle Paddle. * The allocator strategy is under development and the non-legacy * allocator is not yet stable. */ DEFINE_string(allocator_strategy, "naive_best_fit", "The allocation strategy. naive_best_fit means the original best " "fit allocator of Fluid. " "auto_growth means the experimental auto-growth allocator. " "Enum in [naive_best_fit, auto_growth]."); /** * Memory related FLAG * Name: FLAGS_fraction_of_cpu_memory_to_use * Since Version: * Value Range: * Example: * Note: */ DEFINE_double(fraction_of_cpu_memory_to_use, 1, "Default use 100% of CPU memory for PaddlePaddle," "reserve the rest for page tables, etc"); /** * Memory related FLAG * Name: FLAGS_initial_cpu_memory_in_mb * Since Version: 0.14.0 * Value Range: uint64, default=500 (MB) * Example: * Note: The CPU memory block size of the initial allocator in MB. * The allocator takes the minimum values of * FLAGS_initial_cpu_memory_in_mb and * FLAGS_fraction_of_cpu_memory_to_use*(total physical memory) * as memory block sizes. */ DEFINE_uint64(initial_cpu_memory_in_mb, 500ul, "Initial CPU memory for PaddlePaddle, in MD unit."); /** * Memory related FLAG * Name: FLAGS_fraction_of_cuda_pinned_memory_to_use * Since Version: * Value Range: * Example: * Note: */ DEFINE_double( fraction_of_cuda_pinned_memory_to_use, 0.5, "Default use 50% of CPU memory as the pinned_memory for PaddlePaddle," "reserve the rest for page tables, etc"); #ifdef PADDLE_WITH_CUDA /** * Memory related FLAG * Name: FLAGS_fraction_of_gpu_memory_to_use * Since Version: 1.2.0 * Value Range: double, default=0.5 if win32, 0.92 else * Example: * Note: Represents the proportion of allocated memory blocks to the total * memory size * of the GPU. Future memory usage will be allocated from this memory * block. * If the memory block does not have enough GPU memory, new memory blocks * of * the same size as the memory block will be allocated from the GPU * request * until the GPU does not have enough memory. */ #ifndef _WIN32 constexpr static float fraction_of_gpu_memory_to_use = 0.92f; #else // fraction_of_gpu_memory_to_use cannot be too high on windows, // since the win32 graphic sub-system can occupy some GPU memory // which may lead to insufficient memory left for paddle constexpr static float fraction_of_gpu_memory_to_use = 0.5f; #endif DEFINE_double(fraction_of_gpu_memory_to_use, fraction_of_gpu_memory_to_use, "Allocate a trunk of gpu memory that is this fraction of the " "total gpu memory size. Future memory usage will be allocated " "from the trunk. If the trunk doesn't have enough gpu memory, " "additional trunks of the same size will be requested from gpu " "until the gpu has no memory left for another trunk."); /** * Memory related FLAG * Name: FLAGS_initial_gpu_memory_in_mb * Since Version: 1.4.0 * Value Range: uint64, default=0 (MB) * Example: * Note: Allocate a specified size of GPU memory block. Later memory usage * will be allocated from that memory block. If the memory block does not * have enough GPU memory, the memory block with the size * FLAGS_reallocate_gpu_memory_in_mb will be requested from the GPU until * the GPU has no remaining memory. */ DEFINE_uint64( initial_gpu_memory_in_mb, 0ul, "Allocate a trunk of gpu memory whose byte size is specified by " "the flag. Future memory usage will be allocated from the " "trunk. If the trunk doesn't have enough gpu memory, additional " "trunks of the gpu memory will be requested from gpu with size " "specified by FLAGS_reallocate_gpu_memory_in_mb until the gpu has " "no memory left for the additional trunk. Note: if you set this " "flag, the memory size set by " "FLAGS_fraction_of_gpu_memory_to_use will be overrided by this " "flag. If you don't set this flag, PaddlePaddle will use " "FLAGS_fraction_of_gpu_memory_to_use to allocate gpu memory"); /** * Memory related FLAG * Name: FLAGS_reallocate_gpu_memory_in_mb * Since Version: 1.4.0 * Value Range: uint64, default=0 (MB) * Example: * Note: If the allocated GPU memory blocks are exhausted, * additional GPU memory blocks are reallocated */ DEFINE_uint64(reallocate_gpu_memory_in_mb, 0ul, "If this flag is set, Paddle will reallocate the gpu memory with " "size specified by this flag. Else Paddle will reallocate by " "FLAGS_fraction_of_gpu_memory_to_use"); #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: ANTS.cxx,v $ Language: C++ Date: $Date: 2008/11/15 23:46:05 $ Version: $Revision: 1.19 $ Copyright (c) 2002 Insight 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. =========================================================================*/ #include "itkPICSLAdvancedNormalizationToolKit.h" #include "itkANTSImageTransformation.h" #include "itkANTSImageRegistrationOptimizer.h" #include <string> template <unsigned int ImageDimension> int ANTSex(int argc, char *argv[]) { typedef itk::PICSLAdvancedNormalizationToolKit<ImageDimension> RegistrationType; typename RegistrationType::Pointer registration = RegistrationType::New(); registration->ParseCommandLine( argc, argv ); std::cout << " Run Reg " << std::endl; try { registration->RunRegistration(); } catch(...) { std::cerr << "Exception thrown: ANTS" << std::endl; return EXIT_FAILURE; } registration->GetTransformationModel()->SetWriteComponentImages(true); registration->GetTransformationModel()->Write(); return EXIT_SUCCESS; } int main(int argc, char *argv[] ) { int dim = 2; // while(argc--) printf("%s\n", *argv++); if ( argc < 2 ) { std::cout << " Call to get detailed usage : \n ANTS -h \n or \n ANTS --help \n \n " << std::endl; std::cout << " typical use, for a 3D image matching with mutual information : \n ANTS 3 -m MI[fixedimage.nii,movingimage.nii,1,32] -o MutualInformationMapping.nii -i 30x20x0 -r Gauss[3,1] -t Elast[3] " << std::endl; std::cout << " the value 32 in the metric call ( -m MI[ ...] ) is the joint histogram # of bins " << std::endl; std::cout << " the transformation model is elastic with gradient descent step-length of 3 " << std::endl; std::cout << " 3 levels of optimization with 30 iterations at the coarsest (fastest) level, 20 at the next and 0 at full resolution " << std::endl; std::cout << " \n typical use, for a 3D image matching with correlation : \n ANTS 3 -m PR[fixedimage.nii,movingimage.nii,1,2] -o CC.nii -i 30x20x0 -r Gauss[3,0] -t SyN[1] " << std::endl; std::cout << " the value 2 in the metric call ( -m PR[ ...] ) is the radius of the correlation window " << std::endl; std::cout << " the transformation is the greedy symmetric diffeomorphic mapping with xgradient descent step-length of 1" << std::endl; std::cout << " \n typical use, for a 3D image matching with correlation implementation 2 : \n ANTS 3 -m CC[fixedimage.nii,movingimage.nii,1,2] -o CC2.nii -i 30x20x0 -r Gauss[3,0.5] -t SyN[1,2,0.1] " << std::endl; std::cout << " the value 2 in the metric call ( -m CC[ ...] ) is the radius of the correlation window " << std::endl; std::cout << " the transformation is the symmetric diffeomorphic mapping with time-varying velocity fied - 10 integration points in time and gradient step length of 1 " << std::endl; std::cout << " \n Call to get detailed usage : \n ANTS -h \n or \n ANTS --help \n \n " << std::endl; return 1; } else dim = atoi( argv[1] ); if ( dim <= 1 || dim > 3 ) { std::cout <<" you passed image dimension (first argument) as " << dim << " ANTS does not function with images of this dimension " << std::endl; argv[1]=(char*)("--help"); ANTSex<2>( argc,argv ); exit(1); } /** * Try the simple case of the call "ANTS fixedImage movingImage" */ if( argc == 3 && ( atoi( argv[1] ) != 2 || atoi( argv[1] ) != 3 ) ) { itk::ImageIOBase::Pointer fixedImageIO = itk::ImageIOFactory::CreateImageIO( argv[1], itk::ImageIOFactory::ReadMode ); if( fixedImageIO.IsNull() ) { std::cerr << "Invalid fixed image: " << argv[1] << std::endl; return EXIT_FAILURE; } itk::ImageIOBase::Pointer movingImageIO = itk::ImageIOFactory::CreateImageIO( argv[2], itk::ImageIOFactory::ReadMode ); if( movingImageIO.IsNull() ) { std::cerr << "Invalid moving image: " << argv[2] << std::endl; return EXIT_FAILURE; } fixedImageIO->SetFileName( argv[1] ); fixedImageIO->ReadImageInformation(); movingImageIO->SetFileName( argv[2] ); movingImageIO->ReadImageInformation(); unsigned int fdim = fixedImageIO->GetNumberOfDimensions(); unsigned int mdim = movingImageIO->GetNumberOfDimensions(); if( fdim != mdim ) { std::cerr << "Fixed image dimension does not equal " << "the moving image dimension (" << fdim << " != " << mdim << ")" << std::endl; return EXIT_FAILURE; } if( fdim != 2 && fdim != 3 ) { std::cerr << "Unsupported image dimension" << std::endl; return EXIT_FAILURE; } /** * After the checking, we can add the default parameters; */ std::string arguments; std::string transformation( " -t SyN[1.0] "); std::string regularization( " -r Gauss[3,0.5] "); std::string metric = std::string( " -m PR[" ) + std::string( argv[1] ) + std::string( "," ) + std::string( argv[2] ) + std::string( ",1,3] " ); std::string outputNaming( " -o ANTS.nii.gz " ); long maxSize = vnl_math_min( fixedImageIO->GetDimensions( 0 ), movingImageIO->GetDimensions( 0 ) ); for( unsigned int d = 1; d < fdim; d++ ) { long tmpMax = vnl_math_max( fixedImageIO->GetDimensions( d ), movingImageIO->GetDimensions( d ) ); if( maxSize < tmpMax ) { maxSize = tmpMax; } } unsigned int numberOfLevels = static_cast<unsigned int>( vcl_log( (double)maxSize / 32 ) / vcl_log( (double) 2 ) ) + 1; std::string iterations( " -i " ); for( int n = numberOfLevels; n > 0; n-- ) { itk::OStringStream buf; unsigned long numberOfIterations = ( 5 << (n-1) ); buf << numberOfIterations << "x"; iterations += buf.str(); } iterations = iterations.substr( 0, iterations.length()-1 ); itk::OStringStream dimBuf; dimBuf << fdim; arguments.clear(); arguments = std::string( " ANTS " ) + dimBuf.str() + iterations + transformation + regularization + metric + outputNaming; dim = fdim; std::cout << arguments << std::endl; unsigned int my_argc = 0; std::string::size_type delimPos = 0; std::string::size_type tokenPos = 0; std::string::size_type pos = 0; while( true ) { delimPos = arguments.find_first_of( " ", pos ); tokenPos = arguments.find_first_not_of( " ", pos ); if( std::string::npos != delimPos && std::string::npos != tokenPos && tokenPos < delimPos ) { my_argc++; } else if( std::string::npos == delimPos ) { if( std::string::npos != tokenPos ) { my_argc++; } else { break; } } pos = delimPos + 1; } unsigned int arg_count = 0; char **my_argv = new char*[my_argc]; delimPos = 0; tokenPos = 0; pos = 0; while( true ) { delimPos = arguments.find_first_of( " ", pos ); tokenPos = arguments.find_first_not_of( " ", pos ); if( std::string::npos != delimPos && std::string::npos != tokenPos && tokenPos < delimPos ) { std::string arg = arguments.substr( pos, delimPos-pos ); my_argv[arg_count] = new char[arg.size() + 1]; strcpy( my_argv[arg_count], arg.c_str() ); arg_count++; } else if( std::string::npos == delimPos ) { if( std::string::npos != tokenPos ) { std::string arg = arguments.substr( pos ); my_argv[arg_count] = new char[arg.size() + 1]; strcpy( my_argv[arg_count], arg.c_str() ); arg_count++; } else { break; } } pos = delimPos + 1; } switch ( dim ) { case 3: ANTSex<3>( my_argc, my_argv ); break; default: ANTSex<2>( my_argc, my_argv ); } } else { switch ( dim ) { case 3: ANTSex<3>( argc, argv ); break; default: ANTSex<2>( argc, argv ); } } return EXIT_SUCCESS; } <commit_msg> Thanks NM vanStrien <commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: ANTS.cxx,v $ Language: C++ Date: $Date: 2008/11/15 23:46:05 $ Version: $Revision: 1.19 $ Copyright (c) 2002 Insight 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. =========================================================================*/ #include "itkPICSLAdvancedNormalizationToolKit.h" #include "itkANTSImageTransformation.h" #include "itkANTSImageRegistrationOptimizer.h" #include <string> template <unsigned int ImageDimension> int ANTSex(int argc, char *argv[]) { typedef itk::PICSLAdvancedNormalizationToolKit<ImageDimension> RegistrationType; typename RegistrationType::Pointer registration = RegistrationType::New(); registration->ParseCommandLine( argc, argv ); std::cout << " Run Reg " << std::endl; try { registration->RunRegistration(); } catch(...) { std::cerr << "Exception thrown: ANTS" << std::endl; return EXIT_FAILURE; } registration->GetTransformationModel()->SetWriteComponentImages(true); registration->GetTransformationModel()->Write(); return EXIT_SUCCESS; } int main(int argc, char *argv[] ) { int dim = 2; // while(argc--) printf("%s\n", *argv++); if ( argc < 2 ) { std::cout << " \n " << std::endl; std::cout << "Example usage: \n " << std::endl; std::cout << argv[0] << " ImageDimension -m MI[fixedimage.nii.gz,movingimage.nii.gz,1,32] -o Outputfname.nii.gz -i 30x20x0 -r Gauss[3,1] -t Elast[3] \n \n " << std::endl; std::cout << " Compulsory arguments:\n " << std::endl; std::cout << " ImageDimension: 2 or 3 (for 2 or 3 Dimensional registration)\n " << std::endl; std::cout << " -m: Type of similarity model used for registration. \n " << std::endl; std::cout << " For intramodal image registration, use: " << std::endl; std::cout << " CC = cross-correlation " << std::endl; std::cout << " MI = mutual information " << std::endl; std::cout << " PR = probability mapping " << std::endl; std::cout << " MSQ = mean square difference " << std::endl; std::cout << " \n " << std::endl; std::cout << " For intermodal image registration, use: " << std::endl; std::cout << " MI = mutual information " << std::endl; std::cout << " PR = probability mapping " << std::endl; std::cout << " \n " << std::endl; std::cout << " -o Outputfname.nii.gz: the name of the resulting image.\n " << std::endl; std::cout << " -i Max-iterations in format: JxKxL, where: " << std::endl; std::cout << " J = max iterations at coarsest resolution (here, reduce by power of 2^2) " << std::endl; std::cout << " K = middle resolution iterations (here,reduce by power of 2) " << std::endl; std::cout << " L = fine resolution iterations (here, full resolution). This level takes much more time per iteration!\n " << std::endl; std::cout << " Adding an extra value before JxKxL (i.e. resulting in IxJxKxL) would add another iteration level.\n " << std::endl; std::cout << " -r Regularization \n" << std::endl; std::cout << " -t Type of transformation model used for registration \n" << std::endl; std::cout << " For elastic image registration, use: " << std::endl; std::cout << " Elast = elastic transformation model (less deformation possible)\n " << std::endl; std::cout << " For diffeomorphic image registration, use: " << std::endl; std::cout << " Syn[GradStep,TimePoints,IntegrationStep] --geodesic 2 = SyN with time with arbitrary number of time points in time discretization " << std::endl; std::cout << " SyN[GradStep,2,IntegrationStep] = SyN with time optimized specifically for 2 time points in the time discretization " << std::endl; std::cout << " SyN[GradStep] = Greedy SyN, typicall GradStep=0.25 " << std::endl; std::cout << " Exp[GradStep,TimePoints] = Exponential " << std::endl; std::cout << " GreedyExp = Diffeomorphic Demons style exponential mapping " << std::endl; std::cout << " \n " << std::endl; std::cout << " Please use the "ANTS -h " call or refer to the ANTS.pdf manual or antsIntroduction.sh script for additional information and typical values for transformation models\n " << std::endl; return 1; } else dim = atoi( argv[1] ); if ( dim <= 1 || dim > 3 ) { std::cout <<" You passed ImageDimension: " << dim << " . Please use only 2 or 3 (for 2 or 3 Dimensional registration) " << std::endl; argv[1]=(char*)("--help"); ANTSex<2>( argc,argv ); exit(1); } /** * Try the simple case of the call "ANTS fixedImage movingImage" */ if( argc == 3 && ( atoi( argv[1] ) != 2 || atoi( argv[1] ) != 3 ) ) { itk::ImageIOBase::Pointer fixedImageIO = itk::ImageIOFactory::CreateImageIO( argv[1], itk::ImageIOFactory::ReadMode ); if( fixedImageIO.IsNull() ) { std::cerr << "Invalid fixed image: " << argv[1] << std::endl; return EXIT_FAILURE; } itk::ImageIOBase::Pointer movingImageIO = itk::ImageIOFactory::CreateImageIO( argv[2], itk::ImageIOFactory::ReadMode ); if( movingImageIO.IsNull() ) { std::cerr << "Invalid moving image: " << argv[2] << std::endl; return EXIT_FAILURE; } fixedImageIO->SetFileName( argv[1] ); fixedImageIO->ReadImageInformation(); movingImageIO->SetFileName( argv[2] ); movingImageIO->ReadImageInformation(); unsigned int fdim = fixedImageIO->GetNumberOfDimensions(); unsigned int mdim = movingImageIO->GetNumberOfDimensions(); if( fdim != mdim ) { std::cerr << "Fixed image dimension does not equal " << "the moving image dimension (" << fdim << " != " << mdim << ")" << std::endl; return EXIT_FAILURE; } if( fdim != 2 && fdim != 3 ) { std::cerr << "Unsupported image dimension" << std::endl; return EXIT_FAILURE; } /** * After the checking, we can add the default parameters; */ std::string arguments; std::string transformation( " -t SyN[1.0] "); std::string regularization( " -r Gauss[3,0.5] "); std::string metric = std::string( " -m PR[" ) + std::string( argv[1] ) + std::string( "," ) + std::string( argv[2] ) + std::string( ",1,3] " ); std::string outputNaming( " -o ANTS.nii.gz " ); long maxSize = vnl_math_min( fixedImageIO->GetDimensions( 0 ), movingImageIO->GetDimensions( 0 ) ); for( unsigned int d = 1; d < fdim; d++ ) { long tmpMax = vnl_math_max( fixedImageIO->GetDimensions( d ), movingImageIO->GetDimensions( d ) ); if( maxSize < tmpMax ) { maxSize = tmpMax; } } unsigned int numberOfLevels = static_cast<unsigned int>( vcl_log( (double)maxSize / 32 ) / vcl_log( (double) 2 ) ) + 1; std::string iterations( " -i " ); for( int n = numberOfLevels; n > 0; n-- ) { itk::OStringStream buf; unsigned long numberOfIterations = ( 5 << (n-1) ); buf << numberOfIterations << "x"; iterations += buf.str(); } iterations = iterations.substr( 0, iterations.length()-1 ); itk::OStringStream dimBuf; dimBuf << fdim; arguments.clear(); arguments = std::string( " ANTS " ) + dimBuf.str() + iterations + transformation + regularization + metric + outputNaming; dim = fdim; std::cout << arguments << std::endl; unsigned int my_argc = 0; std::string::size_type delimPos = 0; std::string::size_type tokenPos = 0; std::string::size_type pos = 0; while( true ) { delimPos = arguments.find_first_of( " ", pos ); tokenPos = arguments.find_first_not_of( " ", pos ); if( std::string::npos != delimPos && std::string::npos != tokenPos && tokenPos < delimPos ) { my_argc++; } else if( std::string::npos == delimPos ) { if( std::string::npos != tokenPos ) { my_argc++; } else { break; } } pos = delimPos + 1; } unsigned int arg_count = 0; char **my_argv = new char*[my_argc]; delimPos = 0; tokenPos = 0; pos = 0; while( true ) { delimPos = arguments.find_first_of( " ", pos ); tokenPos = arguments.find_first_not_of( " ", pos ); if( std::string::npos != delimPos && std::string::npos != tokenPos && tokenPos < delimPos ) { std::string arg = arguments.substr( pos, delimPos-pos ); my_argv[arg_count] = new char[arg.size() + 1]; strcpy( my_argv[arg_count], arg.c_str() ); arg_count++; } else if( std::string::npos == delimPos ) { if( std::string::npos != tokenPos ) { std::string arg = arguments.substr( pos ); my_argv[arg_count] = new char[arg.size() + 1]; strcpy( my_argv[arg_count], arg.c_str() ); arg_count++; } else { break; } } pos = delimPos + 1; } switch ( dim ) { case 3: ANTSex<3>( my_argc, my_argv ); break; default: ANTSex<2>( my_argc, my_argv ); } } else { switch ( dim ) { case 3: ANTSex<3>( argc, argv ); break; default: ANTSex<2>( argc, argv ); } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 Google 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 <cstdint> #include <cstring> #include <iostream> #include <string> #if _WIN32 #include <fcntl.h> #include <stdio.h> #endif #include <google/protobuf/util/json_util.h> #include "core/os/device/device.pb.h" #include "core/os/device/deviceinfo/cc/instance.h" void print_help() { std::cout << "Usage: device-info [--binary]" << std::endl; std::cout << "Output information about the current device." << std::endl; std::cout << " --binary Output a binary protobuf instead of json" << std::endl; } int main(int argc, char const *argv[]) { bool output_binary = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) { print_help(); return 0; } else if (strcmp(argv[i], "--binary") == 0) { output_binary = true; } else { print_help(); return -1; } } device_instance instance = get_device_instance(); if (output_binary) { #if _WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif std::cout << std::string(reinterpret_cast<char *>(instance.data), instance.size); } else { device::Instance device_inst; if (!device_inst.ParseFromArray(instance.data, instance.size)) { std::cerr << "Internal error." << std::endl; free_device_instance(instance); return -1; } std::string output; google::protobuf::util::JsonPrintOptions options; options.add_whitespace = true; if (google::protobuf::util::Status::OK != google::protobuf::util::MessageToJsonString(device_inst, &output, options)) { std::cerr << "Internal error: Could not convert to json" << std::endl; free_device_instance(instance); return -1; } std::cout << output; } free_device_instance(instance); return 0; } <commit_msg>Use logging function for error reporting (#2694)<commit_after>/* * Copyright (C) 2018 Google 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 <cstdint> #include <cstring> #include <iostream> #include <string> #if _WIN32 #include <fcntl.h> #include <stdio.h> #endif #include <google/protobuf/util/json_util.h> #include "core/cc/log.h" #include "core/os/device/device.pb.h" #include "core/os/device/deviceinfo/cc/instance.h" void print_help() { std::cout << "Usage: device-info [--binary]" << std::endl; std::cout << "Output information about the current device." << std::endl; std::cout << " --binary Output a binary protobuf instead of json" << std::endl; } int main(int argc, char const *argv[]) { bool output_binary = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) { print_help(); return 0; } else if (strcmp(argv[i], "--binary") == 0) { output_binary = true; } else { print_help(); return -1; } } device_instance instance = get_device_instance(); if (output_binary) { #if _WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif std::cout << std::string(reinterpret_cast<char *>(instance.data), instance.size); } else { device::Instance device_inst; if (!device_inst.ParseFromArray(instance.data, instance.size)) { GAPID_ERROR("Internal error"); free_device_instance(instance); return -1; } std::string output; google::protobuf::util::JsonPrintOptions options; options.add_whitespace = true; if (google::protobuf::util::Status::OK != google::protobuf::util::MessageToJsonString(device_inst, &output, options)) { GAPID_ERROR("Internal error: Could not convert to json"); free_device_instance(instance); return -1; } std::cout << output; } free_device_instance(instance); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Shanghai Jiao Tong University. * 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. * * For more about this software visit: * * http://ipads.se.sjtu.edu.cn/projects/wukong.html * */ #pragma once #include <iostream> #include <string> #include <set> #include <boost/unordered_map.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include "config.hpp" #include "proxy.hpp" #include "logger.hpp" using namespace std; // communicate between proxy threads TCP_Adaptor *con_adaptor; template<typename T> static void console_send(int sid, int tid, T &r) { std::stringstream ss; boost::archive::binary_oarchive oa(ss); oa << r; con_adaptor->send(sid, tid, ss.str()); } template<typename T> static T console_recv(int tid) { std::string str; str = con_adaptor->recv(tid); std::stringstream ss; ss << str; boost::archive::binary_iarchive ia(ss); T r; ia >> r; return r; } static void console_barrier(int tid) { static int _curr = 0; static __thread int _next = 1; // inter-server barrier if (tid == 0) MPI_Barrier(MPI_COMM_WORLD); // intra-server barrier __sync_fetch_and_add(&_curr, 1); while (_curr < _next) usleep(1); // wait _next += global_num_proxies; // next barrier } void print_help(void) { cout << "These are common Wukong commands: " << endl; cout << " help display help infomation" << endl; cout << " quit quit from console" << endl; cout << " config <args> run commands on config" << endl; cout << " -v print current config" << endl; cout << " -l <file> load config items from <file>" << endl; cout << " -s <string> set config items by <str> (format: item1=val1&item2=...)" << endl; cout << " sparql <args> run SPARQL queries" << endl; cout << " -f <file> [<args>] a single query from <file>" << endl; cout << " -n <num> run <num> times" << endl; cout << " -v <num> print at most <num> lines of results" << endl; cout << " -w <file> write results into <file>" << endl; cout << " -b <file> a set of queries configured by <file>" << endl; } // the master proxy is the 1st proxy of the 1st server (i.e., sid == 0 and tid == 0) #define IS_MASTER(_p) ((_p)->sid == 0 && (_p)->tid == 0) #define PRINT_ID(_p) (cout << "[" << (_p)->sid << "-" << (_p)->tid << "]$ ") static void file2str(string fname, string &str) { ifstream file(fname.c_str()); if (!file) { cout << "ERROR: " << fname << " does not exist." << endl; return; } string line; while (std::getline(file, line)) str += line + " "; } static void args2str(string &str) { size_t found = str.find_first_of("=&"); while (found != string::npos) { str[found] = ' '; found = str.find_first_of("=&", found + 1); } } /** * The Wukong's console is co-located with the main proxy (the 1st proxy thread on the 1st server) * and provide a simple interactive cmdline to tester */ void run_console(Proxy *proxy) { console_barrier(proxy->tid); if (IS_MASTER(proxy)) cout << endl << "Input \'help\'' command to get more information" << endl << endl; while (true) { console_barrier(proxy->tid); next: string cmd; if (IS_MASTER(proxy)) { cout << "> "; std::getline(std::cin, cmd); // trim input size_t pos = cmd.find_first_not_of(" \t"); // trim blanks from head if (pos == string::npos) goto next; cmd.erase(0, pos); pos = cmd.find_last_not_of(" \t"); // trim blanks from tail cmd.erase(pos + 1, cmd.length() - (pos + 1)); // only run <cmd> on the master console if (cmd == "help") { print_help(); goto next; } // send <cmd> to all consoles for (int i = 0; i < global_num_servers; i++) { for (int j = 0; j < global_num_proxies; j++) { if (i == 0 && j == 0) continue ; console_send<string>(i, j, cmd); } } } else { // recieve <cmd> cmd = console_recv<string>(proxy->tid); } // run <cmd> on all consoles if (cmd == "quit" || cmd == "q") { if (proxy->tid == 0) exit(0); // each server exits once by the 1st console } else { std::stringstream cmd_ss(cmd); std::string token; // get keyword of command cmd_ss >> token; if (token == "config") { cmd_ss >> token; if (token == "-v") { // only show config on the master console if (IS_MASTER(proxy)) print_config(); } else if (token == "-l") { // each server load config file once by the 1st console if (proxy->tid != 0) continue; string fname; if (cmd_ss >> fname) { string str; if (IS_MASTER(proxy)) { file2str(fname, str); // send <str> to all consoles for (int i = 1; i < global_num_servers; i++) console_send<string>(i, 0, str); } else { // recieve <str> str = console_recv<string>(proxy->tid); } if (!str.empty()) { reload_config(str); } else { if (IS_MASTER(proxy)) cout << "Failed to load config file: " << fname << endl; } } else { goto failed; } } else if (token == "-s") { // each server set config item once by the 1st console if (proxy->tid != 0) continue; string str; if (cmd_ss >> str) { if (IS_MASTER(proxy)) { args2str(str); // send <str> to all consoles for (int i = 1; i < global_num_servers; i++) console_send<string>(i, 0, str); } else { // recieve <str> str = console_recv<string>(proxy->tid); } reload_config(str); } else { goto failed; } } else { goto failed; } } else if (token == "sparql") { // handle SPARQL queries string fname, bfname, ofname; int cnt = 1, nlines = 0; bool f_enable = false, b_enable = false, o_enable = false; // parse parameters while (cmd_ss >> token) { if (token == "-f") { cmd_ss >> fname; f_enable = true; } else if (token == "-n") { cmd_ss >> cnt; } else if (token == "-v") { cmd_ss >> nlines; } else if (token == "-o") { cmd_ss >> ofname; o_enable = true; } else if (token == "-b") { cmd_ss >> bfname; b_enable = true; } else { goto failed; } } if (!f_enable && !b_enable) goto failed; // meaningless args for SPARQL queries if (f_enable) { // use the main proxy thread to run a single query if (IS_MASTER(proxy)) { ifstream ifs(fname); if (!ifs.good()) { cout << "Query file not found: " << fname << endl; continue ; } ofstream ofs(ofname, std::ios::out); if (o_enable && !ofs.good()) { cout << "Can't open/create output file: " << ofname << endl; continue; } if (global_silent) { if (nlines > 0) { cout << "Can't print results (-v) with global_silent." << endl; continue; } if (o_enable) { cout << "Can't output results (-w) with global_silent." << endl; continue; } } request_or_reply reply; Logger logger; int ret = proxy->run_single_query(ifs, cnt, reply, logger); if (ret != 0) { cout << "Failed to run the query (ERROR: " << ret << ")!" << endl; continue; } // print or dump results logger.print_latency(cnt); cout << "(last) result size: " << reply.row_num << endl; if (!global_silent && !reply.blind) { if (nlines > 0) proxy->print_result(reply, min(reply.row_num, nlines)); if (o_enable) proxy->dump_result(reply, ofs); } } } if (b_enable) { Logger logger; // dedicate the master frontend worker to run a single query // and others to run a set of queries if '-f' is enabled if (!f_enable || !IS_MASTER(proxy)) { ifstream ifs(bfname); if (!ifs.good()) { PRINT_ID(proxy); cout << "Configure file not found: " << bfname << endl; continue; } proxy->nonblocking_run_batch_query(ifs, logger); //proxy->run_batch_query(ifs, logger); } console_barrier(proxy->tid); // print a statistic of runtime for the batch processing on all servers if (IS_MASTER(proxy)) { for (int i = 0; i < global_num_servers * global_num_proxies - 1; i++) { Logger other = console_recv<Logger>(proxy->tid); logger.merge(other); } logger.print_rdf(); logger.print_thpt(); } else { // send logs to the master proxy console_send<Logger>(0, 0, logger); } } } else { failed: if (IS_MASTER(proxy)) { cout << "Failed to run the command: " << cmd << endl; print_help(); } } } } } <commit_msg>config command done<commit_after>/* * Copyright (c) 2016 Shanghai Jiao Tong University. * 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. * * For more about this software visit: * * http://ipads.se.sjtu.edu.cn/projects/wukong.html * */ #pragma once #include <iostream> #include <string> #include <set> #include <boost/unordered_map.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include "config.hpp" #include "proxy.hpp" #include "logger.hpp" using namespace std; // communicate between proxy threads TCP_Adaptor *con_adaptor; template<typename T> static void console_send(int sid, int tid, T &r) { std::stringstream ss; boost::archive::binary_oarchive oa(ss); oa << r; con_adaptor->send(sid, tid, ss.str()); } template<typename T> static T console_recv(int tid) { std::string str; str = con_adaptor->recv(tid); std::stringstream ss; ss << str; boost::archive::binary_iarchive ia(ss); T r; ia >> r; return r; } static void console_barrier(int tid) { static int _curr = 0; static __thread int _next = 1; // inter-server barrier if (tid == 0) MPI_Barrier(MPI_COMM_WORLD); // intra-server barrier __sync_fetch_and_add(&_curr, 1); while (_curr < _next) usleep(1); // wait _next += global_num_proxies; // next barrier } void print_help(void) { cout << "These are common Wukong commands: " << endl; cout << " help display help infomation" << endl; cout << " quit quit from console" << endl; cout << " config <args> run commands on config" << endl; cout << " -v print current config" << endl; cout << " -l <file> load config items from <file>" << endl; cout << " -s <string> set config items by <str> (format: item1=val1&item2=...)" << endl; cout << " sparql <args> run SPARQL queries" << endl; cout << " -f <file> [<args>] a single query from <file>" << endl; cout << " -n <num> run <num> times" << endl; cout << " -v <num> print at most <num> lines of results" << endl; cout << " -w <file> write results into <file>" << endl; cout << " -b <file> a set of queries configured by <file>" << endl; } // the master proxy is the 1st proxy of the 1st server (i.e., sid == 0 and tid == 0) #define IS_MASTER(_p) ((_p)->sid == 0 && (_p)->tid == 0) #define PRINT_ID(_p) (cout << "[" << (_p)->sid << "-" << (_p)->tid << "]$ ") static void file2str(string fname, string &str) { ifstream file(fname.c_str()); if (!file) { cout << "ERROR: " << fname << " does not exist." << endl; return; } string line; while (std::getline(file, line)) str += line + " "; } static void args2str(string &str) { size_t found = str.find_first_of("=&"); while (found != string::npos) { str[found] = ' '; found = str.find_first_of("=&", found + 1); } } /** * The Wukong's console is co-located with the main proxy (the 1st proxy thread on the 1st server) * and provide a simple interactive cmdline to tester */ void run_console(Proxy *proxy) { console_barrier(proxy->tid); if (IS_MASTER(proxy)) cout << endl << "Input \'help\'' command to get more information" << endl << endl; while (true) { console_barrier(proxy->tid); next: string cmd; if (IS_MASTER(proxy)) { cout << "> "; std::getline(std::cin, cmd); // trim input size_t pos = cmd.find_first_not_of(" \t"); // trim blanks from head if (pos == string::npos) goto next; cmd.erase(0, pos); pos = cmd.find_last_not_of(" \t"); // trim blanks from tail cmd.erase(pos + 1, cmd.length() - (pos + 1)); // only run <cmd> on the master console if (cmd == "help") { print_help(); goto next; } // send <cmd> to all consoles for (int i = 0; i < global_num_servers; i++) { for (int j = 0; j < global_num_proxies; j++) { if (i == 0 && j == 0) continue ; console_send<string>(i, j, cmd); } } } else { // recieve <cmd> cmd = console_recv<string>(proxy->tid); } // run <cmd> on all consoles if (cmd == "quit" || cmd == "q") { if (proxy->tid == 0) exit(0); // each server exits once by the 1st console } else { std::stringstream cmd_ss(cmd); std::string token; // get keyword of command cmd_ss >> token; if (token == "config") { if (proxy->tid != 0) continue; string fname, str; bool v_enable = false, l_enable = false, s_enable = false; // parse parameters while (cmd_ss >> token) { if (token == "-v") { v_enable = true; } else if (token == "-l") { l_enable = true; if (!(cmd_ss >> fname)) goto failed; } else if (token == "-s") { s_enable = true; if (!(cmd_ss >> str)) goto failed; } else { goto failed; } } if (v_enable) { // -v if (IS_MASTER(proxy)) print_config(); } else if (l_enable || s_enable) { // -l <file> or -s <str> if (IS_MASTER(proxy)) { if (l_enable) // -l file2str(fname, str); else if (s_enable) // -s args2str(str); // send <str> to all consoles for (int i = 1; i < global_num_servers; i++) console_send<string>(i, 0, str); } else { // recieve <str> str = console_recv<string>(proxy->tid); } if (!str.empty()) { reload_config(str); } else { if (IS_MASTER(proxy)) cout << "Failed to load config file: " << fname << endl; } } else { goto failed; } } else if (token == "sparql") { // handle SPARQL queries string fname, bfname, ofname; int cnt = 1, nlines = 0; bool f_enable = false, b_enable = false, o_enable = false; // parse parameters while (cmd_ss >> token) { if (token == "-f") { cmd_ss >> fname; f_enable = true; } else if (token == "-n") { cmd_ss >> cnt; } else if (token == "-v") { cmd_ss >> nlines; } else if (token == "-o") { cmd_ss >> ofname; o_enable = true; } else if (token == "-b") { cmd_ss >> bfname; b_enable = true; } else { goto failed; } } if (!f_enable && !b_enable) goto failed; // meaningless args for SPARQL queries if (f_enable) { // -f <file> // use the main proxy thread to run a single query if (IS_MASTER(proxy)) { ifstream ifs(fname); if (!ifs.good()) { cout << "Query file not found: " << fname << endl; continue ; } ofstream ofs(ofname, std::ios::out); if (o_enable && !ofs.good()) { cout << "Can't open/create output file: " << ofname << endl; continue; } if (global_silent) { if (nlines > 0) { cout << "Can't print results (-v) with global_silent." << endl; continue; } if (o_enable) { cout << "Can't output results (-w) with global_silent." << endl; continue; } } request_or_reply reply; Logger logger; int ret = proxy->run_single_query(ifs, cnt, reply, logger); if (ret != 0) { cout << "Failed to run the query (ERROR: " << ret << ")!" << endl; continue; } // print or dump results logger.print_latency(cnt); cout << "(last) result size: " << reply.row_num << endl; if (!global_silent && !reply.blind) { if (nlines > 0) proxy->print_result(reply, min(reply.row_num, nlines)); if (o_enable) proxy->dump_result(reply, ofs); } } } if (b_enable) { // -b <config> Logger logger; // dedicate the master frontend worker to run a single query // and others to run a set of queries if '-f' is enabled if (!f_enable || !IS_MASTER(proxy)) { ifstream ifs(bfname); if (!ifs.good()) { PRINT_ID(proxy); cout << "Configure file not found: " << bfname << endl; continue; } proxy->nonblocking_run_batch_query(ifs, logger); //proxy->run_batch_query(ifs, logger); } console_barrier(proxy->tid); // print a statistic of runtime for the batch processing on all servers if (IS_MASTER(proxy)) { for (int i = 0; i < global_num_servers * global_num_proxies - 1; i++) { Logger other = console_recv<Logger>(proxy->tid); logger.merge(other); } logger.print_rdf(); logger.print_thpt(); } else { // send logs to the master proxy console_send<Logger>(0, 0, logger); } } } else { failed: if (IS_MASTER(proxy)) { cout << "Failed to run the command: " << cmd << endl; print_help(); } } } } } <|endoftext|>
<commit_before>/* 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/. */ #include "json.h" #include "gtest/gtest.h" using namespace json; TEST(without, non_empty) { EXPECT_EQ("abc", without('<', '>', "<abc>")); } TEST(without, empty) { EXPECT_EQ("", without('<', '>', "<>")); } TEST(without, exception_without_opening_bracket) { EXPECT_THROW(without('<', '>', "abc>"), std::runtime_error); } TEST(without, exception_without_closing_bracket) { EXPECT_THROW(without('<', '>', "<abc"), std::runtime_error); } TEST(withoutCurly, non_empty) { EXPECT_EQ("abc", withoutCurly("{abc}")); } TEST(withoutRect, non_empty) { EXPECT_EQ("abc", withoutRect("[abc]")); } TEST(withoutQuot, non_empty) { EXPECT_EQ("abc", withoutQuot("\"abc\"")); } TEST(find_element_delimiter, simple) { EXPECT_EQ(1, findListDelimiter("a,b")); } TEST(find_element_delimiter, nested) { EXPECT_EQ(5, findListDelimiter("{a,b},c")); } TEST(trimmed, without_spaces) { EXPECT_EQ("hello", trimmed("hello")); } TEST(trimmed, leading_spaces) { EXPECT_EQ("hello", trimmed(" hello")); } TEST(trimmed, trailing_spaces) { EXPECT_EQ("hello", trimmed("hello ")); } TEST(trimmed, one_space) { EXPECT_EQ("", trimmed(" ")); } TEST(trimmed, two_spaces) { EXPECT_EQ("", trimmed(" ")); } TEST(to_json, fromString) { EXPECT_EQ("\"text\"", to_json("text")); } TEST(from_json, toString) { std::string result; from_json(" \"text\" ", result); EXPECT_EQ("text", result); } TEST(to_json, fromStdString) { EXPECT_EQ("\"text\"", to_json(std::string("text"))); } TEST(to_json, fromTrue) { EXPECT_EQ("true", to_json(true)); } TEST(from_json, toTrue) { bool result; from_json("true", result); EXPECT_EQ(true, result); } TEST(to_json, fromFalse) { EXPECT_EQ("false", to_json(false)); } TEST(from_json, toFalse) { bool result; from_json("false", result); EXPECT_EQ(false, result); } TEST(to_json, fromInt) { EXPECT_EQ("-123", to_json(-123)); } TEST(from_json, toInt) { int result; from_json("-123", result); EXPECT_EQ(-123, result); } TEST(to_json, fromUInt) { EXPECT_EQ("123", to_json(123u)); } TEST(from_json, toUInt) { unsigned int result; from_json("123", result); EXPECT_EQ(123, result); } TEST(to_json, fromDouble) { EXPECT_EQ("1.23", to_json(1.23)); } TEST(to_json, fromNaturalDouble) { EXPECT_EQ("3", to_json(3)); } TEST(to_json, fromNegativeDouble) { EXPECT_EQ("-3.141", to_json(-3.141)); } TEST(from_json, toDouble) { double result; from_json("1.23", result); EXPECT_DOUBLE_EQ(1.23, result); } TEST(from_json, toNaturalDouble) { double result; from_json("3", result); EXPECT_DOUBLE_EQ(3, result); } TEST(from_json, toNegativeDouble) { double result; from_json("-3.141", result); EXPECT_DOUBLE_EQ(-3.141, result); } TEST(to_json, fromEmptyList) { EXPECT_EQ("[]", to_json(std::list<int>())); } TEST(from_json, toEmptyList) { std::list<int> result; from_json("[ ]", result); EXPECT_EQ(0, result.size()); } TEST(to_json, fromListOfInts) { auto l = std::list<int>({1,2,3}); EXPECT_EQ("[1,2,3]", to_json(l)); } TEST(from_json, toListOfInts) { std::list<int> result; from_json("[1,2,3]", result); EXPECT_EQ(3, result.size()); auto it = result.begin(); EXPECT_EQ(1, *it++); EXPECT_EQ(2, *it++); EXPECT_EQ(3, *it++); } TEST(to_json, fromListOfStrings) { auto l = std::list<std::string>({"a", "b", "c"}); EXPECT_EQ("[\"a\",\"b\",\"c\"]", to_json(l)); } TEST(from_json, toListOfStrings) { std::list<std::string> result; from_json("[\"a\",\"b\",\"c\"]", result); EXPECT_EQ(3, result.size()); auto it = result.begin(); EXPECT_EQ("a", *it++); EXPECT_EQ("b", *it++); EXPECT_EQ("c", *it++); } namespace { class Object { int a_{0}; int b_{0}; public: Object() = default; Object(int a, int b) : a_(a), b_(b) { } bool operator==(const Object& rhs) const { return a_ == rhs.a_ && b_ == rhs.b_; } std::string to_json() const { return ::to_json("a", a_) + "," + ::to_json("b", b_); } void from_json(const std::string& j) { ::from_json(j, "a", a_); ::from_json(j, "b", b_); } }; }; TEST(to_json, fromObject) { EXPECT_EQ("{\"a\":1,\"b\":2}", to_json(Object(1,2))); } TEST(from_json, toObjectOriginalOrder) { Object result; from_json("{\"a\":1,\"b\":2}", result); EXPECT_EQ(Object(1, 2), result); } TEST(from_json, toObjectDifferentOrder) { Object result; from_json("{\"b\":2,\"a\":1}", result); EXPECT_EQ(Object(1, 2), result); } namespace { class ObjectObject { Object obj_; public: ObjectObject() = default; ObjectObject(int a, int b) : obj_(a, b) { } bool operator==(const ObjectObject& rhs) const { return obj_ == rhs.obj_; } std::string to_json() const { return ::to_json("obj", obj_); } void from_json(const std::string& j) { ::from_json(j, "obj", obj_); } }; } TEST(to_json, fromObjectWithObject) { EXPECT_EQ("{\"obj\":{\"a\":1,\"b\":2}}", to_json(ObjectObject(1,2))); } TEST(from_json, toObjectWithObject) { ObjectObject result; from_json("{\"obj\":{\"a\":1,\"b\":2}}", result); EXPECT_EQ(ObjectObject(1,2), result); } namespace { class ObjectWithLists { std::list<int> a_; std::list<int> b_; public: ObjectWithLists() = default; ObjectWithLists(std::list<int> a, std::list<int> b) : a_(a), b_(b) { } bool operator==(const ObjectWithLists& rhs) const { return a_ == rhs.a_ && b_ == rhs.b_; } std::string to_json() const { return ::to_json("a", a_) + "," + ::to_json("b", b_); } void from_json(const std::string& j) { ::from_json(j, "a", a_); ::from_json(j, "b", b_); } }; } TEST(to_json, fromObjectWithList) { EXPECT_EQ("{\"a\":[1,2,3],\"b\":[4,5,6]}", to_json(ObjectWithLists({1, 2, 3}, {4, 5, 6}))); } TEST(from_json, toObjectWithList) { ObjectWithLists result; from_json("{ \"a\" : [1, 2, 3], \"b\" : [4, 5, 6] }", result); EXPECT_EQ(ObjectWithLists({1, 2, 3}, {4, 5, 6}), result); } TEST(to_json, fromListWithObjects) { auto l = std::list<Object>({Object(1,2), Object(3,4)}); EXPECT_EQ("[{\"a\":1,\"b\":2},{\"a\":3,\"b\":4}]", to_json(l)); } TEST(from_json, toListWithObjects) { std::list<Object> result; from_json("[ { \"a\" : 1, \"b\" : 2 }, { \"a\" : 3, \"b\" : 4 } ]", result); EXPECT_EQ(std::list<Object>({Object(1,2), Object(3,4)}), result); }<commit_msg>Fixed spelling of included header file.<commit_after>/* 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/. */ #include "JSON.h" #include "gtest/gtest.h" using namespace CoAP; TEST(without, non_empty) { EXPECT_EQ("abc", __internal__::without('<', '>', "<abc>")); } TEST(without, empty) { EXPECT_EQ("", __internal__::without('<', '>', "<>")); } TEST(without, exception_without_opening_bracket) { EXPECT_THROW(__internal__::without('<', '>', "abc>"), std::runtime_error); } TEST(without, exception_without_closing_bracket) { EXPECT_THROW(__internal__::without('<', '>', "<abc"), std::runtime_error); } TEST(withoutCurly, non_empty) { EXPECT_EQ("abc", __internal__::withoutCurly("{abc}")); } TEST(withoutRect, non_empty) { EXPECT_EQ("abc", __internal__::withoutRect("[abc]")); } TEST(withoutQuot, non_empty) { EXPECT_EQ("abc", __internal__::withoutQuot("\"abc\"")); } TEST(find_element_delimiter, simple) { EXPECT_EQ(1, __internal__::findListDelimiter("a,b")); } TEST(find_element_delimiter, nested) { EXPECT_EQ(5, __internal__::findListDelimiter("{a,b},c")); } TEST(trimmed, without_spaces) { EXPECT_EQ("hello", __internal__::trimmed("hello")); } TEST(trimmed, leading_spaces) { EXPECT_EQ("hello", __internal__::trimmed(" hello")); } TEST(trimmed, trailing_spaces) { EXPECT_EQ("hello", __internal__::trimmed("hello ")); } TEST(trimmed, one_space) { EXPECT_EQ("", __internal__::trimmed(" ")); } TEST(trimmed, two_spaces) { EXPECT_EQ("", __internal__::trimmed(" ")); } TEST(to_json, fromString) { EXPECT_EQ("\"text\"", to_json("text")); } TEST(from_json, toString) { std::string result; from_json(" \"text\" ", result); EXPECT_EQ("text", result); } TEST(to_json, fromStdString) { EXPECT_EQ("\"text\"", to_json(std::string("text"))); } TEST(to_json, fromTrue) { EXPECT_EQ("true", to_json(true)); } TEST(from_json, toTrue) { bool result; from_json("true", result); EXPECT_EQ(true, result); } TEST(to_json, fromFalse) { EXPECT_EQ("false", to_json(false)); } TEST(from_json, toFalse) { bool result; from_json("false", result); EXPECT_EQ(false, result); } TEST(to_json, fromInt) { EXPECT_EQ("-123", to_json(-123)); } TEST(from_json, toInt) { int result; from_json("-123", result); EXPECT_EQ(-123, result); } TEST(to_json, fromUInt) { EXPECT_EQ("123", to_json(123u)); } TEST(from_json, toUInt) { unsigned int result; from_json("123", result); EXPECT_EQ(123, result); } TEST(to_json, fromDouble) { EXPECT_EQ("1.23", to_json(1.23)); } TEST(to_json, fromNaturalDouble) { EXPECT_EQ("3", to_json(3)); } TEST(to_json, fromNegativeDouble) { EXPECT_EQ("-3.141", to_json(-3.141)); } TEST(from_json, toDouble) { double result; from_json("1.23", result); EXPECT_DOUBLE_EQ(1.23, result); } TEST(from_json, toNaturalDouble) { double result; from_json("3", result); EXPECT_DOUBLE_EQ(3, result); } TEST(from_json, toNegativeDouble) { double result; from_json("-3.141", result); EXPECT_DOUBLE_EQ(-3.141, result); } TEST(to_json, fromEmptyList) { EXPECT_EQ("[]", to_json(std::list<int>())); } TEST(from_json, toEmptyList) { std::list<int> result; from_json("[ ]", result); EXPECT_EQ(0, result.size()); } TEST(to_json, fromListOfInts) { auto l = std::list<int>({1,2,3}); EXPECT_EQ("[1,2,3]", to_json(l)); } TEST(from_json, toListOfInts) { std::list<int> result; from_json("[1,2,3]", result); EXPECT_EQ(3, result.size()); auto it = result.begin(); EXPECT_EQ(1, *it++); EXPECT_EQ(2, *it++); EXPECT_EQ(3, *it++); } TEST(to_json, fromListOfStrings) { auto l = std::list<std::string>({"a", "b", "c"}); EXPECT_EQ("[\"a\",\"b\",\"c\"]", to_json(l)); } TEST(from_json, toListOfStrings) { std::list<std::string> result; from_json("[\"a\",\"b\",\"c\"]", result); EXPECT_EQ(3, result.size()); auto it = result.begin(); EXPECT_EQ("a", *it++); EXPECT_EQ("b", *it++); EXPECT_EQ("c", *it++); } namespace { class Object { int a_{0}; int b_{0}; public: Object() = default; Object(int a, int b) : a_(a), b_(b) { } bool operator==(const Object& rhs) const { return a_ == rhs.a_ && b_ == rhs.b_; } std::string to_json() const { return ::to_json("a", a_) + "," + ::to_json("b", b_); } void from_json(const std::string& j) { ::from_json(j, "a", a_); ::from_json(j, "b", b_); } }; }; TEST(to_json, fromObject) { EXPECT_EQ("{\"a\":1,\"b\":2}", to_json(Object(1,2))); } TEST(from_json, toObjectOriginalOrder) { Object result; from_json("{\"a\":1,\"b\":2}", result); EXPECT_EQ(Object(1, 2), result); } TEST(from_json, toObjectDifferentOrder) { Object result; from_json("{\"b\":2,\"a\":1}", result); EXPECT_EQ(Object(1, 2), result); } namespace { class ObjectObject { Object obj_; public: ObjectObject() = default; ObjectObject(int a, int b) : obj_(a, b) { } bool operator==(const ObjectObject& rhs) const { return obj_ == rhs.obj_; } std::string to_json() const { return ::to_json("obj", obj_); } void from_json(const std::string& j) { ::from_json(j, "obj", obj_); } }; } TEST(to_json, fromObjectWithObject) { EXPECT_EQ("{\"obj\":{\"a\":1,\"b\":2}}", to_json(ObjectObject(1,2))); } TEST(from_json, toObjectWithObject) { ObjectObject result; from_json("{\"obj\":{\"a\":1,\"b\":2}}", result); EXPECT_EQ(ObjectObject(1,2), result); } namespace { class ObjectWithLists { std::list<int> a_; std::list<int> b_; public: ObjectWithLists() = default; ObjectWithLists(std::list<int> a, std::list<int> b) : a_(a), b_(b) { } bool operator==(const ObjectWithLists& rhs) const { return a_ == rhs.a_ && b_ == rhs.b_; } std::string to_json() const { return ::to_json("a", a_) + "," + ::to_json("b", b_); } void from_json(const std::string& j) { ::from_json(j, "a", a_); ::from_json(j, "b", b_); } }; } TEST(to_json, fromObjectWithList) { EXPECT_EQ("{\"a\":[1,2,3],\"b\":[4,5,6]}", to_json(ObjectWithLists({1, 2, 3}, {4, 5, 6}))); } TEST(from_json, toObjectWithList) { ObjectWithLists result; from_json("{ \"a\" : [1, 2, 3], \"b\" : [4, 5, 6] }", result); EXPECT_EQ(ObjectWithLists({1, 2, 3}, {4, 5, 6}), result); } TEST(to_json, fromListWithObjects) { auto l = std::list<Object>({Object(1,2), Object(3,4)}); EXPECT_EQ("[{\"a\":1,\"b\":2},{\"a\":3,\"b\":4}]", to_json(l)); } TEST(from_json, toListWithObjects) { std::list<Object> result; from_json("[ { \"a\" : 1, \"b\" : 2 }, { \"a\" : 3, \"b\" : 4 } ]", result); EXPECT_EQ(std::list<Object>({Object(1,2), Object(3,4)}), result); }<|endoftext|>
<commit_before>#include <iostream> #include "classes/Filter.cpp" #include "classes/Matrix.cpp" #include "classes/BlockDiagMatrix.cpp" #include "classes/Buffer.cpp" using namespace std; int main () { int x = 60; Matrix a(x,x); a.identity(); cout << a.toString() << endl << endl; Matrix b(x,1); b.fill(); Matrix c(1,x); c.fill(); cout << c.multiply(a).toString(); BlockDiagMatrix z(10,10,2); return 0; } <commit_msg>BlockMAtrix tests<commit_after>#include <iostream> #include "classes/Filter.cpp" #include "classes/Matrix.cpp" #include "classes/BlockDiagMatrix.cpp" #include "classes/Buffer.cpp" using namespace std; int main () { int x = 6; BlockDiagMatrix a; a.resize(x,x,2); a.identity(); BlockDiagMatrix b(x,x,2); b.fill(); cout << a.toString() << endl; cout << b.toString() << endl; cout << a.multiply(b).toString(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "addrinfo.h" #include "cxxtools/log.h" #include "cxxtools/tcpserver.h" #include "cxxtools/systemerror.h" log_define("cxxtools.net.tcp") namespace cxxtools { namespace net { TcpSocketImpl::TcpSocketImpl() : _fd(-1) { } TcpSocketImpl::~TcpSocketImpl() { } void TcpSocketImpl::create(int domain, int type, int protocol) { log_debug("create socket"); _fd = ::socket(domain, type, protocol); if (_fd < 0) throw SystemError("socket"); } void TcpSocketImpl::close() { if (_fd >= 0) { log_debug("close socket"); ::close(_fd); _fd = -1; } } void TcpSocketImpl::connect(const std::string& ipaddr, unsigned short int port) { log_debug("connect to " << ipaddr << " port " << port); Addrinfo ai(ipaddr, port); log_debug("do connect"); for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it) { try { this->create(it->ai_family, SOCK_STREAM, 0); } catch (const SystemError&) { continue; } if (::connect(this->fd(), it->ai_addr, it->ai_addrlen) == 0) { // save our information memmove(&_peeraddr, it->ai_addr, it->ai_addrlen); return; } // TODO add timeout handling //if (errno == EINPROGRESS && getTimeout() > 0) { //poll(POLLOUT); int sockerr; socklen_t optlen = sizeof(sockerr); if (::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0) { this->close(); throw SystemError("getsockopt"); } if(sockerr != 0) { this->close(); throw SystemError(sockerr, "connect"); } // save our information memmove(&_peeraddr, it->ai_addr, it->ai_addrlen); return; } } throw SystemError("connect"); } void TcpSocketImpl::accept(TcpServer& server) { socklen_t peeraddr_len = sizeof(_peeraddr); log_debug( "accept " << server.impl().fd() ); _fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); //TODO ECONNABORTED EINTR EPERM log_debug( "accepted " << server.impl().fd() << " => " << _fd ); } } // namespace net } // namespace cxxtools <commit_msg>add missing header<commit_after>/* * Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tcpsocketimpl.h" #include "tcpserverimpl.h" #include "addrinfo.h" #include "cxxtools/log.h" #include "cxxtools/tcpserver.h" #include "cxxtools/systemerror.h" #include <string.h> log_define("cxxtools.net.tcp") namespace cxxtools { namespace net { TcpSocketImpl::TcpSocketImpl() : _fd(-1) { } TcpSocketImpl::~TcpSocketImpl() { } void TcpSocketImpl::create(int domain, int type, int protocol) { log_debug("create socket"); _fd = ::socket(domain, type, protocol); if (_fd < 0) throw SystemError("socket"); } void TcpSocketImpl::close() { if (_fd >= 0) { log_debug("close socket"); ::close(_fd); _fd = -1; } } void TcpSocketImpl::connect(const std::string& ipaddr, unsigned short int port) { log_debug("connect to " << ipaddr << " port " << port); Addrinfo ai(ipaddr, port); log_debug("do connect"); for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it) { try { this->create(it->ai_family, SOCK_STREAM, 0); } catch (const SystemError&) { continue; } if (::connect(this->fd(), it->ai_addr, it->ai_addrlen) == 0) { // save our information memmove(&_peeraddr, it->ai_addr, it->ai_addrlen); return; } // TODO add timeout handling //if (errno == EINPROGRESS && getTimeout() > 0) { //poll(POLLOUT); int sockerr; socklen_t optlen = sizeof(sockerr); if (::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0) { this->close(); throw SystemError("getsockopt"); } if(sockerr != 0) { this->close(); throw SystemError(sockerr, "connect"); } // save our information memmove(&_peeraddr, it->ai_addr, it->ai_addrlen); return; } } throw SystemError("connect"); } void TcpSocketImpl::accept(TcpServer& server) { socklen_t peeraddr_len = sizeof(_peeraddr); log_debug( "accept " << server.impl().fd() ); _fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len); if( _fd < 0 ) throw SystemError("accept"); //TODO ECONNABORTED EINTR EPERM log_debug( "accepted " << server.impl().fd() << " => " << _fd ); } } // namespace net } // namespace cxxtools <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <string> #include <map> #include <set> #include <atomic> #include <thread> #include <glog/logging.h> #include "Kafka.h" #include "MySQLConnection.hpp" #include "utilities_js.hpp" #include "utils.hpp" using namespace std; class WorkerUpdate { public: const size_t FLUSH_SIZE = 1; const time_t FIX_GROUPID_INTERVAL = 60; WorkerUpdate( string consumeBrokers, string consumeTopic, string consumeGroupId, const MysqlConnectInfo &mysqlInfo ) : running_(false), messageNumber_(0), lastMessageTime_{0} , consumeBrokers_(consumeBrokers), consumeTopic_(consumeTopic), consumeGroupId_(consumeGroupId) , consumer_(consumeBrokers_.c_str(), consumeTopic_.c_str(), 0/* patition */, consumeGroupId_.c_str()) , mysqlInfo_(mysqlInfo) { } bool init() { LOG(INFO) << "setup kafka consumer..."; if (!consumer_.setup()) { LOG(ERROR) << "setup kafka consumer fail"; return false; } mysqlConn_ = make_shared<MySQLConnection>(mysqlInfo_); if (!mysqlConn_->ping()) { LOG(INFO) << "common events db ping failure"; return false; } return true; } void run() { const int32_t kTimeoutMs = 1000; running_ = true; LOG(INFO) << "waiting kafka messages..."; while (running_) { // // consume message // rd_kafka_message_t *rkmessage; rkmessage = consumer_.consumer(kTimeoutMs); // timeout, most of time it's not nullptr and set an error: // rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF if (rkmessage == nullptr) { continue; } // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; running_ = false; rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } DLOG(INFO) << "a new message, size: " << rkmessage->len; // repeat a message bool success = handleMessage(rkmessage); if (success) { messageNumber_++; } rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ } LOG(INFO) << "kafka consumer stopped"; } void stop() { LOG(INFO) << "stopping kafka consume..."; running_ = false; } bool isRunning() { return running_; } size_t getMessageNumber() { return messageNumber_; } void resetMessageNumber() { messageNumber_ = 0; } void runMessageNumberDisplayThread(time_t interval) { std::thread t([this, interval] () { this->resetMessageNumber(); while (this->isRunning()) { sleep(interval); size_t num = this->getMessageNumber(); this->resetMessageNumber(); displayMessageNumber(num, interval); } }); t.detach(); } protected: bool handleMessage(rd_kafka_message_t *rkmessage) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly return false; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; } return false; } const char *message = (const char*)rkmessage->payload; DLOG(INFO) << "A New Common Event: " << string(message, rkmessage->len); JsonNode r; if (!JsonNode::parse(message, message + rkmessage->len, r)) { LOG(ERROR) << "decode common event failure"; return false; } // check fields if (r["type"].type() != Utilities::JS::type::Str || r["content"].type() != Utilities::JS::type::Obj || r["created_at"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event missing some fields"; return false; } string lastMessageTime = r["created_at"].str(); lastMessageTime.resize(19); memcpy(lastMessageTime_, lastMessageTime.c_str(), 20); // update worker status if (r["type"].str() == "worker_update") { // check fields if (r["content"]["user_id"].type() != Utilities::JS::type::Int || r["content"]["worker_id"].type() != Utilities::JS::type::Int || r["content"]["worker_name"].type() != Utilities::JS::type::Str || r["content"]["miner_agent"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event `worker_update` missing some fields"; return false; } int32_t userId = r["content"]["user_id"].int32(); int64_t workerId = r["content"]["worker_id"].int64(); string workerName = filterWorkerName(r["content"]["worker_name"].str()); string minerAgent = filterWorkerName(r["content"]["miner_agent"].str()); updateWorkerStatusToDB(userId, workerId, workerName.c_str(), minerAgent.c_str()); return true; } // There is no worker_id in miner_connect event for legacy branch. // TODO: compute worker_id for miner_connect event /*if (r["type"].str() == "miner_connect") { // check fields if (r["content"]["user_id"].type() != Utilities::JS::type::Int || r["content"]["worker_id"].type() != Utilities::JS::type::Int || r["content"]["worker_name"].type() != Utilities::JS::type::Str || r["content"]["client_agent"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event `miner_connect` missing some fields"; return false; } int32_t userId = r["content"]["user_id"].int32(); int64_t workerId = r["content"]["worker_id"].int64(); string workerName = filterWorkerName(r["content"]["worker_name"].str()); string minerAgent = filterWorkerName(r["content"]["client_agent"].str()); updateWorkerStatusToDB(userId, workerId, workerName.c_str(), minerAgent.c_str()); return true; }*/ return false; } string sql_; time_t lastFixGroupIdTime_ = 0; bool updateWorkerStatusToDB( const int32_t userId, const int64_t workerId, const char *workerName, const char *minerAgent) { MySQLResult res; time_t now = time(nullptr); const string nowStr = date("%F %T", now); const string sqlBegin = "INSERT INTO `mining_workers`(`puid`,`worker_id`," " `group_id`,`worker_name`,`miner_agent`," " `created_at`,`updated_at`) VALUES"; const string sqlEnd = " ON DUPLICATE KEY UPDATE " " `worker_name`= VALUES(`worker_name`)," " `miner_agent`= VALUES(`miner_agent`)," " `updated_at`= VALUES(`updated_at`)"; static map<int32_t, set<int64_t>> workerCache; if (workerCache[userId].find(workerId) != workerCache[userId].end()) { return true; } string sqlValues = StringFormat( "(%d,%" PRId64",%d,'%s','%s','%s','%s')", userId, workerId, userId * -1, // default group id workerName, minerAgent, nowStr.c_str(), nowStr.c_str()); sql_ += sql_.empty() ? sqlBegin : ", "; sql_ += sqlValues; workerCache[userId].insert(workerId); if (sql_.size() < FLUSH_SIZE) { return true; } sql_ += sqlEnd; if (mysqlConn_->execute(sql_) == false) { LOG(ERROR) << "insert worker name failure"; // try to reconnect mysql, so last update may success if (!mysqlConn_->reconnect()) { LOG(ERROR) << "updateWorkerStatusToDB: can't connect to pool DB"; } sql_.clear(); return false; } if (now - lastFixGroupIdTime_ > FIX_GROUPID_INTERVAL) { sql_ = "UPDATE `mining_workers` SET `group_id`=-`puid`" " WHERE `group_id`=0 AND `last_share_time` > CURRENT_TIMESTAMP()-900"; if (mysqlConn_->execute(sql_)) { LOG(ERROR) << "fix group_id success"; lastFixGroupIdTime_ = now; } else { LOG(ERROR) << "fix group_id failure"; } } sql_.clear(); return true; } void displayMessageNumber(size_t messageNumber, time_t time) { LOG(INFO) << "Handled " << messageNumber << " messages in " << time << " seconds, last message time: " << lastMessageTime_; } std::atomic<bool> running_; size_t messageNumber_; // don't need thread safe (for logs only) char lastMessageTime_[20]; // xxxx-xx-xx xx:xx:xx string consumeBrokers_; string consumeTopic_; string consumeGroupId_; KafkaHighLevelConsumer consumer_; MysqlConnectInfo mysqlInfo_; shared_ptr<MySQLConnection> mysqlConn_; }; <commit_msg>worker_update: clear local cache after fix group_id.<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <string> #include <map> #include <set> #include <atomic> #include <thread> #include <glog/logging.h> #include "Kafka.h" #include "MySQLConnection.hpp" #include "utilities_js.hpp" #include "utils.hpp" using namespace std; class WorkerUpdate { public: const size_t FLUSH_SIZE = 1; const time_t FIX_GROUPID_INTERVAL = 60; WorkerUpdate( string consumeBrokers, string consumeTopic, string consumeGroupId, const MysqlConnectInfo &mysqlInfo ) : running_(false), messageNumber_(0), lastMessageTime_{0} , consumeBrokers_(consumeBrokers), consumeTopic_(consumeTopic), consumeGroupId_(consumeGroupId) , consumer_(consumeBrokers_.c_str(), consumeTopic_.c_str(), 0/* patition */, consumeGroupId_.c_str()) , mysqlInfo_(mysqlInfo) { } bool init() { LOG(INFO) << "setup kafka consumer..."; if (!consumer_.setup()) { LOG(ERROR) << "setup kafka consumer fail"; return false; } mysqlConn_ = make_shared<MySQLConnection>(mysqlInfo_); if (!mysqlConn_->ping()) { LOG(INFO) << "common events db ping failure"; return false; } return true; } void run() { const int32_t kTimeoutMs = 1000; running_ = true; LOG(INFO) << "waiting kafka messages..."; while (running_) { // // consume message // rd_kafka_message_t *rkmessage; rkmessage = consumer_.consumer(kTimeoutMs); // timeout, most of time it's not nullptr and set an error: // rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF if (rkmessage == nullptr) { continue; } // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; running_ = false; rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ continue; } DLOG(INFO) << "a new message, size: " << rkmessage->len; // repeat a message bool success = handleMessage(rkmessage); if (success) { messageNumber_++; } rd_kafka_message_destroy(rkmessage); /* Return message to rdkafka */ } LOG(INFO) << "kafka consumer stopped"; } void stop() { LOG(INFO) << "stopping kafka consume..."; running_ = false; } bool isRunning() { return running_; } size_t getMessageNumber() { return messageNumber_; } void resetMessageNumber() { messageNumber_ = 0; } void runMessageNumberDisplayThread(time_t interval) { std::thread t([this, interval] () { this->resetMessageNumber(); while (this->isRunning()) { sleep(interval); size_t num = this->getMessageNumber(); this->resetMessageNumber(); displayMessageNumber(num, interval); } }); t.detach(); } protected: bool handleMessage(rd_kafka_message_t *rkmessage) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. // Not really an error. // LOG(INFO) << "consumer reached end of " << rd_kafka_topic_name(rkmessage->rkt) // << "[" << rkmessage->partition << "] " // << " message queue at offset " << rkmessage->offset; // acturlly return false; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; } return false; } const char *message = (const char*)rkmessage->payload; DLOG(INFO) << "A New Common Event: " << string(message, rkmessage->len); JsonNode r; if (!JsonNode::parse(message, message + rkmessage->len, r)) { LOG(ERROR) << "decode common event failure"; return false; } // check fields if (r["type"].type() != Utilities::JS::type::Str || r["content"].type() != Utilities::JS::type::Obj || r["created_at"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event missing some fields"; return false; } string lastMessageTime = r["created_at"].str(); lastMessageTime.resize(19); memcpy(lastMessageTime_, lastMessageTime.c_str(), 20); // update worker status if (r["type"].str() == "worker_update") { // check fields if (r["content"]["user_id"].type() != Utilities::JS::type::Int || r["content"]["worker_id"].type() != Utilities::JS::type::Int || r["content"]["worker_name"].type() != Utilities::JS::type::Str || r["content"]["miner_agent"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event `worker_update` missing some fields"; return false; } int32_t userId = r["content"]["user_id"].int32(); int64_t workerId = r["content"]["worker_id"].int64(); string workerName = filterWorkerName(r["content"]["worker_name"].str()); string minerAgent = filterWorkerName(r["content"]["miner_agent"].str()); updateWorkerStatusToDB(userId, workerId, workerName.c_str(), minerAgent.c_str()); return true; } // There is no worker_id in miner_connect event for legacy branch. // TODO: compute worker_id for miner_connect event /*if (r["type"].str() == "miner_connect") { // check fields if (r["content"]["user_id"].type() != Utilities::JS::type::Int || r["content"]["worker_id"].type() != Utilities::JS::type::Int || r["content"]["worker_name"].type() != Utilities::JS::type::Str || r["content"]["client_agent"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "common event `miner_connect` missing some fields"; return false; } int32_t userId = r["content"]["user_id"].int32(); int64_t workerId = r["content"]["worker_id"].int64(); string workerName = filterWorkerName(r["content"]["worker_name"].str()); string minerAgent = filterWorkerName(r["content"]["client_agent"].str()); updateWorkerStatusToDB(userId, workerId, workerName.c_str(), minerAgent.c_str()); return true; }*/ return false; } string sql_; time_t lastFixGroupIdTime_ = 0; bool updateWorkerStatusToDB( const int32_t userId, const int64_t workerId, const char *workerName, const char *minerAgent) { MySQLResult res; time_t now = time(nullptr); const string nowStr = date("%F %T", now); const string sqlBegin = "INSERT INTO `mining_workers`(`puid`,`worker_id`," " `group_id`,`worker_name`,`miner_agent`," " `created_at`,`updated_at`) VALUES"; const string sqlEnd = " ON DUPLICATE KEY UPDATE " " `worker_name`= VALUES(`worker_name`)," " `miner_agent`= VALUES(`miner_agent`)," " `updated_at`= VALUES(`updated_at`)"; static map<int32_t, set<int64_t>> workerCache; if (workerCache[userId].find(workerId) != workerCache[userId].end()) { return true; } string sqlValues = StringFormat( "(%d,%" PRId64",%d,'%s','%s','%s','%s')", userId, workerId, userId * -1, // default group id workerName, minerAgent, nowStr.c_str(), nowStr.c_str()); sql_ += sql_.empty() ? sqlBegin : ", "; sql_ += sqlValues; workerCache[userId].insert(workerId); if (sql_.size() < FLUSH_SIZE) { return true; } sql_ += sqlEnd; if (mysqlConn_->execute(sql_) == false) { LOG(ERROR) << "insert worker name failure"; // try to reconnect mysql, so last update may success if (!mysqlConn_->reconnect()) { LOG(ERROR) << "updateWorkerStatusToDB: can't connect to pool DB"; } sql_.clear(); return false; } if (now - lastFixGroupIdTime_ > FIX_GROUPID_INTERVAL) { sql_ = "UPDATE `mining_workers` SET `group_id`=-`puid`" " WHERE `group_id`=0 AND `last_share_time` > CURRENT_TIMESTAMP()-900"; if (mysqlConn_->execute(sql_)) { LOG(ERROR) << "fix group_id success"; workerCache.clear(); lastFixGroupIdTime_ = now; } else { LOG(ERROR) << "fix group_id failure"; } } sql_.clear(); return true; } void displayMessageNumber(size_t messageNumber, time_t time) { LOG(INFO) << "Handled " << messageNumber << " messages in " << time << " seconds, last message time: " << lastMessageTime_; } std::atomic<bool> running_; size_t messageNumber_; // don't need thread safe (for logs only) char lastMessageTime_[20]; // xxxx-xx-xx xx:xx:xx string consumeBrokers_; string consumeTopic_; string consumeGroupId_; KafkaHighLevelConsumer consumer_; MysqlConnectInfo mysqlInfo_; shared_ptr<MySQLConnection> mysqlConn_; }; <|endoftext|>
<commit_before>#include <QApplication> #include <QLineEdit> #include <QCheckBox> #include <QDebug> #include <QTabFormWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTabFormWidget* settingsWidget = new QTabFormWidget(0); settingsWidget->addWidget("Menu A\\/B/A/Field A1",new QLineEdit(),LabelPolicy::Empty); settingsWidget->addWidget("Menu A\\/B/B/Field B1",new QLineEdit(),LabelPolicy::Show); settingsWidget->addWidget("Menu A\\/B/B/Field B2",new QCheckBox("Field B2"),LabelPolicy::Empty); settingsWidget->addWidget("Menu C/Field C1",new QLineEdit(),LabelPolicy::None); settingsWidget->addWidget("Menu C/Field C2",new QLineEdit(),LabelPolicy::Show); settingsWidget->addWidget("Menu C/Field C3",new QLineEdit(),LabelPolicy::NewLine); settingsWidget->show(); qDebug() << settingsWidget->getWidget<QLineEdit>("Menu C/Field B3"); return a.exec(); } <commit_msg>test commit<commit_after>#include <QApplication> #include <QLineEdit> #include <QCheckBox> #include <QDebug> #include <QTabFormWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTabFormWidget* settingsWidget = new QTabFormWidget(0); settingsWidget->addWidget("Menu A\\/B/A/Field A1",new QLineEdit(),LabelPolicy::Empty); settingsWidget->addWidget("Menu A\\/B/B/Field B1",new QLineEdit(),LabelPolicy::Show); settingsWidget->addWidget("Menu A\\/B/B/Field B2",new QCheckBox("Field B2"),LabelPolicy::Empty); settingsWidget->addWidget("Menu C/Field C1",new QLineEdit(),LabelPolicy::None); settingsWidget->addWidget("Menu C/Field C2",new QLineEdit(),LabelPolicy::Show); settingsWidget->addWidget("Menu C/Field C3",new QLineEdit(),LabelPolicy::NewLine); settingsWidget->show(); qDebug() << settingsWidget->getWidget<QLineEdit>("Menu C/Field B3"); return a.exec(); } <|endoftext|>
<commit_before>#include <aery32/all.h> #include "board.h" #define LED AVR32_PIN_PC04 #define ADC_PINMASK_ALLCHAN (0xff << 21) using namespace aery; using namespace boad; int main(void) { uint16_t result; /* conversion result in bits */ double volt; /* conversion in volts */ /* * Put your application initialization sequence here. The default * board initializer defines all pins as input and sets the CPU clock * speed to 66 MHz. */ board::init(); gpio_init_pins(porta, ADC_PINMASK_ALLCHAN, GPIO_FUNCTION_A); adc_init( 7, /* prescal, adclk = pba_clk / (2 * (prescal+1)) */ true, /* hires, 10-bit (false would be 8-bit) */ 0, /* shtim, sample and hold time = (shtim + 3) / adclk */ 0 /* startup, startup time = (startup + 1) * 8 / adclk */ ); /* Enable ADC channel 3. That's PA24. */ adc_enable(1 << 3); gpio_init_pin(LED, GPIO_OUTPUT); gpio_set_pin_high(LED); for(;;) { /* Put your application code here */ adc_start_cnv(); while (adc_isbusy(1 << 3)); result = adc_read_cnv(3); volt = cnv_to_volt(result); } return 0; } <commit_msg>Fix typo in namespace<commit_after>#include <aery32/all.h> #include "board.h" #define LED AVR32_PIN_PC04 #define ADC_PINMASK_ALLCHAN (0xff << 21) using namespace aery; using namespace board; int main(void) { uint16_t result; /* conversion result in bits */ double volt; /* conversion in volts */ /* * Put your application initialization sequence here. The default * board initializer defines all pins as input and sets the CPU clock * speed to 66 MHz. */ board::init(); gpio_init_pins(porta, ADC_PINMASK_ALLCHAN, GPIO_FUNCTION_A); adc_init( 7, /* prescal, adclk = pba_clk / (2 * (prescal+1)) */ true, /* hires, 10-bit (false would be 8-bit) */ 0, /* shtim, sample and hold time = (shtim + 3) / adclk */ 0 /* startup, startup time = (startup + 1) * 8 / adclk */ ); /* Enable ADC channel 3. That's PA24. */ adc_enable(1 << 3); gpio_init_pin(LED, GPIO_OUTPUT); gpio_set_pin_high(LED); for(;;) { /* Put your application code here */ adc_start_cnv(); while (adc_isbusy(1 << 3)); result = adc_read_cnv(3); volt = cnv_to_volt(result); } return 0; } <|endoftext|>
<commit_before>#include <QImage> #include "raster.h" #include "pixeliterator.h" #include "rootdrawer.h" #include "factory.h" #include "abstractfactory.h" #include "drawers/rasterimagefactory.h" #include "drawers/attributevisualproperties.h" #include "rastervalueimage.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_RASTERIMAGETYPE(RasterValueImage,itNUMERICDOMAIN); RasterValueImage::RasterValueImage(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) : RasterImage(rootDrawer,raster,vattribute, options) { } RasterValueImage::~RasterValueImage() { } RasterImage *RasterValueImage::create(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) { return new RasterValueImage(rootDrawer, raster, vattribute, options) ; } bool RasterValueImage::prepare(int prepareType) { bool resetImage = false; BoundingBox bb(_raster->size()); // lines must be 32 bit alligned. an entry pixel is a byte, so everything must be 4 alligned (32 bit is 4 bytes) int xl = (quint32)bb.xlength() % 4 == 0 ? bb.xlength() : (((quint32)bb.xlength() / 4) + 1) * 4; int rest = xl - bb.xlength(); if ( hasType(prepareType, DrawerInterface::ptRENDER)){ std::vector<QColor> colors = _visualAttribute.colors(); _colorTable = QVector<QRgb>(colors.size()) ; for(int i = 0; i < _colorTable.size(); ++i) _colorTable[i] = colors[i].rgba(); resetImage = true; } if ( hasType(prepareType, DrawerInterface::ptGEOMETRY)){ quint32 size = xl * bb.ylength(); _pixels.resize(size); PixelIterator pixIter(_raster); SPNumericRange numrange = _raster->datadef().range<NumericRange>(); auto end = pixIter.end(); quint32 position = 0; while(pixIter != end){ double value = *pixIter; int index = value == rUNDEF ? 0 : 1 + (_colorTable.size() - 1) * (value - numrange->min()) / numrange->distance(); _pixels[position] = index; ++pixIter; if ( pixIter.ychanged()){ position += rest; } ++position; } resetImage = true; } if ( resetImage) { const uchar *datablock = (const uchar *)_pixels.data(); _image.reset(new QImage(datablock,xl, bb.ylength(),QImage::Format_Indexed8)); _image->setColorTable(_colorTable); } return resetImage; } <commit_msg>added make imageTemp; functie is nog niet actief maar bevat stuk code voor efficienter uitrekening van het display image<commit_after>#include <QImage> #include "raster.h" #include "pixeliterator.h" #include "rootdrawer.h" #include "factory.h" #include "abstractfactory.h" #include "drawers/rasterimagefactory.h" #include "drawers/attributevisualproperties.h" #include "rastervalueimage.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_RASTERIMAGETYPE(RasterValueImage,itNUMERICDOMAIN); RasterValueImage::RasterValueImage(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) : RasterImage(rootDrawer,raster,vattribute, options) { } RasterValueImage::~RasterValueImage() { } RasterImage *RasterValueImage::create(DrawerInterface *rootDrawer, const IRasterCoverage& raster, const VisualAttribute &vattribute,const IOOptions &options) { return new RasterValueImage(rootDrawer, raster, vattribute, options) ; } bool RasterValueImage::prepare(int prepareType) { bool resetImage = false; BoundingBox bb(_raster->size()); // lines must be 32 bit alligned. an entry pixel is a byte, so everything must be 4 alligned (32 bit is 4 bytes) int xl = (quint32)bb.xlength() % 4 == 0 ? bb.xlength() : (((quint32)bb.xlength() / 4) + 1) * 4; int rest = xl - bb.xlength(); if ( hasType(prepareType, DrawerInterface::ptRENDER)){ std::vector<QColor> colors = _visualAttribute.colors(); _colorTable = QVector<QRgb>(colors.size()) ; for(int i = 0; i < _colorTable.size(); ++i) _colorTable[i] = colors[i].rgba(); resetImage = true; } if ( hasType(prepareType, DrawerInterface::ptGEOMETRY)){ quint32 size = xl * bb.ylength(); _pixels.resize(size); PixelIterator pixIter(_raster); SPNumericRange numrange = _raster->datadef().range<NumericRange>(); auto end = pixIter.end(); quint32 position = 0; while(pixIter != end){ double value = *pixIter; int index = value == rUNDEF ? 0 : 1 + (_colorTable.size() - 1) * (value - numrange->min()) / numrange->distance(); _pixels[position] = index; ++pixIter; if ( pixIter.ychanged()){ position += rest; } ++position; } resetImage = true; } if ( resetImage) { const uchar *datablock = (const uchar *)_pixels.data(); _image.reset(new QImage(datablock,xl, bb.ylength(),QImage::Format_Indexed8)); _image->setColorTable(_colorTable); } return resetImage; } void RasterImage::makeImageTemp() { // doesnt work, but i keep it around for later checking, should be more efficient version of makeImage() // BoundingBox bb(_raster->size()); // = _rootDrawer->screenGrf()->coord2Pixel(_raster->envelope()); // Size<> pixArea = _rootDrawer->pixelAreaSize(); // double dx = std::max(1.0,(double)bb.xlength() / pixArea.xsize()); // double dy = std::max(1.0,(double)bb.ylength() / pixArea.ysize()); // std::vector<double> xsteps(pixArea.xsize(),0); // std::vector<double> ysteps(pixArea.ysize(),0); // for(int x = 1; x < xsteps.size(); ++x){ // xsteps[x] = xsteps[x-1] + dx; // } // for(int x = 1; x < xsteps.size(); ++x){ // xsteps[x] = (int)(xsteps[x] - (int)((x - 1) * dx)); // } // for(int y = 1; y < ysteps.size(); ++y){ // ysteps[y] = ysteps[y-1] + dy; // } // for(int y = 1; y < ysteps.size(); ++y){ // ysteps[y] = (int)(ysteps[y] - (int)((y - 1) * dy)); // } // _pixels.resize(pixArea.linearSize()); // PixelIterator pixIter(_raster); // int xindex = 1; // int yindex = 1; // while(yindex != ysteps.size()){ // double value = *pixIter; // auto color = _visualAttribute.value2color(value); // _pixels[yindex * pixArea.xsize() + xindex] = color; // pixIter += xsteps[xindex++]; // if ( pixIter.ychanged()){ // pixIter = Pixel(0,pixIter.y() + ysteps[yindex++]); // xindex = 0; // } // } // const uchar *datablock = (const uchar *)_pixels.data(); // _image.reset(new QImage(datablock,pixArea.xsize(), pixArea.ysize(),QImage::Format_RGBA8888)); } <|endoftext|>
<commit_before>// Dijkstra algorithm is well-known algorithm for single-source shortes path problem. // This file contains Dijkstra algorithm implementation. // // Copyright (c) savrus, 2014 #pragma once #include <vector> #include <cassert> #include "graph.hpp" #include "binheap.hpp" #include "kheap.hpp" // Data structures to implement Dijkstra-like algorithms class BasicDijkstra { protected: Graph *g; // graph KHeap<Vertex, Distance> queue; // Dijkstra queue std::vector<Vertex> parent; // parent[v] is v's parent in the shortest path tree std::vector<Distance> distance; // distance[v] is distance from source to v std::vector<bool> is_dirty; // is_dirty[v] is true if we touched v in current run std::vector<Vertex> dirty; // list of visited vertices // Update vertex v: set distance to d and parent to p void update(Vertex v, Distance d, Vertex p = none) { distance[v] = d; parent[v] = p; queue.update(v, d); if (!is_dirty[v]) { dirty.push_back(v); is_dirty[v] = true; } } // Clear internal structures void clear() { queue.clear(); for(size_t i = 0; i < dirty.size(); ++i) { parent[dirty[i]] = none; distance[dirty[i]] = infty; is_dirty[dirty[i]] = false; } dirty.clear(); dirty.reserve(g->get_n()); } BasicDijkstra(Graph &g) : g(&g), queue(g.get_n()), parent(g.get_n(), none), distance(g.get_n(), infty), is_dirty(g.get_n()) {} }; // Dijkstra algorithm implementation class Dijkstra : BasicDijkstra{ public: Dijkstra(Graph &g) : BasicDijkstra(g) {} Distance get_distance(Vertex v) { return distance[v]; } // Distance from source to v Vertex get_parent(Vertex v) { return parent[v]; } // v's parent in the shortest path tree // Find distances from v to all other vertices and build shortest path tree void run(Vertex v, bool forward = true) { clear(); update(v, 0); while (!queue.empty()) { Vertex u = queue.pop(); Distance d = distance[u]; for (Graph::arc_iterator a = g->begin(u, forward), end = g->end(u, forward); a < end; ++a) { Distance dd = d + a->length; assert(dd > d && dd < infty); if (dd < distance[a->head]) update(a->head, dd, u); } } } }; <commit_msg>Remove remaining binheap.hpp inclusion<commit_after>// Dijkstra algorithm is well-known algorithm for single-source shortes path problem. // This file contains Dijkstra algorithm implementation. // // Copyright (c) savrus, 2014 #pragma once #include <vector> #include <cassert> #include "graph.hpp" #include "kheap.hpp" // Data structures to implement Dijkstra-like algorithms class BasicDijkstra { protected: Graph *g; // graph KHeap<Vertex, Distance> queue; // Dijkstra queue std::vector<Vertex> parent; // parent[v] is v's parent in the shortest path tree std::vector<Distance> distance; // distance[v] is distance from source to v std::vector<bool> is_dirty; // is_dirty[v] is true if we touched v in current run std::vector<Vertex> dirty; // list of visited vertices // Update vertex v: set distance to d and parent to p void update(Vertex v, Distance d, Vertex p = none) { distance[v] = d; parent[v] = p; queue.update(v, d); if (!is_dirty[v]) { dirty.push_back(v); is_dirty[v] = true; } } // Clear internal structures void clear() { queue.clear(); for(size_t i = 0; i < dirty.size(); ++i) { parent[dirty[i]] = none; distance[dirty[i]] = infty; is_dirty[dirty[i]] = false; } dirty.clear(); dirty.reserve(g->get_n()); } BasicDijkstra(Graph &g) : g(&g), queue(g.get_n()), parent(g.get_n(), none), distance(g.get_n(), infty), is_dirty(g.get_n()) {} }; // Dijkstra algorithm implementation class Dijkstra : BasicDijkstra{ public: Dijkstra(Graph &g) : BasicDijkstra(g) {} Distance get_distance(Vertex v) { return distance[v]; } // Distance from source to v Vertex get_parent(Vertex v) { return parent[v]; } // v's parent in the shortest path tree // Find distances from v to all other vertices and build shortest path tree void run(Vertex v, bool forward = true) { clear(); update(v, 0); while (!queue.empty()) { Vertex u = queue.pop(); Distance d = distance[u]; for (Graph::arc_iterator a = g->begin(u, forward), end = g->end(u, forward); a < end; ++a) { Distance dd = d + a->length; assert(dd > d && dd < infty); if (dd < distance[a->head]) update(a->head, dd, u); } } } }; <|endoftext|>
<commit_before>#include "ShadingWithLightCulling.h" #include "EngineShaderFactory.hpp" #include "Director.h" using namespace Device; using namespace Core; using namespace Rendering; using namespace Rendering::Light; using namespace Rendering::Buffer; using namespace Rendering::Shader; using namespace GPGPU::DirectCompute; using namespace Rendering::TBDR; ShadingWithLightCulling::ShadingWithLightCulling() : _offScreen(nullptr), _inputPointLightColorBuffer(nullptr), _inputSpotLightColorBuffer(nullptr), _inputDirectionalLightColorBuffer(nullptr), _inputDirectionalLightParamBuffer(nullptr), _inputDirectionalLightTransformBuffer(nullptr) { } ShadingWithLightCulling::~ShadingWithLightCulling() { Destory(); } void ShadingWithLightCulling::Initialize(const Texture::DepthBuffer* opaqueDepthBuffer, const Texture::RenderTexture* gbuffer_albedo_emission, const Texture::RenderTexture* gbuffer_specular_metallic, const Texture::RenderTexture* gbuffer_normal_roughness, const Math::Size<uint>& backBufferSize, bool useDebugMode) { Manager::LightManager* lightManager = Director::GetInstance()->GetCurrentScene()->GetLightManager(); std::string filePath = ""; { Factory::EngineFactory pathFind(nullptr); pathFind.FetchShaderFullPath(filePath, "TBDR"); ASSERT_COND_MSG(filePath.empty() == false, "Error, File path is empty"); } std::vector<ShaderMacro> macros; { if(useDebugMode) macros.push_back(ShaderMacro("DEBUG_MODE", "")); } LightCulling::Initialize(filePath, "TileBasedDeferredShadingCS", opaqueDepthBuffer, nullptr, &macros); // Input buffer { // Point Light Color { uint idx = (uint)InputBufferShaderIndex::PointLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetPointLightColorBufferSR(); AddInputBufferToList(_inputPointLightColorBuffer, idx, srBuffer); } // Spot Light Color { uint idx = (uint)InputBufferShaderIndex::SpotLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetSpotLightColorBufferSR(); AddInputBufferToList(_inputSpotLightColorBuffer, idx, srBuffer); } // Directional Light { // Center With DirZ { uint idx = (uint)InputBufferShaderIndex::DirectionalLightCenterWithDirZ; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightTransformBufferSR(); AddInputBufferToList(_inputDirectionalLightTransformBuffer, idx, srBuffer); } // Color { uint idx = (uint)InputBufferShaderIndex::DirectionalLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightColorBufferSR(); AddInputBufferToList(_inputSpotLightColorBuffer, idx, srBuffer); } // Param half / DirX, DirY { uint idx = (uint)InputBufferShaderIndex::DirectionalLightParam; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightParamBufferSR(); AddInputBufferToList(_inputDirectionalLightParamBuffer, idx, srBuffer); } } } // Input Texture { // Albedo_Emission { uint idx = (uint)InputTextureShaderIndex::GBuffer_Albedo_Emission; AddTextureToInputTextureList(idx, gbuffer_albedo_emission); } // Specular_Metallic { uint idx = (uint)InputTextureShaderIndex::GBuffer_Specular_Metallic; AddTextureToInputTextureList(idx, gbuffer_specular_metallic); } // Normal_Roughness { uint idx = (uint)InputTextureShaderIndex::GBuffer_Normal_Roughness; AddTextureToInputTextureList(idx, gbuffer_normal_roughness); } } // Offscreen { Math::Size<uint> bufferSize = backBufferSize; { const DXGI_SAMPLE_DESC& msaaDesc = Director::GetInstance()->GetDirectX()->GetMSAADesc(); if(msaaDesc.Count > 1) { bufferSize.w *= 2; bufferSize.h *= 2; } } _offScreen = new CSRWTexture; _offScreen->Initialize(bufferSize, DXGI_FORMAT_R16G16B16A16_FLOAT, 0); ComputeShader::Output output; { output.idx = (uint)OutputBufferShaderIndex::OutScreen; output.output = _offScreen; } std::vector<ComputeShader::Output> outputs; outputs.push_back(output); SetOuputBuferToCS(outputs); } SetInputsToCS(); } void ShadingWithLightCulling::Destory() { _inputPointLightColorBuffer = nullptr; _inputSpotLightColorBuffer = nullptr; _inputDirectionalLightTransformBuffer = nullptr; _inputDirectionalLightColorBuffer = nullptr; _inputDirectionalLightParamBuffer = nullptr; SAFE_DELETE(_offScreen); LightCulling::Destroy(); }<commit_msg>dl color 버그 수정 #89<commit_after>#include "ShadingWithLightCulling.h" #include "EngineShaderFactory.hpp" #include "Director.h" using namespace Device; using namespace Core; using namespace Rendering; using namespace Rendering::Light; using namespace Rendering::Buffer; using namespace Rendering::Shader; using namespace GPGPU::DirectCompute; using namespace Rendering::TBDR; ShadingWithLightCulling::ShadingWithLightCulling() : _offScreen(nullptr), _inputPointLightColorBuffer(nullptr), _inputSpotLightColorBuffer(nullptr), _inputDirectionalLightColorBuffer(nullptr), _inputDirectionalLightParamBuffer(nullptr), _inputDirectionalLightTransformBuffer(nullptr) { } ShadingWithLightCulling::~ShadingWithLightCulling() { Destory(); } void ShadingWithLightCulling::Initialize(const Texture::DepthBuffer* opaqueDepthBuffer, const Texture::RenderTexture* gbuffer_albedo_emission, const Texture::RenderTexture* gbuffer_specular_metallic, const Texture::RenderTexture* gbuffer_normal_roughness, const Math::Size<uint>& backBufferSize, bool useDebugMode) { Manager::LightManager* lightManager = Director::GetInstance()->GetCurrentScene()->GetLightManager(); std::string filePath = ""; { Factory::EngineFactory pathFind(nullptr); pathFind.FetchShaderFullPath(filePath, "TBDR"); ASSERT_COND_MSG(filePath.empty() == false, "Error, File path is empty"); } std::vector<ShaderMacro> macros; { if(useDebugMode) macros.push_back(ShaderMacro("DEBUG_MODE", "")); } LightCulling::Initialize(filePath, "TileBasedDeferredShadingCS", opaqueDepthBuffer, nullptr, &macros); // Additional Input buffer { // Point Light Color { uint idx = (uint)InputBufferShaderIndex::PointLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetPointLightColorBufferSR(); AddInputBufferToList(_inputPointLightColorBuffer, idx, srBuffer); } // Spot Light Color { uint idx = (uint)InputBufferShaderIndex::SpotLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetSpotLightColorBufferSR(); AddInputBufferToList(_inputSpotLightColorBuffer, idx, srBuffer); } // Directional Light { // Center With DirZ { uint idx = (uint)InputBufferShaderIndex::DirectionalLightCenterWithDirZ; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightTransformBufferSR(); AddInputBufferToList(_inputDirectionalLightTransformBuffer, idx, srBuffer); } // Color { uint idx = (uint)InputBufferShaderIndex::DirectionalLightColor; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightColorBufferSR(); AddInputBufferToList(_inputDirectionalLightColorBuffer, idx, srBuffer); } // Param half / DirX, DirY { uint idx = (uint)InputBufferShaderIndex::DirectionalLightParam; const ShaderResourceBuffer* srBuffer = lightManager->GetDirectionalLightParamBufferSR(); AddInputBufferToList(_inputDirectionalLightParamBuffer, idx, srBuffer); } } } // Input Texture { // Albedo_Emission { uint idx = (uint)InputTextureShaderIndex::GBuffer_Albedo_Emission; AddTextureToInputTextureList(idx, gbuffer_albedo_emission); } // Specular_Metallic { uint idx = (uint)InputTextureShaderIndex::GBuffer_Specular_Metallic; AddTextureToInputTextureList(idx, gbuffer_specular_metallic); } // Normal_Roughness { uint idx = (uint)InputTextureShaderIndex::GBuffer_Normal_Roughness; AddTextureToInputTextureList(idx, gbuffer_normal_roughness); } } // Offscreen { Math::Size<uint> bufferSize = backBufferSize; { const DXGI_SAMPLE_DESC& msaaDesc = Director::GetInstance()->GetDirectX()->GetMSAADesc(); if(msaaDesc.Count > 1) { bufferSize.w *= 2; bufferSize.h *= 2; } } _offScreen = new CSRWTexture; _offScreen->Initialize(bufferSize, DXGI_FORMAT_R16G16B16A16_FLOAT, 0); ComputeShader::Output output; { output.idx = (uint)OutputBufferShaderIndex::OutScreen; output.output = _offScreen; } std::vector<ComputeShader::Output> outputs; outputs.push_back(output); SetOuputBuferToCS(outputs); } SetInputsToCS(); } void ShadingWithLightCulling::Destory() { _inputPointLightColorBuffer = nullptr; _inputSpotLightColorBuffer = nullptr; _inputDirectionalLightTransformBuffer = nullptr; _inputDirectionalLightColorBuffer = nullptr; _inputDirectionalLightParamBuffer = nullptr; SAFE_DELETE(_offScreen); LightCulling::Destroy(); }<|endoftext|>
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "BatchEncoder.h" #include "utilities\Utilities.h" #include "BatchEncoderWorkerContext.h" CBatchEncoderWorkerContext::CBatchEncoderWorkerContext(CConfiguration* pConfig, CBatchEncoderDlg* pDlg) : CWorkerContext(pConfig) { this->bDone = true; this->pDlg = pDlg; } CBatchEncoderWorkerContext::~CBatchEncoderWorkerContext() { } void CBatchEncoderWorkerContext::Init() { this->timer.Start(); pDlg->m_Progress.SetPos(0); } void CBatchEncoderWorkerContext::Next(int nItemId) { this->nProcessedFiles++; this->nErrors = (this->nProcessedFiles - 1) - this->nDoneWithoutError; if (this->nThreadCount == 1) { CString szText; szText.Format(_T("Processing item %d of %d (%d Done, %d %s)"), this->nProcessedFiles, this->nTotalFiles, this->nDoneWithoutError, this->nErrors, ((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error")); pDlg->m_StatusBar.SetText(szText, 1, 0); this->nLastItemId = nItemId; pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE); } } void CBatchEncoderWorkerContext::Done() { this->timer.Stop(); this->nErrors = this->nProcessedFiles - this->nDoneWithoutError; CString szText; szText.Format(_T("Processed %d of %d (%d Done, %d %s) in %s"), this->nProcessedFiles, this->nTotalFiles, this->nDoneWithoutError, this->nErrors, ((this->nErrors == 0) || (this->nErrors > 1)) ? _T("Errors") : _T("Error"), this->timer.Format(this->timer.ElapsedTime(), 3)); pDlg->m_StatusBar.SetText(szText, 1, 0); pDlg->FinishConvert(); } bool CBatchEncoderWorkerContext::Callback(int nItemId, int nProgress, bool bFinished, bool bError) { if (bError == true) { if (pConfig->m_Options.bStopOnErrors == true) { pDlg->m_Progress.SetPos(0); this->bRunning = false; } return this->bRunning; } if (bFinished == false && this->bRunning == true) { nProgess[nItemId] = nProgress; // check previous progress if two or more passes are used to for item processing if (nPreviousProgess[nItemId] > nProgress) nPreviousProgess[nItemId] = nProgress; static volatile bool bSafeCheck = false; if (bSafeCheck == false) { bSafeCheck = true; if (nItemId > this->nLastItemId) { this->nLastItemId = nItemId; pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE); } int nTotalProgress = 0; int nItems = pConfig->m_Items.GetSize(); for (int i = 0; i < nItems; i++) { if (pConfig->m_Items.GetData(i).bChecked == TRUE) { int nItemProgress = nProgess[i]; int nItemPreviousProgress = nPreviousProgess[i]; nTotalProgress += nItemProgress; if (nItemProgress > 0 && nItemProgress < 100 && nItemProgress > nItemPreviousProgress) { CString szProgress; szProgress.Format(_T("%d%%\0"), nItemProgress); pDlg->m_LstInputItems.SetItemText(i, ITEM_COLUMN_STATUS, szProgress); // Status nPreviousProgess[i] = nItemProgress; } } } int nPos = nTotalProgress / nTotalFiles; if (pDlg->m_Progress.GetPos() != nPos) { pDlg->m_Progress.SetPos(nPos); } bSafeCheck = false; } } return this->bRunning; } void CBatchEncoderWorkerContext::Status(int nItemId, CString szTime, CString szStatus) { pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_TIME, szTime); // Time pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szStatus); // Status }; <commit_msg>Added language strings support<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "BatchEncoder.h" #include "utilities\Utilities.h" #include "BatchEncoderWorkerContext.h" const TCHAR* pszWorkerContext[] = { /* 00 */ _T("Error"), /* 01 */ _T("Errors"), /* 02 */ _T("Processing item %d of %d (%d Done, %d %s)"), /* 03 */ _T("Processed %d of %d (%d Done, %d %s) in %s") }; CBatchEncoderWorkerContext::CBatchEncoderWorkerContext(CConfiguration* pConfig, CBatchEncoderDlg* pDlg) : CWorkerContext(pConfig) { this->bDone = true; this->pDlg = pDlg; } CBatchEncoderWorkerContext::~CBatchEncoderWorkerContext() { } void CBatchEncoderWorkerContext::Init() { this->timer.Start(); pDlg->m_Progress.SetPos(0); } void CBatchEncoderWorkerContext::Next(int nItemId) { this->nProcessedFiles++; this->nErrors = (this->nProcessedFiles - 1) - this->nDoneWithoutError; if (this->nThreadCount == 1) { CString szText; szText.Format(this->GetString(0x00190003, pszWorkerContext[2]), this->nProcessedFiles, this->nTotalFiles, this->nDoneWithoutError, this->nErrors, ((this->nErrors == 0) || (this->nErrors > 1)) ? this->GetString(0x00190002, pszWorkerContext[1]) : this->GetString(0x00190001, pszWorkerContext[0])); pDlg->m_StatusBar.SetText(szText, 1, 0); this->nLastItemId = nItemId; pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE); } } void CBatchEncoderWorkerContext::Done() { this->timer.Stop(); this->nErrors = this->nProcessedFiles - this->nDoneWithoutError; CString szText; szText.Format(this->GetString(0x00190004, pszWorkerContext[3]), this->nProcessedFiles, this->nTotalFiles, this->nDoneWithoutError, this->nErrors, ((this->nErrors == 0) || (this->nErrors > 1)) ? this->GetString(0x00190002, pszWorkerContext[1]) : this->GetString(0x00190001, pszWorkerContext[0]), this->timer.Format(this->timer.ElapsedTime(), 3)); pDlg->m_StatusBar.SetText(szText, 1, 0); pDlg->FinishConvert(); } bool CBatchEncoderWorkerContext::Callback(int nItemId, int nProgress, bool bFinished, bool bError) { if (bError == true) { if (pConfig->m_Options.bStopOnErrors == true) { pDlg->m_Progress.SetPos(0); this->bRunning = false; } return this->bRunning; } if (bFinished == false && this->bRunning == true) { nProgess[nItemId] = nProgress; // check previous progress if two or more passes are used to for item processing if (nPreviousProgess[nItemId] > nProgress) nPreviousProgess[nItemId] = nProgress; static volatile bool bSafeCheck = false; if (bSafeCheck == false) { bSafeCheck = true; if (nItemId > this->nLastItemId) { this->nLastItemId = nItemId; pDlg->m_LstInputItems.EnsureVisible(nItemId, FALSE); } int nTotalProgress = 0; int nItems = pConfig->m_Items.GetSize(); for (int i = 0; i < nItems; i++) { if (pConfig->m_Items.GetData(i).bChecked == TRUE) { int nItemProgress = nProgess[i]; int nItemPreviousProgress = nPreviousProgess[i]; nTotalProgress += nItemProgress; if (nItemProgress > 0 && nItemProgress < 100 && nItemProgress > nItemPreviousProgress) { CString szProgress; szProgress.Format(_T("%d%%\0"), nItemProgress); pDlg->m_LstInputItems.SetItemText(i, ITEM_COLUMN_STATUS, szProgress); // Status nPreviousProgess[i] = nItemProgress; } } } int nPos = nTotalProgress / nTotalFiles; if (pDlg->m_Progress.GetPos() != nPos) { pDlg->m_Progress.SetPos(nPos); } bSafeCheck = false; } } return this->bRunning; } void CBatchEncoderWorkerContext::Status(int nItemId, CString szTime, CString szStatus) { pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_TIME, szTime); // Time pDlg->m_LstInputItems.SetItemText(nItemId, ITEM_COLUMN_STATUS, szStatus); // Status }; <|endoftext|>
<commit_before>#include "stdafx.h" #include "CallbackHelper.h" // ***************************************************************** // GDALProgressCallback() // ***************************************************************** int CPL_STDCALL GDALProgressCallback(double dfComplete, const char* pszMessage, void *pData) { CallbackParams* params = (CallbackParams*)pData; if (params != NULL && params->cBack != NULL) { long percent = long(dfComplete * 100.0); CallbackHelper::Progress(params->cBack, percent, params->sMsg); } return TRUE; } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, long& lastPercent) { Progress(localCback, index, (double)count, message, m_globalSettings.emptyBstr, lastPercent); } void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, BSTR& key, long& lastPercent) { Progress(localCback, index, (double)count, message, key, lastPercent); } // ******************************************************************** // GetCurrent() // ******************************************************************** ICallback* CallbackHelper::GetCurrent(ICallback* localCback) { if (m_globalSettings.overrideLocalCallback) { return m_globalSettings.callback ? m_globalSettings.callback : localCback; } else { return localCback ? localCback : m_globalSettings.callback; } } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int index, double count, const char* message, BSTR& key, long& lastPercent) { ICallback* callback = GetCurrent(localCback); if (!callback) return; long newpercent = (long)(((double)(index + 1) / count) * 100); if (newpercent > lastPercent) { lastPercent = newpercent; CComBSTR bstrMsg(message); callback->Progress(key, newpercent, bstrMsg); } } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message, BSTR& key) { ICallback* callback = GetCurrent(localCback); if (!callback) return; CComBSTR bstrMsg(message); callback->Progress(key, percent, bstrMsg); } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message) { ICallback* callback = GetCurrent(localCback); if (!callback) return; if (!message) message = ""; CComBSTR bstrMsg(message); callback->Progress(m_globalSettings.emptyBstr, percent, bstrMsg); } // ******************************************************************** // DisplayProgressCompleted() // ******************************************************************** void CallbackHelper::ProgressCompleted(ICallback* localCback, BSTR& key) { ICallback* callback = GetCurrent(localCback); if (!callback) return; CComBSTR bstrMsg("Completed"); callback->Progress(key, 100, bstrMsg); callback->Progress(key, 0, m_globalSettings.emptyBstr); } // ******************************************************************** // DisplayProgressCompleted() // ******************************************************************** void CallbackHelper::ProgressCompleted(ICallback* localCback) { ProgressCompleted(localCback, m_globalSettings.emptyBstr); } // ******************************************************************** // DisplayErrorMsg() // ******************************************************************** void CallbackHelper::ErrorMsg(CString className, ICallback* localCback, BSTR& key, const char* message, ...) { ICallback* callback = GetCurrent(localCback); if (callback || Debug::IsDebugMode()) { if (strcmp(message, "No Error") == 0) return; TCHAR buffer[1024]; va_list args; va_start(args, message); vsprintf(buffer, message, args); CString s = buffer; s = className + ": " + s; CComBSTR bstr(s); if (callback) { callback->Error(key, bstr); } else { Debug::WriteError(s); } } } void CallbackHelper::ErrorMsg(CString className, ICallback* localCallback, CString key, const char* message, ...) { if (localCallback || Debug::IsDebugMode()) { CComBSTR bstrKey(key); ErrorMsg(className, localCallback, bstrKey.m_str, message); } } void CallbackHelper::ErrorMsg(const char* message) { CString s = message; ErrorMsg(s); } void CallbackHelper::ErrorMsg(CString message) { if (m_globalSettings.callback) { CComBSTR bstr(message); m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr); } else { if (Debug::IsDebugMode()) Debug::WriteError(message); } } // **************************************************************** // AssertionFailed // **************************************************************** void CallbackHelper::AssertionFailed(CString message) { message = "Assertion failed: " + message; if (m_globalSettings.callback) { CComBSTR bstr(message); m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr); } else { if (Debug::IsDebugMode()) Debug::WriteError(message); } }<commit_msg>A minor fix to enable callback notification from Utils.Polygonize.<commit_after>#include "stdafx.h" #include "CallbackHelper.h" // ***************************************************************** // GDALProgressCallback() // ***************************************************************** int CPL_STDCALL GDALProgressCallback(double dfComplete, const char* pszMessage, void *pData) { CallbackParams* params = (CallbackParams*)pData; // No need to check the presence of local callback, // global application callback can be used as a fallback. // There is no need to pass it as a parameter from each method. if (params != NULL) { long percent = long(dfComplete * 100.0); CallbackHelper::Progress(params->cBack, percent, params->sMsg); } return TRUE; } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, long& lastPercent) { Progress(localCback, index, (double)count, message, m_globalSettings.emptyBstr, lastPercent); } void CallbackHelper::Progress(ICallback* localCback, int index, int count, const char* message, BSTR& key, long& lastPercent) { Progress(localCback, index, (double)count, message, key, lastPercent); } // ******************************************************************** // GetCurrent() // ******************************************************************** ICallback* CallbackHelper::GetCurrent(ICallback* localCback) { if (m_globalSettings.overrideLocalCallback) { return m_globalSettings.callback ? m_globalSettings.callback : localCback; } else { return localCback ? localCback : m_globalSettings.callback; } } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int index, double count, const char* message, BSTR& key, long& lastPercent) { ICallback* callback = GetCurrent(localCback); if (!callback) return; long newpercent = (long)(((double)(index + 1) / count) * 100); if (newpercent > lastPercent) { lastPercent = newpercent; CComBSTR bstrMsg(message); callback->Progress(key, newpercent, bstrMsg); } } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message, BSTR& key) { ICallback* callback = GetCurrent(localCback); if (!callback) return; CComBSTR bstrMsg(message); callback->Progress(key, percent, bstrMsg); } // ******************************************************************** // DisplayProgress() // ******************************************************************** void CallbackHelper::Progress(ICallback* localCback, int percent, const char* message) { ICallback* callback = GetCurrent(localCback); if (!callback) return; if (!message) message = ""; CComBSTR bstrMsg(message); callback->Progress(m_globalSettings.emptyBstr, percent, bstrMsg); } // ******************************************************************** // DisplayProgressCompleted() // ******************************************************************** void CallbackHelper::ProgressCompleted(ICallback* localCback, BSTR& key) { ICallback* callback = GetCurrent(localCback); if (!callback) return; CComBSTR bstrMsg("Completed"); callback->Progress(key, 100, bstrMsg); callback->Progress(key, 0, m_globalSettings.emptyBstr); } // ******************************************************************** // DisplayProgressCompleted() // ******************************************************************** void CallbackHelper::ProgressCompleted(ICallback* localCback) { ProgressCompleted(localCback, m_globalSettings.emptyBstr); } // ******************************************************************** // DisplayErrorMsg() // ******************************************************************** void CallbackHelper::ErrorMsg(CString className, ICallback* localCback, BSTR& key, const char* message, ...) { ICallback* callback = GetCurrent(localCback); if (callback || Debug::IsDebugMode()) { if (strcmp(message, "No Error") == 0) return; TCHAR buffer[1024]; va_list args; va_start(args, message); vsprintf(buffer, message, args); CString s = buffer; s = className + ": " + s; CComBSTR bstr(s); if (callback) { callback->Error(key, bstr); } else { Debug::WriteError(s); } } } void CallbackHelper::ErrorMsg(CString className, ICallback* localCallback, CString key, const char* message, ...) { if (localCallback || Debug::IsDebugMode()) { CComBSTR bstrKey(key); ErrorMsg(className, localCallback, bstrKey.m_str, message); } } void CallbackHelper::ErrorMsg(const char* message) { CString s = message; ErrorMsg(s); } void CallbackHelper::ErrorMsg(CString message) { if (m_globalSettings.callback) { CComBSTR bstr(message); m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr); } else { if (Debug::IsDebugMode()) Debug::WriteError(message); } } // **************************************************************** // AssertionFailed // **************************************************************** void CallbackHelper::AssertionFailed(CString message) { message = "Assertion failed: " + message; if (m_globalSettings.callback) { CComBSTR bstr(message); m_globalSettings.callback->Error(m_globalSettings.emptyBstr, bstr); } else { if (Debug::IsDebugMode()) Debug::WriteError(message); } }<|endoftext|>
<commit_before>/* Copyright (c) 2010-2017, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h" namespace tudat { namespace propagators { //! Function to check whether the propagation is to be be stopped bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { bool stopPropagation = 0; // Check whether stop time has been reached if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) ) { stopPropagation = 1; } else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) ) { stopPropagation = 1; } return stopPropagation; } //! Function to check whether the propagation is to be be stopped bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { return cpuTime >= cpuStopTime_; } //! Function to check whether the propagation is to be be stopped bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { bool stopPropagation = 0; double currentVariable = variableRetrievalFuntion_( ); if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) ) { stopPropagation = 1; } else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) ) { stopPropagation = 1; } return stopPropagation; } //! Function to check whether the propagation is to be be stopped bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { // Check if single condition is fulfilled. bool stopPropagation = -1; if( fulFillSingleCondition_ ) { stopPropagation = 0; for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { stopPropagation = 1; break; } } return stopPropagation; } // Check all conditions are fulfilled. else { stopPropagation = 1; for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { stopPropagation = 0; break; } } } // Save if conditions were met if( stopPropagation ) { for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { isConditionMetWhenStopping_[ i ] = false; } else { isConditionMetWhenStopping_[ i ] = true; } } } return stopPropagation; } //! Function to create propagation termination conditions from associated settings boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions( const boost::shared_ptr< PropagationTerminationSettings > terminationSettings, const simulation_setup::NamedBodyMap& bodyMap, const double initialTimeStep ) { boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition; // Check termination type. switch( terminationSettings->terminationType_ ) { case time_stopping_condition: { // Create stopping time termination condition. boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings = boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings ); propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >( timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ), timeTerminationSettings->terminateExactlyOnFinalCondition_ ); break; } case cpu_time_stopping_condition: { // Create stopping time termination condition. boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings = boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings ); propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >( cpuTimeTerminationSettings->cpuTerminationTime_ ); break; } case dependent_variable_stopping_condition: { boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings = boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings ); // Get dependent variable function boost::function< double( ) > dependentVariableFunction; if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 ) { dependentVariableFunction = getDoubleDependentVariableFunction( dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap ); } else { throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" ); } // Create dependent variable termination condition. propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >( dependentVariableTerminationSettings->dependentVariableSettings_, dependentVariableFunction, dependentVariableTerminationSettings->limitValue_, dependentVariableTerminationSettings->useAsLowerLimit_, dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_, dependentVariableTerminationSettings->terminationRootFinderSettings_ ); break; } case hybrid_stopping_condition: { boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings = boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings ); // Recursively create termination condition list. std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList; for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ ) { propagationTerminationConditionList.push_back( createPropagationTerminationConditions( hybridTerminationSettings->terminationSettings_.at( i ), bodyMap, initialTimeStep ) ); } propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >( propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_, hybridTerminationSettings->terminateExactlyOnFinalCondition_ ); break; } default: std::string errorMessage = "Error, stopping condition type " + std::to_string( terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object"; throw std::runtime_error( errorMessage ); break; } return propagationTerminationCondition; } // namespace propagators } // namespace tudat } <commit_msg>Fixed another small bug in accurate termination<commit_after>/* Copyright (c) 2010-2017, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h" namespace tudat { namespace propagators { //! Function to check whether the propagation is to be be stopped bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { bool stopPropagation = 0; // Check whether stop time has been reached if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) ) { stopPropagation = 1; } else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) ) { stopPropagation = 1; } return stopPropagation; } //! Function to check whether the propagation is to be be stopped bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { return cpuTime >= cpuStopTime_; } //! Function to check whether the propagation is to be be stopped bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { bool stopPropagation = 0; double currentVariable = variableRetrievalFuntion_( ); if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) ) { stopPropagation = 1; } else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) ) { stopPropagation = 1; } return stopPropagation; } //! Function to check whether the propagation is to be be stopped bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime ) { // Check if single condition is fulfilled. bool stopPropagation = -1; if( fulFillSingleCondition_ ) { stopPropagation = 0; for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { stopPropagation = 1; break; } } } // Check all conditions are fulfilled. else { stopPropagation = 1; for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { stopPropagation = 0; break; } } } // Save if conditions were met if( stopPropagation ) { for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ ) { if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) ) { isConditionMetWhenStopping_[ i ] = false; } else { isConditionMetWhenStopping_[ i ] = true; } } } return stopPropagation; } //! Function to create propagation termination conditions from associated settings boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions( const boost::shared_ptr< PropagationTerminationSettings > terminationSettings, const simulation_setup::NamedBodyMap& bodyMap, const double initialTimeStep ) { boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition; // Check termination type. switch( terminationSettings->terminationType_ ) { case time_stopping_condition: { // Create stopping time termination condition. boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings = boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings ); propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >( timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ), timeTerminationSettings->terminateExactlyOnFinalCondition_ ); break; } case cpu_time_stopping_condition: { // Create stopping time termination condition. boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings = boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings ); propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >( cpuTimeTerminationSettings->cpuTerminationTime_ ); break; } case dependent_variable_stopping_condition: { boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings = boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings ); // Get dependent variable function boost::function< double( ) > dependentVariableFunction; if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 ) { dependentVariableFunction = getDoubleDependentVariableFunction( dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap ); } else { throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" ); } // Create dependent variable termination condition. propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >( dependentVariableTerminationSettings->dependentVariableSettings_, dependentVariableFunction, dependentVariableTerminationSettings->limitValue_, dependentVariableTerminationSettings->useAsLowerLimit_, dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_, dependentVariableTerminationSettings->terminationRootFinderSettings_ ); break; } case hybrid_stopping_condition: { boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings = boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings ); // Recursively create termination condition list. std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList; for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ ) { propagationTerminationConditionList.push_back( createPropagationTerminationConditions( hybridTerminationSettings->terminationSettings_.at( i ), bodyMap, initialTimeStep ) ); } propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >( propagationTerminationConditionList, hybridTerminationSettings->fulFillSingleCondition_, hybridTerminationSettings->terminateExactlyOnFinalCondition_ ); break; } default: std::string errorMessage = "Error, stopping condition type " + std::to_string( terminationSettings->terminationType_ ) + "not recognized when making stopping conditions object"; throw std::runtime_error( errorMessage ); break; } return propagationTerminationCondition; } // namespace propagators } // namespace tudat } <|endoftext|>
<commit_before>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; #include "clang/Basic/Version.h" #ifdef HAVE_SVN_VERSION_INC # include "SVNVersion.inc" #endif #ifdef HAVE_APPLE_VERSION_INC # include "AppleVersion.inc" #endif static const char *GetLLDBRevision() { #ifdef LLDB_REVISION return LLDB_REVISION; #else return NULL; #endif } static const char *GetLLDBRepository() { #ifdef LLDB_REPOSITORY return LLDB_REPOSITORY; #else return NULL; #endif } #define QUOTE(str) #str #define EXPAND_AND_QUOTE(str) QUOTE(str) const char *lldb_private::GetVersion() { // On platforms other than Darwin, report a version number in the same style // as the clang tool. static std::string g_version_str; if (g_version_str.empty()) { g_version_str += "lldb version "; g_version_str += CLANG_VERSION_STRING; const char *lldb_repo = GetLLDBRepository(); const char *lldb_rev = GetLLDBRevision(); if (lldb_repo || lldb_rev) { g_version_str += " ("; if (lldb_repo) g_version_str += lldb_repo; if (lldb_rev) { g_version_str += " revision "; g_version_str += lldb_rev; } g_version_str += ")"; } std::string clang_rev(clang::getClangRevision()); if (clang_rev.length() > 0) { g_version_str += "\n clang revision "; g_version_str += clang_rev; } std::string llvm_rev(clang::getLLVMRevision()); if (llvm_rev.length() > 0) { g_version_str += "\n llvm revision "; g_version_str += llvm_rev; } } return g_version_str.c_str(); } <commit_msg>Run clang-format on lldb.cpp<commit_after>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; #include "clang/Basic/Version.h" #ifdef HAVE_SVN_VERSION_INC #include "SVNVersion.inc" #endif #ifdef HAVE_APPLE_VERSION_INC #include "AppleVersion.inc" #endif static const char *GetLLDBRevision() { #ifdef LLDB_REVISION return LLDB_REVISION; #else return NULL; #endif } static const char *GetLLDBRepository() { #ifdef LLDB_REPOSITORY return LLDB_REPOSITORY; #else return NULL; #endif } #define QUOTE(str) #str #define EXPAND_AND_QUOTE(str) QUOTE(str) const char *lldb_private::GetVersion() { // On platforms other than Darwin, report a version number in the same style // as the clang tool. static std::string g_version_str; if (g_version_str.empty()) { g_version_str += "lldb version "; g_version_str += CLANG_VERSION_STRING; const char *lldb_repo = GetLLDBRepository(); const char *lldb_rev = GetLLDBRevision(); if (lldb_repo || lldb_rev) { g_version_str += " ("; if (lldb_repo) g_version_str += lldb_repo; if (lldb_rev) { g_version_str += " revision "; g_version_str += lldb_rev; } g_version_str += ")"; } std::string clang_rev(clang::getClangRevision()); if (clang_rev.length() > 0) { g_version_str += "\n clang revision "; g_version_str += clang_rev; } std::string llvm_rev(clang::getLLVMRevision()); if (llvm_rev.length() > 0) { g_version_str += "\n llvm revision "; g_version_str += llvm_rev; } } return g_version_str.c_str(); } <|endoftext|>
<commit_before>// // // Created by Steven Massey on 4/15/19. // Copyright © 2019 Steven Massey. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include "m3.hpp" #include <time.h> extern "C" { # include "m3_core.h" } #include "m3_host.h" void m3Output (const char * i_string) { printf ("%s\n", i_string); } int main (int i_argc, const char * i_argv []) { M3Result result = c_m3Err_none; m3_PrintM3Info (); if (i_argc >= 2) { FILE * f = fopen (i_argv [1], "rb"); if (f) { fseek (f, 0, SEEK_END); size_t fsize = ftell (f); fseek (f, 0, SEEK_SET); if (fsize < 100000) { u8 * wasm = (u8 *) malloc (fsize); if (wasm) { IM3Runtime env = nullptr; try { fread (wasm, 1, fsize, f); fclose (f); IM3Module module; result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result; env = m3_NewRuntime (32768); result = m3_LoadModule (env, module); if (result) throw result; m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut); m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output); m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export); m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64); m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32); m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn); m3_LinkFunction (module, "abortStackOverflow", "v(i)", (void *) m3_abort); result = m3_LinkCStd (module); if (result) throw result; m3_PrintRuntimeInfo (env); IM3Function f; result = m3_FindFunction (& f, env, "__post_instantiate"); //if (result) throw result; if (not result) { result = m3_Call (f); if (result) throw result; } IM3Function main; result = m3_FindFunction (& main, env, "_main"); if (result) throw result; if (main) { printf ("found _main\n"); clock_t start = clock (); // result = m3_Call (main); if (i_argc) { --i_argc; ++i_argv; } result = m3_CallWithArgs (main, i_argc, i_argv); clock_t end = clock (); double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ; printf("%lf\n", elapsed_time); // printf ("call: %s\n", result); m3_PrintProfilerInfo (); } } catch (const M3Result & r) {} if (result) { printf ("result: %s", result); if (env) { M3ErrorInfo info = m3_GetErrorInfo (env); printf (" (%s)", info.message); } printf ("\n"); } m3_FreeRuntime (env); } free (wasm); } } else printf ("couldn't open '%s'\n", i_argv [1]); } printf ("\n"); return 0; } <commit_msg>Allow running arbitrary exported function<commit_after>// // // Created by Steven Massey on 4/15/19. // Copyright © 2019 Steven Massey. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include "m3.hpp" #include <time.h> extern "C" { # include "m3_core.h" } #include "m3_host.h" void m3Output (const char * i_string) { printf ("%s\n", i_string); } int main (int i_argc, const char * i_argv []) { M3Result result = c_m3Err_none; if (i_argc >= 2) { FILE * f = fopen (i_argv [1], "rb"); if (f) { fseek (f, 0, SEEK_END); size_t fsize = ftell (f); fseek (f, 0, SEEK_SET); if (fsize < 100000) { u8 * wasm = (u8 *) malloc (fsize); if (wasm) { IM3Runtime env = nullptr; try { fread (wasm, 1, fsize, f); fclose (f); IM3Module module; result = m3_ParseModule (& module, wasm, (u32) fsize); if (result) throw result; env = m3_NewRuntime (32768); result = m3_LoadModule (env, module); if (result) throw result; m3_LinkFunction (module, "_m3TestOut", "v(iFi)", (void *) m3TestOut); m3_LinkFunction (module, "_m3StdOut", "v(*)", (void *) m3Output); m3_LinkFunction (module, "_m3Export", "v(*i)", (void *) m3Export); m3_LinkFunction (module, "_m3Out_f64", "v(F)", (void *) m3Out_f64); m3_LinkFunction (module, "_m3Out_i32", "v(i)", (void *) m3Out_i32); m3_LinkFunction (module, "_TestReturn", "F(i)", (void *) TestReturn); m3_LinkFunction (module, "abortStackOverflow", "v(i)", (void *) m3_abort); result = m3_LinkCStd (module); if (result) throw result; m3_PrintRuntimeInfo (env); IM3Function f; result = m3_FindFunction (& f, env, "__post_instantiate"); //if (result) throw result; if (not result) { result = m3_Call (f); if (result) throw result; } IM3Function main; result = m3_FindFunction (& main, env, i_argv[2]); if (result) throw result; if (main) { printf ("found %s\n", i_argv[2]); clock_t start = clock (); // result = m3_Call (main); if (i_argc) { i_argc -= 2; i_argv += 2; } result = m3_CallWithArgs (main, i_argc, i_argv); clock_t end = clock (); double elapsed_time = (end - start) / (double) CLOCKS_PER_SEC ; printf("Time: %.3lf s\n", elapsed_time); // printf ("call: %s\n", result); m3_PrintProfilerInfo (); } } catch (const M3Result & r) {} if (result) { printf ("result: %s", result); if (env) { M3ErrorInfo info = m3_GetErrorInfo (env); printf (" (%s)", info.message); } printf ("\n"); return 1; } m3_FreeRuntime (env); } free (wasm); } } else printf ("couldn't open '%s'\n", i_argv [1]); } else printf ("not enough arguments\n"); printf ("\n"); return 0; } <|endoftext|>
<commit_before>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.4" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << batchInfo; details << "(" << pos << " / " << totalSize << ")" << "\n"; details << "Press B to cancel."; uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, (u32) ((pos * 100) / totalSize)); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << fileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); batchInfo = ""; if(ret != APP_SUCCESS) { Error error = platformGetError(); platformSetError(error); std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) { failed = true; break; } } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << fileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Add option to disable prompts when installing over the network.<commit_after>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.5" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << batchInfo; details << "(" << pos << " / " << totalSize << ")" << "\n"; details << "Press B to cancel."; uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, (u32) ((pos * 100) / totalSize)); inputPoll(); return !inputIsPressed(BUTTON_B); }; bool showNetworkPrompts = true; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) { if(inputIsPressed(BUTTON_A)) { showNetworkPrompts = !showNetworkPrompts; } infoStream << "\n"; infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n"; infoStream << "Press A to toggle prompts." << "\n"; }); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); if(showNetworkPrompts || ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << fileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); batchInfo = ""; if(ret != APP_SUCCESS) { Error error = platformGetError(); platformSetError(error); std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) { failed = true; break; } } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << fileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before>#include <type_traits> #define GLM_FORCE_RADIANS #include <glow/VertexArrayObject.h> #include <glow/Error.h> #include <glow/StaticStringSource.h> #include <glow/Program.h> #include <glow/Buffer.h> #include <glow/VertexAttributeBinding.h> #include <glowutils/StringTemplate.h> #include <glowwindow/Context.h> #include <glowwindow/ContextFormat.h> #include <glowwindow/MainLoop.h> #include <glowwindow/Window.h> #include <glowwindow/WindowEventHandler.h> #include <glowwindow/events.h> #include <GL/glx.h> namespace { const char* vertexShaderCode = R"( #version 140 #extension GL_ARB_explicit_attrib_location : require layout (location = 0) in vec2 corner; out vec4 color; void main() { gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0); color = vec4(corner, 0.0, 1.0); } )"; const char* fragmentShaderCode = R"( #version 140 #extension GL_ARB_explicit_attrib_location : require layout (location = 0) out vec4 fragColor; in vec4 color; void main() { fragColor = color; } )"; } namespace { __GLXextFuncPtr (*glowGetProcAddress) (const GLubyte*) = glXGetProcAddressARB; GLenum (*glowGetError) (void); inline void CheckGlowError() { assert(glowGetError() == GL_NO_ERROR); } template <typename ReturnType, typename... Arguments> class GlowFunction { public: using FunctionSignature = ReturnType (*) (Arguments...); GlowFunction() : m_valid(false) { } GlowFunction(FunctionSignature functionPointer) : m_functionPointer(functionPointer) , m_valid(true) { } void setFunction(FunctionSignature functionPointer) { m_valid = true; m_functionPointer = functionPointer; } ReturnType operator()(Arguments... arguments) { assert(m_valid); ReturnType returnValue = m_functionPointer(std::forward<Arguments>(arguments)...); CheckGlowError(); return returnValue; } protected: FunctionSignature m_functionPointer; bool m_valid; }; template <typename... Arguments> class GlowFunction<void, Arguments...> { public: using FunctionSignature = void (*) (Arguments...); GlowFunction() : m_valid(false) { } GlowFunction(FunctionSignature functionPointer) : m_functionPointer(functionPointer) , m_valid(true) { } void setFunction(FunctionSignature functionPointer) { m_valid = true; m_functionPointer = functionPointer; } void operator()(Arguments... arguments) { assert(m_valid); m_functionPointer(std::forward<Arguments>(arguments)...); CheckGlowError(); } protected: FunctionSignature m_functionPointer; bool m_valid; }; template <typename ReturnType, typename... Arguments> void initializeCheckedGlowFunction(const char* name, GlowFunction<ReturnType, Arguments...> & functor) { functor.setFunction( reinterpret_cast<typename GlowFunction<ReturnType, Arguments...>::FunctionSignature>( glowGetProcAddress(reinterpret_cast<const GLubyte*>(name)) ) ); } template <typename FunctionSignature> void initializeGlowFunction(const char* name, FunctionSignature & functionPointer) { functionPointer = reinterpret_cast<FunctionSignature>(glowGetProcAddress(reinterpret_cast<const GLubyte*>(name))); } GlowFunction<void, GLbitfield> glowClear; GlowFunction<void, GLfloat, GLfloat, GLfloat, GLfloat> glowClearColor; GlowFunction<void, GLsizei, GLuint*> glowGenBuffers; GlowFunction<void, GLsizei, GLuint*> glowDeleteBuffers; } class EventHandler : public glowwindow::WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { cornerBuffer->unref(); program->unref(); vao->unref(); glowDeleteBuffers(1, &m_cornerBuffer); CheckGlowError(); } virtual void initialize(glowwindow::Window &) override { initializeGlowFunction("glGetError", glowGetError); initializeCheckedGlowFunction("glClear", glowClear); initializeCheckedGlowFunction("glClearColor", glowClearColor); initializeCheckedGlowFunction("glGenBuffers", glowGenBuffers); initializeCheckedGlowFunction("glDeleteBuffers", glowDeleteBuffers); glowClearColor(0.2f, 0.3f, 0.4f, 1.f); CheckGlowError(); auto vertexShaderSource = new glow::StaticStringSource(vertexShaderCode); auto fragmentShaderSource = new glow::StaticStringSource(fragmentShaderCode); glowGenBuffers(1, &m_cornerBuffer); CheckGlowError(); cornerBuffer = glow::Buffer::fromId(m_cornerBuffer, false); cornerBuffer->ref(); program = new glow::Program(); program->ref(); vao = new glow::VertexArrayObject(); vao->ref(); program->attach( new glow::Shader(GL_VERTEX_SHADER, vertexShaderSource), new glow::Shader(GL_FRAGMENT_SHADER, fragmentShaderSource) ); cornerBuffer->setData(std::array<glm::vec2, 4>{ { glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(0, 1), glm::vec2(1, 1) } }); vao->binding(0)->setAttribute(0); vao->binding(0)->setBuffer(cornerBuffer, 0, sizeof(glm::vec2)); vao->binding(0)->setFormat(2, GL_FLOAT); vao->enable(0); } virtual void framebufferResizeEvent(glowwindow::ResizeEvent & event) override { glViewport(0, 0, event.width(), event.height()); CheckGlowError(); } virtual void paintEvent(glowwindow::PaintEvent &) override { glowClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CheckGlowError(); program->use(); vao->drawArrays(GL_TRIANGLE_STRIP, 0, 4); } virtual void idle(glowwindow::Window & /*window*/) override { //window.repaint(); } private: GLuint m_vao; GLuint m_cornerBuffer; GLuint m_program; glow::VertexArrayObject* vao; glow::Buffer* cornerBuffer; glow::Program* program; }; int main(int /*argc*/, char* /*argv*/[]) { glowwindow::ContextFormat format; format.setVersion(3, 0); glowwindow::Window window; window.setEventHandler(new EventHandler()); if (window.create(format, "GLBindings Example")) { window.context()->setSwapInterval(glowwindow::Context::VerticalSyncronization); window.show(); return glowwindow::MainLoop::run(); } else { return 1; } } <commit_msg>Remove glow::Program from example code<commit_after>#include <type_traits> #define GLM_FORCE_RADIANS #include <glow/VertexArrayObject.h> #include <glow/Error.h> #include <glow/StaticStringSource.h> #include <glow/Program.h> #include <glow/Buffer.h> #include <glow/VertexAttributeBinding.h> #include <glowutils/StringTemplate.h> #include <glowwindow/Context.h> #include <glowwindow/ContextFormat.h> #include <glowwindow/MainLoop.h> #include <glowwindow/Window.h> #include <glowwindow/WindowEventHandler.h> #include <glowwindow/events.h> #include <GL/glx.h> namespace { const char* vertexShaderCode = R"( #version 140 #extension GL_ARB_explicit_attrib_location : require layout (location = 0) in vec2 corner; out vec4 color; void main() { gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0); color = vec4(corner, 0.0, 1.0); } )"; const char* fragmentShaderCode = R"( #version 140 #extension GL_ARB_explicit_attrib_location : require layout (location = 0) out vec4 fragColor; in vec4 color; void main() { fragColor = color; } )"; } namespace { __GLXextFuncPtr (*glowGetProcAddress) (const GLubyte*) = glXGetProcAddressARB; GLenum (*glowGetError) (void); inline void CheckGlowError() { assert(glowGetError() == GL_NO_ERROR); } template <typename ReturnType, typename... Arguments> class GlowFunction { public: using FunctionSignature = ReturnType (*) (Arguments...); GlowFunction() : m_valid(false) { } GlowFunction(FunctionSignature functionPointer) : m_functionPointer(functionPointer) , m_valid(true) { } void setFunction(FunctionSignature functionPointer) { m_valid = true; m_functionPointer = functionPointer; } ReturnType operator()(Arguments... arguments) { assert(m_valid); ReturnType returnValue = m_functionPointer(std::forward<Arguments>(arguments)...); CheckGlowError(); return returnValue; } protected: FunctionSignature m_functionPointer; bool m_valid; }; template <typename... Arguments> class GlowFunction<void, Arguments...> { public: using FunctionSignature = void (*) (Arguments...); GlowFunction() : m_valid(false) { } GlowFunction(FunctionSignature functionPointer) : m_functionPointer(functionPointer) , m_valid(true) { } void setFunction(FunctionSignature functionPointer) { m_valid = true; m_functionPointer = functionPointer; } void operator()(Arguments... arguments) { assert(m_valid); m_functionPointer(std::forward<Arguments>(arguments)...); CheckGlowError(); } protected: FunctionSignature m_functionPointer; bool m_valid; }; template <typename ReturnType, typename... Arguments> void initializeGlowFunction(const char* name, GlowFunction<ReturnType, Arguments...> & functor) { functor.setFunction( reinterpret_cast<typename GlowFunction<ReturnType, Arguments...>::FunctionSignature>( glowGetProcAddress(reinterpret_cast<const GLubyte*>(name)) ) ); } template <typename FunctionSignature> void initializeGlowFunction(const char* name, FunctionSignature & functionPointer) { functionPointer = reinterpret_cast<FunctionSignature>(glowGetProcAddress(reinterpret_cast<const GLubyte*>(name))); } GlowFunction<void, GLbitfield> glowClear; GlowFunction<void, GLfloat, GLfloat, GLfloat, GLfloat> glowClearColor; GlowFunction<void, GLsizei, GLuint*> glowGenBuffers; GlowFunction<void, GLsizei, GLuint*> glowDeleteBuffers; GlowFunction<void, GLint, GLint, GLsizei, GLsizei> glowViewport; GlowFunction<void, GLuint> glowBindVertexArray; GlowFunction<void, GLuint> glowUseProgram; GlowFunction<void, GLenum, GLint, GLsizei> glowDrawArrays; GlowFunction<GLuint> glowCreateProgram; GlowFunction<void, GLuint> glowDeleteProgram; GlowFunction<void, GLsizei, GLuint*> glowGenVertexArrays; GlowFunction<void, GLsizei, GLuint*> glowDeleteVertexArrays; GlowFunction<void, GLuint> glowLinkProgram; GlowFunction<void, GLuint> glowCompileShader; GlowFunction<void, GLuint, GLuint> glowAttachShader; } class EventHandler : public glowwindow::WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { glowDeleteBuffers(1, &m_cornerBuffer); glowDeleteProgram(m_program); glowDeleteVertexArrays(1, &m_vao); } virtual void initialize(glowwindow::Window &) override { initializeGlowFunction("glGetError", glowGetError); initializeGlowFunction("glClear", glowClear); initializeGlowFunction("glClearColor", glowClearColor); initializeGlowFunction("glGenBuffers", glowGenBuffers); initializeGlowFunction("glDeleteBuffers", glowDeleteBuffers); initializeGlowFunction("glViewport", glowViewport); initializeGlowFunction("glBindVertexArray", glowBindVertexArray); initializeGlowFunction("glUseProgram", glowUseProgram); initializeGlowFunction("glDrawArrays", glowDrawArrays); initializeGlowFunction("glCreateProgram", glowCreateProgram); initializeGlowFunction("glDeleteProgram", glowDeleteProgram); initializeGlowFunction("glGenVertexArrays", glowGenVertexArrays); initializeGlowFunction("glDeleteVertexArrays", glowDeleteVertexArrays); initializeGlowFunction("glLinkProgram", glowLinkProgram); initializeGlowFunction("glCompileShader", glowCompileShader); initializeGlowFunction("glAttachShader", glowAttachShader); glowClearColor(0.2f, 0.3f, 0.4f, 1.f); auto vertexShaderSource = new glow::StaticStringSource(vertexShaderCode); auto fragmentShaderSource = new glow::StaticStringSource(fragmentShaderCode); glowGenBuffers(1, &m_cornerBuffer); m_program = glowCreateProgram(); glowGenVertexArrays(1, &m_vao); cornerBuffer = glow::Buffer::fromId(m_cornerBuffer, false); cornerBuffer->ref(); vao = glow::VertexArrayObject::fromId(m_vao, false); vao->ref(); glow::Shader* vertexShader = new glow::Shader(GL_VERTEX_SHADER, vertexShaderSource); vertexShader->ref(); glow::Shader* fragmentShader = new glow::Shader(GL_FRAGMENT_SHADER, fragmentShaderSource); fragmentShader->ref(); m_vertexShader = vertexShader->id(); m_fragmentShader = fragmentShader->id(); cornerBuffer->setData(std::array<glm::vec2, 4>{ { glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(0, 1), glm::vec2(1, 1) } }); vao->binding(0)->setAttribute(0); vao->binding(0)->setBuffer(cornerBuffer, 0, sizeof(glm::vec2)); vao->binding(0)->setFormat(2, GL_FLOAT); vao->enable(0); glowCompileShader(m_vertexShader); glowCompileShader(m_fragmentShader); glowAttachShader(m_program, m_vertexShader); glowAttachShader(m_program, m_fragmentShader); glowLinkProgram(m_program); } virtual void framebufferResizeEvent(glowwindow::ResizeEvent & event) override { glowViewport(0, 0, event.width(), event.height()); } virtual void paintEvent(glowwindow::PaintEvent &) override { glowClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glowBindVertexArray(vao->id()); glowUseProgram(m_program); glowDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glowUseProgram(0); glowBindVertexArray(0); } virtual void idle(glowwindow::Window & /*window*/) override { //window.repaint(); } private: GLuint m_vao; GLuint m_cornerBuffer; GLuint m_program; GLuint m_vertexShader; GLuint m_fragmentShader; glow::VertexArrayObject* vao; glow::Buffer* cornerBuffer; }; int main(int /*argc*/, char* /*argv*/[]) { glowwindow::ContextFormat format; format.setVersion(3, 0); glowwindow::Window window; window.setEventHandler(new EventHandler()); if (window.create(format, "GLBindings Example")) { window.context()->setSwapInterval(glowwindow::Context::VerticalSyncronization); window.show(); return glowwindow::MainLoop::run(); } else { return 1; } } <|endoftext|>
<commit_before> #include <QSurfaceFormat> #include <QWidget> #include "Application.h" #include "Viewer.h" #include "Canvas.h" #include "Painter.h" int main(int argc, char* argv[]) { int result = -1; Application app(argc, argv); { QScopedPointer<Viewer> viewer(new Viewer()); QSurfaceFormat format; #ifdef NO_OPENGL_320 format.setVersion(3, 0); #else format.setVersion(3, 2); format.setProfile(QSurfaceFormat::CoreProfile); #endif Canvas * canvas = new Canvas(format); canvas->setContinuousRepaint(true, 0); canvas->setSwapInterval(Canvas::VerticalSyncronization); QObject::connect(canvas, &Canvas::fpsUpdate, viewer.data(), &Viewer::fpsChanged); QObject::connect(canvas, &Canvas::objUpdate, viewer.data(), &Viewer::objChanged); QObject::connect(canvas, &Canvas::timeUpdate, viewer.data(), &Viewer::timeChanged); QObject::connect(canvas, &Canvas::mouseUpdate, viewer.data(), &Viewer::mouseChanged); QObject::connect(viewer.data(), &Viewer::toggleSwapInterval, canvas, &Canvas::toggleSwapInterval); Painter painter; canvas->assignPainter(&painter); QWidget * widget = QWidget::createWindowContainer(canvas); widget->setMinimumSize(1, 1); widget->setAutoFillBackground(false); // Important for overdraw, not occluding the scene. widget->setFocusPolicy(Qt::TabFocus); viewer->setCentralWidget(widget); viewer->show(); result = app.exec(); canvas->assignPainter(nullptr); } return result; }<commit_msg>Add comment indicating a bug<commit_after> #include <QSurfaceFormat> #include <QWidget> #include "Application.h" #include "Viewer.h" #include "Canvas.h" #include "Painter.h" int main(int argc, char* argv[]) { int result = -1; Application app(argc, argv); QScopedPointer<Viewer> viewer(new Viewer()); QSurfaceFormat format; #ifdef NO_OPENGL_320 format.setVersion(3, 0); #else format.setVersion(3, 2); format.setProfile(QSurfaceFormat::CoreProfile); #endif Canvas* canvas = new Canvas(format); canvas->setContinuousRepaint(true, 0); canvas->setSwapInterval(Canvas::VerticalSyncronization); QObject::connect(canvas, &Canvas::fpsUpdate, viewer.data(), &Viewer::fpsChanged); QObject::connect(canvas, &Canvas::objUpdate, viewer.data(), &Viewer::objChanged); QObject::connect(canvas, &Canvas::timeUpdate, viewer.data(), &Viewer::timeChanged); QObject::connect(canvas, &Canvas::mouseUpdate, viewer.data(), &Viewer::mouseChanged); QObject::connect(viewer.data(), &Viewer::toggleSwapInterval, canvas, &Canvas::toggleSwapInterval); Painter painter; canvas->assignPainter(&painter); QWidget * widget = QWidget::createWindowContainer(canvas); widget->setMinimumSize(1, 1); widget->setAutoFillBackground(false); // Important for overdraw, not occluding the scene. widget->setFocusPolicy(Qt::TabFocus); viewer->setCentralWidget(widget); viewer->show(); result = app.exec(); canvas->assignPainter(nullptr); return result; // QWidget seems to take double ownership of canvas and frees it doubled } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed.h" #include "ble/BLE.h" #include "ble-blocktransfer/BlockTransferService.h" #include "voytalk/Voytalk.h" /*****************************************************************************/ /* Configuration */ /*****************************************************************************/ // set device name const char DEVICE_NAME[] = "Testoy"; // set TX power #ifndef CFG_BLE_TX_POWER_LEVEL #define CFG_BLE_TX_POWER_LEVEL 0 #endif // control debug output #if 1 #define DEBUGOUT(...) { printf(__VA_ARGS__); } #else #define DEBUGOUT(...) /* nothing */ #endif // DEBUGOUT #define VERBOSE_DEBUG_OUT 1 /*****************************************************************************/ /* Voytalk short UUID */ const UUID uuid(0xFE8E); /* Voytalk states */ typedef enum { FLAG_CONNECTED = 0x01, FLAG_PROVISIONED = 0x02, } flags_t; static volatile uint8_t state; /*****************************************************************************/ /* Global variables used by the test app */ /*****************************************************************************/ // BLE_API ble device BLE ble; // Transfer large blocks of data on platforms without Fragmentation-And-Recombination BlockTransferService bts; // buffer for sending data uint8_t readBuffer[1000]; SharedPointer<Block> readBlock(new BlockStatic(readBuffer, sizeof(readBuffer))); // wifi parameters std::string ssid_string; std::string key_string; // Compatibility function void signalReady(); void onResponseFinished(const VTResponse& res) { DEBUGOUT("main: output buffer usage: %lu of %lu\r\n", readBlock->getLength(), readBlock->getMaxLength()); signalReady(); } // Voytalk handling VoytalkRouter router(DEVICE_NAME, onResponseFinished); /*****************************************************************************/ /* Functions for handling debug output */ /*****************************************************************************/ /* Functions called when BLE device connects and disconnects. */ void whenConnected(const Gap::ConnectionCallbackParams_t* params) { (void) params; DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval, params->connectionParams->maxConnectionInterval, params->connectionParams->slaveLatency); // change state in main application state |= FLAG_CONNECTED; // change state inside Voytalk hub router.setStateMask(state); } void whenDisconnected(const Gap::DisconnectionCallbackParams_t*) { DEBUGOUT("main: Disconnected!\r\n"); DEBUGOUT("main: Restarting the advertising process\r\n"); ble.gap().startAdvertising(); // change state in main application state &= ~FLAG_CONNECTED; // change state inside Voytalk hub router.setStateMask(state); } /*****************************************************************************/ /* BlockTransfer callbacks for sending and receiving data */ /*****************************************************************************/ /* Function called when signaling client that new data is ready to be read. */ void blockServerSendNotification() { DEBUGOUT("main: notify read updated\r\n"); bts.updateCharacteristicValue((uint8_t*)"", 0); } /* Function called when device receives a read request over BLE. */ SharedPointer<Block> blockServerReadHandler(uint32_t offset) { DEBUGOUT("main: block read\r\n"); (void) offset; #if VERBOSE_DEBUG_OUT /* print generated output */ if (readBlock->getLength() > 0) { for (size_t idx = 0; idx < readBlock->getLength(); idx++) { DEBUGOUT("%02X", readBlock->at(idx)); } DEBUGOUT("\r\n\r\n"); } #endif return readBlock; } /* Function called when data has been written over BLE. */ void blockServerWriteHandler(SharedPointer<Block> block) { DEBUGOUT("main: block write\r\n"); #if VERBOSE_DEBUG_OUT DEBUGOUT("main write:\r\n"); for (size_t idx = 0; idx < block->getLength(); idx++) { DEBUGOUT("%02X", block->at(idx)); } DEBUGOUT("\r\n\r\n"); #endif /* Process received data, assuming it is CBOR encoded. Any output generated will be written to the readBlock. */ DEBUGOUT("main: input buffer usage: %lu of %lu\r\n", block->getLength(), block->getMaxLength()); router.processCBOR((BlockStatic*) block.get(), (BlockStatic*) readBlock.get()); } /*****************************************************************************/ /* Voytalk Wifi example */ /*****************************************************************************/ /* Callback function for constructing wifi intent. */ void wifiIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: wifi intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.connectivity.wifi"); intent.knownParameters("/networks") .endpoint("/wifi"); res.write(intent); } /*****************************************************************************/ /* Reset device example */ /*****************************************************************************/ void resetIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: reset intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.reset"); intent.endpoint("/reset"); res.write(intent); } /*****************************************************************************/ /* Voytalk complex example */ /*****************************************************************************/ /* Callback functions for the example intent. */ void exampleIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: complex example intent construction\r\n"); /* create intent */ VTIntent intent("com.arm.examples.complex"); intent.endpoint("/examples/complex"); res.write(intent); } /*****************************************************************************/ /* Voytalk custom example */ /*****************************************************************************/ void customIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: custom intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.examples.custom"); intent.endpoint("/custom") .constraints() .title("Hello!") .description("This is the description") .addProperty("test", VTConstraint(VTConstraint::TypeString) .title("Test") .defaultValue("default goes here") ) .addProperty("test2", VTConstraint(VTConstraint::TypeString) .title("Other test") .defaultValue("default goes here") ); res.write(intent); } /*****************************************************************************/ /* Middleware for actually doing stuff */ /*****************************************************************************/ void printInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { VTIntentInvocation invocation(req.getBody()); invocation.getParameters().print(); next(); } void saveWifi(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: saving wifi details\r\n"); VTIntentInvocation invocation(req.getBody()); invocation.getParameters().find("ssid").getString(ssid_string); invocation.getParameters().find("key").getString(key_string); // change state in main application state |= FLAG_PROVISIONED; // change state inside Voytalk hub router.setStateMask(state); next(); } void resetDevice(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: reset device\r\n"); ssid_string = ""; key_string = ""; // change state in main application state &= ~FLAG_PROVISIONED; // change state inside Voytalk hub router.setStateMask(state); next(); } void sendSuccess(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: sending success coda\r\n"); VTIntentInvocation invocation(req.getBody()); VTCoda coda(invocation.getID()); coda.success(true); res.write(coda); next(200); } void networkList(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: listing network resources"); VoytalkKnownParameters parameters(res, 2); parameters.parameter("com.arm.connectivity.wifi", 50) .map(2) .key("ssid").value("miWifi") .key("key").value("supersecurepassword"); parameters.parameter("com.arm.connectivity.wifi", 20) .map(2) .key("ssid").value("yoWifi") .key("key").value("securepasswordinit"); next(200); } /*****************************************************************************/ /* main */ /*****************************************************************************/ void app_start(int, char *[]) { /* Register Voytalk intents in the hub. First parameter is the callback function for intent generation. Second parameter is a bitmap for grouping intents together. */ // Wifi provisioning intent router.registerIntent(wifiIntentConstruction, FLAG_CONNECTED | FLAG_PROVISIONED); // reset intent router.registerIntent(resetIntentConstruction, FLAG_PROVISIONED); // custom intent //router.registerIntent(customIntentConstruction, // FLAG_CONNECTED | FLAG_PROVISIONED); // example intent router.registerIntent(exampleIntentConstruction, FLAG_CONNECTED | FLAG_PROVISIONED); /* Set the current state mask. Mask is AND'ed with each intent's bitmap and only intents with non-zero results are displayed and can be invoked. */ router.setStateMask(0); /* Define some resource callbacks */ router.get("/networks", networkList, NULL); router.post("/wifi", printInvocation, saveWifi, sendSuccess, NULL); router.post("/reset", printInvocation, resetDevice, sendSuccess, NULL); router.post("/custom", printInvocation, sendSuccess, NULL); router.post("/examples/complex", printInvocation, sendSuccess, NULL); /*************************************************************************/ /*************************************************************************/ /* bluetooth le */ ble.init(); // status callback functions ble.gap().onConnection(whenConnected); ble.gap().onDisconnection(whenDisconnected); /* construct advertising beacon */ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen()); ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */ // set TX power ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL); // Apple uses device name instead of beacon name ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME); /*************************************************************************/ /*************************************************************************/ // setup block transfer service // add service using ble device, responding to uuid, and without encryption bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK); // set callback functions for the BlockTransfer service bts.setWriteAuthorizationCallback(blockServerWriteHandler); bts.setReadAuthorizationCallback(blockServerReadHandler); // ble setup complete - start advertising ble.gap().startAdvertising(); printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__); } /*****************************************************************************/ /* Compatibility */ /*****************************************************************************/ #if defined(YOTTA_MINAR_VERSION_STRING) /*********************************************************/ /* Build for mbed OS */ /*********************************************************/ void signalReady() { minar::Scheduler::postCallback(blockServerSendNotification); } #else /*********************************************************/ /* Build for mbed Classic */ /*********************************************************/ volatile bool sendNotification = false; void signalReady() { sendNotification = true; } int main(void) { app_start(0, NULL); for(;;) { // send notification outside of interrupt context if (sendNotification) { sendNotification = false; blockServerSendNotification(); } ble.waitForEvent(); } } #endif <commit_msg>use stream API for know parameters<commit_after>/* mbed Microcontroller Library * Copyright (c) 2006-2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed.h" #include "ble/BLE.h" #include "ble-blocktransfer/BlockTransferService.h" #include "voytalk/Voytalk.h" /*****************************************************************************/ /* Configuration */ /*****************************************************************************/ // set device name const char DEVICE_NAME[] = "Testoy"; // set TX power #ifndef CFG_BLE_TX_POWER_LEVEL #define CFG_BLE_TX_POWER_LEVEL 0 #endif // control debug output #if 1 #define DEBUGOUT(...) { printf(__VA_ARGS__); } #else #define DEBUGOUT(...) /* nothing */ #endif // DEBUGOUT #define VERBOSE_DEBUG_OUT 1 /*****************************************************************************/ /* Voytalk short UUID */ const UUID uuid(0xFE8E); /* Voytalk states */ typedef enum { FLAG_CONNECTED = 0x01, FLAG_PROVISIONED = 0x02, } flags_t; static volatile uint8_t state; /*****************************************************************************/ /* Global variables used by the test app */ /*****************************************************************************/ // BLE_API ble device BLE ble; // Transfer large blocks of data on platforms without Fragmentation-And-Recombination BlockTransferService bts; // buffer for sending data uint8_t readBuffer[1000]; SharedPointer<Block> readBlock(new BlockStatic(readBuffer, sizeof(readBuffer))); // wifi parameters std::string ssid_string; std::string key_string; // Compatibility function void signalReady(); void onResponseFinished(const VTResponse& res) { DEBUGOUT("main: output buffer usage: %lu of %lu\r\n", readBlock->getLength(), readBlock->getMaxLength()); signalReady(); } // Voytalk handling VoytalkRouter router(DEVICE_NAME, onResponseFinished); /*****************************************************************************/ /* Functions for handling debug output */ /*****************************************************************************/ /* Functions called when BLE device connects and disconnects. */ void whenConnected(const Gap::ConnectionCallbackParams_t* params) { (void) params; DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval, params->connectionParams->maxConnectionInterval, params->connectionParams->slaveLatency); // change state in main application state |= FLAG_CONNECTED; // change state inside Voytalk hub router.setStateMask(state); } void whenDisconnected(const Gap::DisconnectionCallbackParams_t*) { DEBUGOUT("main: Disconnected!\r\n"); DEBUGOUT("main: Restarting the advertising process\r\n"); ble.gap().startAdvertising(); // change state in main application state &= ~FLAG_CONNECTED; // change state inside Voytalk hub router.setStateMask(state); } /*****************************************************************************/ /* BlockTransfer callbacks for sending and receiving data */ /*****************************************************************************/ /* Function called when signaling client that new data is ready to be read. */ void blockServerSendNotification() { DEBUGOUT("main: notify read updated\r\n"); bts.updateCharacteristicValue((uint8_t*)"", 0); } /* Function called when device receives a read request over BLE. */ SharedPointer<Block> blockServerReadHandler(uint32_t offset) { DEBUGOUT("main: block read\r\n"); (void) offset; #if VERBOSE_DEBUG_OUT /* print generated output */ if (readBlock->getLength() > 0) { for (size_t idx = 0; idx < readBlock->getLength(); idx++) { DEBUGOUT("%02X", readBlock->at(idx)); } DEBUGOUT("\r\n\r\n"); } #endif return readBlock; } /* Function called when data has been written over BLE. */ void blockServerWriteHandler(SharedPointer<Block> block) { DEBUGOUT("main: block write\r\n"); #if VERBOSE_DEBUG_OUT DEBUGOUT("main write:\r\n"); for (size_t idx = 0; idx < block->getLength(); idx++) { DEBUGOUT("%02X", block->at(idx)); } DEBUGOUT("\r\n\r\n"); #endif /* Process received data, assuming it is CBOR encoded. Any output generated will be written to the readBlock. */ DEBUGOUT("main: input buffer usage: %lu of %lu\r\n", block->getLength(), block->getMaxLength()); router.processCBOR((BlockStatic*) block.get(), (BlockStatic*) readBlock.get()); } /*****************************************************************************/ /* Voytalk Wifi example */ /*****************************************************************************/ /* Callback function for constructing wifi intent. */ void wifiIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: wifi intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.connectivity.wifi"); intent.knownParameters("/networks") .endpoint("/wifi"); res.write(intent); } /*****************************************************************************/ /* Reset device example */ /*****************************************************************************/ void resetIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: reset intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.reset"); intent.endpoint("/reset"); res.write(intent); } /*****************************************************************************/ /* Voytalk complex example */ /*****************************************************************************/ /* Callback functions for the example intent. */ void exampleIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: complex example intent construction\r\n"); /* create intent */ VTIntent intent("com.arm.examples.complex"); intent.endpoint("/examples/complex"); res.write(intent); } /*****************************************************************************/ /* Voytalk custom example */ /*****************************************************************************/ void customIntentConstruction(VTRequest& req, VTResponse& res) { DEBUGOUT("main: custom intent construction\r\n"); /* create intent using generated endpoint and constraint set */ VTIntent intent("com.arm.examples.custom"); intent.endpoint("/custom") .constraints() .title("Hello!") .description("This is the description") .addProperty("test", VTConstraint(VTConstraint::TypeString) .title("Test") .defaultValue("default goes here") ) .addProperty("test2", VTConstraint(VTConstraint::TypeString) .title("Other test") .defaultValue("default goes here") ); res.write(intent); } /*****************************************************************************/ /* Middleware for actually doing stuff */ /*****************************************************************************/ void printInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { VTIntentInvocation invocation(req.getBody()); invocation.getParameters().print(); next(); } void saveWifi(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: saving wifi details\r\n"); VTIntentInvocation invocation(req.getBody()); invocation.getParameters().find("ssid").getString(ssid_string); invocation.getParameters().find("key").getString(key_string); // change state in main application state |= FLAG_PROVISIONED; // change state inside Voytalk hub router.setStateMask(state); next(); } void resetDevice(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: reset device\r\n"); ssid_string = ""; key_string = ""; // change state in main application state &= ~FLAG_PROVISIONED; // change state inside Voytalk hub router.setStateMask(state); next(); } void sendSuccess(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: sending success coda\r\n"); VTIntentInvocation invocation(req.getBody()); VTCoda coda(invocation.getID()); coda.success(true); res.write(coda); next(200); } void networkList(VTRequest& req, VTResponse& res, VoytalkRouter::next_t next) { DEBUGOUT("main: listing network resources"); VoytalkKnownParameters parameters(res, 2); parameters.parameter("com.arm.connectivity.wifi", 50) .map() .key("ssid").value("miWifi") .end(); parameters.parameter("com.arm.connectivity.wifi", 20) .map() .key("ssid").value("yoWifi") .end(); next(200); } /*****************************************************************************/ /* main */ /*****************************************************************************/ void app_start(int, char *[]) { /* Register Voytalk intents in the hub. First parameter is the callback function for intent generation. Second parameter is a bitmap for grouping intents together. */ // Wifi provisioning intent router.registerIntent(wifiIntentConstruction, FLAG_CONNECTED | FLAG_PROVISIONED); // reset intent router.registerIntent(resetIntentConstruction, FLAG_PROVISIONED); // custom intent //router.registerIntent(customIntentConstruction, // FLAG_CONNECTED | FLAG_PROVISIONED); // example intent router.registerIntent(exampleIntentConstruction, FLAG_CONNECTED | FLAG_PROVISIONED); /* Set the current state mask. Mask is AND'ed with each intent's bitmap and only intents with non-zero results are displayed and can be invoked. */ router.setStateMask(0); /* Define some resource callbacks */ router.get("/networks", networkList, NULL); router.post("/wifi", printInvocation, saveWifi, sendSuccess, NULL); router.post("/reset", printInvocation, resetDevice, sendSuccess, NULL); router.post("/custom", printInvocation, sendSuccess, NULL); router.post("/examples/complex", printInvocation, sendSuccess, NULL); /*************************************************************************/ /*************************************************************************/ /* bluetooth le */ ble.init(); // status callback functions ble.gap().onConnection(whenConnected); ble.gap().onDisconnection(whenDisconnected); /* construct advertising beacon */ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen()); ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */ // set TX power ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL); // Apple uses device name instead of beacon name ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME); /*************************************************************************/ /*************************************************************************/ // setup block transfer service // add service using ble device, responding to uuid, and without encryption bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK); // set callback functions for the BlockTransfer service bts.setWriteAuthorizationCallback(blockServerWriteHandler); bts.setReadAuthorizationCallback(blockServerReadHandler); // ble setup complete - start advertising ble.gap().startAdvertising(); printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__); } /*****************************************************************************/ /* Compatibility */ /*****************************************************************************/ #if defined(YOTTA_MINAR_VERSION_STRING) /*********************************************************/ /* Build for mbed OS */ /*********************************************************/ void signalReady() { minar::Scheduler::postCallback(blockServerSendNotification); } #else /*********************************************************/ /* Build for mbed Classic */ /*********************************************************/ volatile bool sendNotification = false; void signalReady() { sendNotification = true; } int main(void) { app_start(0, NULL); for(;;) { // send notification outside of interrupt context if (sendNotification) { sendNotification = false; blockServerSendNotification(); } ble.waitForEvent(); } } #endif <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <atomic> #include <mutex> #include <tbb/tbb.h> #include <unordered_map> using namespace tbb; using namespace std; inline uint64_t hashKey(uint64_t k) { // MurmurHash64A const uint64_t m = 0xc6a4a7935bd1e995; const int r = 47; uint64_t h = 0x8445d61a4e774912 ^ (8*m); k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; h ^= h >> r; h *= m; h ^= h >> r; return h|(1ull<<63); } class ChainingLockingHT { // Chained tuple entry public: struct Entry { uint64_t key; uint64_t value; Entry* next; }; struct Chain { std::mutex lock; Entry* head; uint64_t size; Chain() : head(nullptr), size(0) {} }; private: unordered_map<uint64_t, Chain*> table; public: // Constructor ChainingLockingHT(uint64_t size) { this->table = unordered_map<uint64_t, Chain*>(); } // Destructor ~ChainingLockingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { return this->table[key]->size; } inline void insert(Entry* entry) { uint64_t key = hashKey(entry->key); Chain* chain = this->table[key]; std::lock_guard<std::mutex> lock(chain->lock); Entry* curr = chain->head; while (curr->next != nullptr) { curr = curr->next; } curr->next = entry; chain->size++; } }; class ChainingHT { // Chained tuple entry public: struct Entry { uint64_t key; uint64_t value; Entry* next; }; private: unordered_map<uint64_t, ChainingHT::Entry*> hashTable; public: std::atomic<Entry*> nextOfCurrentEntry; // Constructor ChainingHT(uint64_t size){ this->hashTable = unordered_map<uint64_t, ChainingHT::Entry*>(); } // Destructor ~ChainingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { uint64_t hashedKey = hashKey(key); if(this->hashTable.count(hashedKey) < 1){ return 0; } else { Entry* e = hashTable.at(hashedKey); unsigned counter = 1; while(e->next != nullptr){ counter++; e = e->next; } return counter; } } inline void insert(Entry* entry) { uint64_t hashValue = hashKey(entry->key); // if hashValue indicates an empty bucket, just insert if(this->hashTable.find(hashValue) == this->hashTable.end()){ entry->next = nullptr; hashTable.emplace(hashValue, entry); } else { entry->next = nullptr; Entry* currentEntry = hashTable.at(hashValue); while(currentEntry->next != nullptr){ currentEntry = currentEntry->next; } Entry* tmp = 0; nextOfCurrentEntry.store(currentEntry->next); while(!nextOfCurrentEntry.compare_exchange_weak(tmp, entry, memory_order_release, memory_order_relaxed)); currentEntry->next = nextOfCurrentEntry.load(); hashTable.emplace(hashValue, entry); } } }; class LinearProbingHT { public: // Entry struct Entry { uint64_t key; uint64_t value; std::atomic<bool> marker; }; // Constructor LinearProbingHT(uint64_t size) { } // Destructor ~LinearProbingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { } inline void insert(uint64_t key, uint64_t value) { } }; int main(int argc,char** argv) { uint64_t sizeR = atoi(argv[1]); uint64_t sizeS = atoi(argv[2]); unsigned threadCount = atoi(argv[3]); task_scheduler_init init(threadCount); // Init build-side relation R with random data uint64_t* R=static_cast<uint64_t*>(malloc(sizeR*sizeof(uint64_t))); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { unsigned int seed=range.begin(); for (size_t i=range.begin(); i!=range.end(); ++i) R[i]=rand_r(&seed)%sizeR; }); // Init probe-side relation S with random data uint64_t* S=static_cast<uint64_t*>(malloc(sizeS*sizeof(uint64_t))); parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { unsigned int seed=range.begin(); for (size_t i=range.begin(); i!=range.end(); ++i) S[i]=rand_r(&seed)%sizeR; }); // STL { // Build hash table (single threaded) tick_count buildTS=tick_count::now(); unordered_multimap<uint64_t,uint64_t> ht(sizeR); for (uint64_t i=0; i<sizeR; i++) ht.emplace(R[i],0); tick_count probeTS=tick_count::now(); cout << "STL build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { auto range=ht.equal_range(S[i]); for (unordered_multimap<uint64_t,uint64_t>::iterator it=range.first; it!=range.second; ++it) localHitCounter++; } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of ChainingLockingHT { // Build hash table tick_count buildTS=tick_count::now(); ChainingLockingHT* cl(new ChainingLockingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { ChainingLockingHT::Entry* e(new ChainingLockingHT::Entry()); e->key = R[i]; e->value = 0; //see your STL Test //----- cl->insert(e); } }); tick_count probeTS=tick_count::now(); cout << "ChainingLockingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { //----- localHitCounter += cl->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of ChainingHT { // Build hash table tick_count buildTS=tick_count::now(); ChainingHT* c(new ChainingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { ChainingHT::Entry* e(new ChainingHT::Entry()); e->key = R[i]; e->value = 0; //see your STL Test c->insert(e); } }); tick_count probeTS=tick_count::now(); cout << "ChainingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { localHitCounter += c->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of LinearProbing { // Build hash table tick_count buildTS=tick_count::now(); LinearProbingHT* lp(new LinearProbingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { lp->insert(R[i], 0); //see your STL Test } }); tick_count probeTS=tick_count::now(); cout << "LinearProbingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { localHitCounter += lp->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } return 0; } <commit_msg>bugfixes for chainingLockingHt, the test now runs without segmentation fault<commit_after>#include <iostream> #include <cstdlib> #include <atomic> #include <mutex> #include <tbb/tbb.h> #include <unordered_map> using namespace tbb; using namespace std; inline uint64_t hashKey(uint64_t k) { // MurmurHash64A const uint64_t m = 0xc6a4a7935bd1e995; const int r = 47; uint64_t h = 0x8445d61a4e774912 ^ (8*m); k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; h ^= h >> r; h *= m; h ^= h >> r; return h|(1ull<<63); } class ChainingLockingHT { // Chained tuple entry public: struct Entry { uint64_t key; uint64_t value; Entry* next; }; struct Chain { std::mutex lock; Entry* head; uint64_t size; Chain() : head(nullptr), size(0) {} }; private: unordered_map<uint64_t, Chain*> table; public: // Constructor ChainingLockingHT(uint64_t size) { this->table = unordered_map<uint64_t, Chain*>(); } // Destructor ~ChainingLockingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { return this->table[hashKey(key)]->size; } inline void insert(Entry* entry) { uint64_t key = hashKey(entry->key); Chain* chain; if(this->table.find(key) == this->table.end()){ entry->next = nullptr; chain = new Chain(); chain->head = entry; chain->size++; this->table.emplace(key, chain); } else { Chain* chain = this->table[key]; std::lock_guard<std::mutex> lock(chain->lock); Entry* curr = chain->head; while (curr->next != nullptr) { curr = curr->next; } curr->next = entry; chain->size++; } } }; class ChainingHT { // Chained tuple entry public: struct Entry { uint64_t key; uint64_t value; Entry* next; }; private: unordered_map<uint64_t, ChainingHT::Entry*> hashTable; public: std::atomic<Entry*> nextOfCurrentEntry; // Constructor ChainingHT(uint64_t size){ this->hashTable = unordered_map<uint64_t, ChainingHT::Entry*>(size); } // Destructor ~ChainingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { uint64_t hashedKey = hashKey(key); if(this->hashTable.count(hashedKey) < 1){ return 0; } else { Entry* e = hashTable.at(hashedKey); unsigned counter = 1; while(e->next != nullptr){ counter++; e = e->next; } return counter; } } inline void insert(Entry* entry) { uint64_t hashValue = hashKey(entry->key); // if hashValue indicates an empty bucket, just insert if(this->hashTable.find(hashValue) == this->hashTable.end()){ entry->next = nullptr; hashTable.emplace(hashValue, entry); } else { entry->next = nullptr; Entry* currentEntry = hashTable.at(hashValue); while(currentEntry->next != nullptr){ currentEntry = currentEntry->next; } Entry* tmp = 0; nextOfCurrentEntry.store(currentEntry->next); while(!nextOfCurrentEntry.compare_exchange_weak(tmp, entry, memory_order_release, memory_order_relaxed)); currentEntry->next = nextOfCurrentEntry.load(); hashTable.emplace(hashValue, entry); } } }; class LinearProbingHT { public: // Entry struct Entry { uint64_t key; uint64_t value; std::atomic<bool> marker; }; // Constructor LinearProbingHT(uint64_t size) { } // Destructor ~LinearProbingHT() { } // Returns the number of hits inline uint64_t lookup(uint64_t key) { } inline void insert(uint64_t key, uint64_t value) { } }; int main(int argc,char** argv) { uint64_t sizeR = atoi(argv[1]); uint64_t sizeS = atoi(argv[2]); unsigned threadCount = atoi(argv[3]); task_scheduler_init init(threadCount); // Init build-side relation R with random data uint64_t* R=static_cast<uint64_t*>(malloc(sizeR*sizeof(uint64_t))); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { unsigned int seed=range.begin(); for (size_t i=range.begin(); i!=range.end(); ++i) R[i]=rand_r(&seed)%sizeR; }); // Init probe-side relation S with random data uint64_t* S=static_cast<uint64_t*>(malloc(sizeS*sizeof(uint64_t))); parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { unsigned int seed=range.begin(); for (size_t i=range.begin(); i!=range.end(); ++i) S[i]=rand_r(&seed)%sizeR; }); // STL { // Build hash table (single threaded) tick_count buildTS=tick_count::now(); unordered_multimap<uint64_t,uint64_t> ht(sizeR); for (uint64_t i=0; i<sizeR; i++) ht.emplace(R[i],0); tick_count probeTS=tick_count::now(); cout << "STL build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { auto range=ht.equal_range(S[i]); for (unordered_multimap<uint64_t,uint64_t>::iterator it=range.first; it!=range.second; ++it) localHitCounter++; } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of ChainingLockingHT { // Build hash table tick_count buildTS=tick_count::now(); ChainingLockingHT* cl(new ChainingLockingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { ChainingLockingHT::Entry* e(new ChainingLockingHT::Entry()); e->key = R[i]; e->value = 0; //see your STL Test cl->insert(e); } }); tick_count probeTS=tick_count::now(); cout << "ChainingLockingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { localHitCounter += cl->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of ChainingHT { // Build hash table tick_count buildTS=tick_count::now(); ChainingHT* c(new ChainingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { ChainingHT::Entry* e(new ChainingHT::Entry()); e->key = R[i]; e->value = 0; //see your STL Test c->insert(e); } }); tick_count probeTS=tick_count::now(); cout << "ChainingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { localHitCounter += c->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } // Test of LinearProbing { // Build hash table tick_count buildTS=tick_count::now(); LinearProbingHT* lp(new LinearProbingHT(sizeR)); parallel_for(blocked_range<size_t>(0, sizeR), [&](const blocked_range<size_t>& range) { for (size_t i=range.begin(); i!=range.end(); ++i) { lp->insert(R[i], 0); //see your STL Test } }); tick_count probeTS=tick_count::now(); cout << "LinearProbingHT build:" << (sizeR/1e6)/(probeTS-buildTS).seconds() << "MT/s "; // Probe hash table and count number of hits std::atomic<uint64_t> hitCounter; hitCounter=0; parallel_for(blocked_range<size_t>(0, sizeS), [&](const blocked_range<size_t>& range) { uint64_t localHitCounter=0; for (size_t i=range.begin(); i!=range.end(); ++i) { localHitCounter += lp->lookup(S[i]); } hitCounter+=localHitCounter; }); tick_count stopTS=tick_count::now(); cout << "probe: " << (sizeS/1e6)/(stopTS-probeTS).seconds() << "MT/s " << "total: " << ((sizeR+sizeS)/1e6)/(stopTS-buildTS).seconds() << "MT/s " << "count: " << hitCounter << endl; } return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> #include <vector> #include <stdexcept> #ifdef USE_DETOURS #include "detours/detours.h" #endif #ifdef USE_MHOOK #include "mhook/mhook-lib/mhook.h" #endif #include "gl-wrappers.h" #include <DGLCommon/os.h> #ifndef _WIN32 #include "dl-intercept.h" #endif #ifdef _WIN32 #define LIBGL_NAME "opengl32.dll" #define LIBGLES1_NAME "libGLESv1_CM.dll" #define LIBGLES2_NAME "libGLESv2.dll" #define LIBEGL_NAME "libEGL.dll" #define STRIP_VERSION(X) X #elif defined(__ANDROID__) //on Android libraries are not opened by SONAME #define LIBGL_NAME "libGL.so" #define LIBGLES1_NAME "libGLESv1_CM.so" #define LIBGLES2_NAME "libGLESv2.so" #define LIBEGL_NAME "libEGL.so" #define STRIP_VERSION(X) X #else #define LIBGL_NAME "libGL.so.1" #define LIBGLES1_NAME "libGLESv1_CM.so.1" #define LIBGLES2_NAME "libGLESv2.so.1" #define LIBEGL_NAME "libEGL.so.1" #define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(".1")) #endif //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers LoadedPointer g_DirectPointers[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library}, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; APILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {} FUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) { #ifdef _WIN32 return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)); #else //(int) -> see http://www.trilithium.com/johan/2004/12/problem-with-dlsym/ return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp))); #endif } bool APILoader::loadExtPointer(Entrypoint entryp) { if (!g_DirectPointers[entryp].ptr) { if (!m_GlueLibrary) { throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded"); } FUNC_PTR ptr = NULL; switch (m_GlueLibrary) { #ifdef HAVE_LIBRARY_WGL case LIBRARY_WGL: ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); break; #endif #ifdef HAVE_LIBRARY_GLX case LIBRARY_GLX: ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)( reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp)))); break; #endif case LIBRARY_EGL: ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp))); break; default: assert(!"unknown glue library"); } g_DirectPointers[entryp].ptr = ptr; } return g_DirectPointers[entryp].ptr != NULL; } std::string APILoader::getLibraryName(ApiLibrary apiLibrary) { switch (apiLibrary) { case LIBRARY_EGL: return LIBEGL_NAME; case LIBRARY_GL: case LIBRARY_WGL: case LIBRARY_GLX: return LIBGL_NAME; case LIBRARY_ES1: return LIBGLES1_NAME; case LIBRARY_ES2: case LIBRARY_ES3: return LIBGLES2_NAME; default: assert(!"unknown library"); throw std::runtime_error("Unknown GL library name"); } } bool APILoader::isLibGL(const char* name) { std::string nameStr(name); bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos; Os::info("isLibGL(%s) == %d", name, (int) ret); return ret; } void APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) { if (entryp < NO_ENTRYPOINT) { g_DirectPointers[entryp].ptr = direct; } } void APILoader::loadLibrary(ApiLibrary apiLibrary) { Os::info("loadLibrary()"); std::string libraryName = getLibraryName(apiLibrary); Os::info("loadLibrary(%s)", libraryName.c_str()); if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) { Os::info("loadLibrary(): not loaded, yet"); std::vector<std::string> libSearchPath; LoadedLib openGLLibraryHandle = NULL; libSearchPath.push_back(""); #ifdef _WIN32 char buffer[1000]; #ifndef _WIN64 if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) { //we are running 32bit app on 64 bit windows libSearchPath.push_back(buffer + std::string("\\")); } #endif if (!openGLLibraryHandle) { if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) { //we are running on native system (32 on 32 or 64 on 64) libSearchPath.push_back(buffer + std::string("\\")); } } #ifndef _WIN64 libSearchPath.push_back("C:\\Windows\\SysWOW64\\"); #endif libSearchPath.push_back("C:\\Windows\\System32\\"); libSearchPath.push_back("."); #endif for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) { #ifdef _WIN32 openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str()); #else openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW); #endif } if (!openGLLibraryHandle) { std::string msg = std::string("Cannot load ") + libraryName + " system library"; Os::fatal(msg.c_str()); } else { m_LoadedLibraries[libraryName] = openGLLibraryHandle; } } LoadedLib library = m_LoadedLibraries[libraryName]; //we use MS Detours only on win32, on x64 mHook is used #ifdef USE_DETOURS DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #endif //g_DirectPointers is now filled with opengl32.dll pointers // we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but //application will always call us. for (int i = 0; i < Entrypoints_NUM; i++) { if (!(g_DirectPointers[i].libraryMask & apiLibrary)) { //Do not load - entrypoint does not belong to currently loaded API continue; } if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) { //Do not load - entrypoint belongs to already loaded API continue; } //this sets g_DirectPointers[i].ptr setPointer(i, loadGLPointer(library, i)); if (g_DirectPointers[i].ptr) { //this entrypoint was loaded from OpenGL32.dll, detour it! #if defined(USE_DETOURS) || defined(USE_MHOOK) FUNC_PTR * hookPtr = getWrapperPointer(i); #endif #ifdef USE_DETOURS DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr); #endif #ifdef USE_MHOOK if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) { Os::fatal("Cannot hook %s() function.", GetEntryPointName(i)); } #endif } } #ifdef USE_DETOURS DetourTransactionCommit(); #endif if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX) m_GlueLibrary = apiLibrary; m_LoadedApiLibraries |= apiLibrary; } FUNC_PTR APILoader::ensurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) { return g_DirectPointers[entryp].ptr; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } APILoader g_ApiLoader; <commit_msg>Remove some debug printfs.<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> #include <vector> #include <stdexcept> #ifdef USE_DETOURS #include "detours/detours.h" #endif #ifdef USE_MHOOK #include "mhook/mhook-lib/mhook.h" #endif #include "gl-wrappers.h" #include <DGLCommon/os.h> #ifndef _WIN32 #include "dl-intercept.h" #endif #ifdef _WIN32 #define LIBGL_NAME "opengl32.dll" #define LIBGLES1_NAME "libGLESv1_CM.dll" #define LIBGLES2_NAME "libGLESv2.dll" #define LIBEGL_NAME "libEGL.dll" #define STRIP_VERSION(X) X #elif defined(__ANDROID__) //on Android libraries are not opened by SONAME #define LIBGL_NAME "libGL.so" #define LIBGLES1_NAME "libGLESv1_CM.so" #define LIBGLES2_NAME "libGLESv2.so" #define LIBEGL_NAME "libEGL.so" #define STRIP_VERSION(X) X #else #define LIBGL_NAME "libGL.so.1" #define LIBGLES1_NAME "libGLESv1_CM.so.1" #define LIBGLES2_NAME "libGLESv2.so.1" #define LIBEGL_NAME "libEGL.so.1" #define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(".1")) #endif //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers LoadedPointer g_DirectPointers[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library}, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; APILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {} FUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) { #ifdef _WIN32 return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)); #else //(int) -> see http://www.trilithium.com/johan/2004/12/problem-with-dlsym/ return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp))); #endif } bool APILoader::loadExtPointer(Entrypoint entryp) { if (!g_DirectPointers[entryp].ptr) { if (!m_GlueLibrary) { throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded"); } FUNC_PTR ptr = NULL; switch (m_GlueLibrary) { #ifdef HAVE_LIBRARY_WGL case LIBRARY_WGL: ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); break; #endif #ifdef HAVE_LIBRARY_GLX case LIBRARY_GLX: ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)( reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp)))); break; #endif case LIBRARY_EGL: ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp))); break; default: assert(!"unknown glue library"); } g_DirectPointers[entryp].ptr = ptr; } return g_DirectPointers[entryp].ptr != NULL; } std::string APILoader::getLibraryName(ApiLibrary apiLibrary) { switch (apiLibrary) { case LIBRARY_EGL: return LIBEGL_NAME; case LIBRARY_GL: case LIBRARY_WGL: case LIBRARY_GLX: return LIBGL_NAME; case LIBRARY_ES1: return LIBGLES1_NAME; case LIBRARY_ES2: case LIBRARY_ES3: return LIBGLES2_NAME; default: assert(!"unknown library"); throw std::runtime_error("Unknown GL library name"); } } bool APILoader::isLibGL(const char* name) { std::string nameStr(name); bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos || nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos; return ret; } void APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) { if (entryp < NO_ENTRYPOINT) { g_DirectPointers[entryp].ptr = direct; } } void APILoader::loadLibrary(ApiLibrary apiLibrary) { std::string libraryName = getLibraryName(apiLibrary); if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) { std::vector<std::string> libSearchPath; LoadedLib openGLLibraryHandle = NULL; libSearchPath.push_back(""); #ifdef _WIN32 char buffer[1000]; #ifndef _WIN64 if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) { //we are running 32bit app on 64 bit windows libSearchPath.push_back(buffer + std::string("\\")); } #endif if (!openGLLibraryHandle) { if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) { //we are running on native system (32 on 32 or 64 on 64) libSearchPath.push_back(buffer + std::string("\\")); } } #ifndef _WIN64 libSearchPath.push_back("C:\\Windows\\SysWOW64\\"); #endif libSearchPath.push_back("C:\\Windows\\System32\\"); libSearchPath.push_back("."); #endif for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) { #ifdef _WIN32 openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str()); #else openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW); #endif } if (!openGLLibraryHandle) { std::string msg = std::string("Cannot load ") + libraryName + " system library"; Os::fatal(msg.c_str()); } else { m_LoadedLibraries[libraryName] = openGLLibraryHandle; } } LoadedLib library = m_LoadedLibraries[libraryName]; //we use MS Detours only on win32, on x64 mHook is used #ifdef USE_DETOURS DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #endif //g_DirectPointers is now filled with opengl32.dll pointers // we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but //application will always call us. for (int i = 0; i < Entrypoints_NUM; i++) { if (!(g_DirectPointers[i].libraryMask & apiLibrary)) { //Do not load - entrypoint does not belong to currently loaded API continue; } if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) { //Do not load - entrypoint belongs to already loaded API continue; } //this sets g_DirectPointers[i].ptr setPointer(i, loadGLPointer(library, i)); if (g_DirectPointers[i].ptr) { //this entrypoint was loaded from OpenGL32.dll, detour it! #if defined(USE_DETOURS) || defined(USE_MHOOK) FUNC_PTR * hookPtr = getWrapperPointer(i); #endif #ifdef USE_DETOURS DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr); #endif #ifdef USE_MHOOK if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) { Os::fatal("Cannot hook %s() function.", GetEntryPointName(i)); } #endif } } #ifdef USE_DETOURS DetourTransactionCommit(); #endif if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX) m_GlueLibrary = apiLibrary; m_LoadedApiLibraries |= apiLibrary; } FUNC_PTR APILoader::ensurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) { return g_DirectPointers[entryp].ptr; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } APILoader g_ApiLoader; <|endoftext|>
<commit_before>#include "AvlTree.h" #include <algorithm> #include <cassert> #include <utility> AvlNode AVLNIL = {-1, -1, &AVLNIL, &AVLNIL, &AVLNIL}; #define is_nil(e) ((e) == &AVLNIL) #define not_nil(e) ((e) != &AVLNIL) #define set_nil(e) ((e) = &AVLNIL) #define get_height(left, right) (std::max((left)->height, (right)->height) + 1) AvlNode::AvlNode() { value = -1; height = -1; set_nil(left); set_nil(right); set_nil(father); } AvlNode::AvlNode(int v, int h, AvlNode *l, AvlNode *r, AvlNode *f) { value = v; height = h; left = l; right = r; father = f; } static void Free(AvlNode *e) { if (is_nil(e)) return; Free(e->left); Free(e->right); delete e; } // left left case // right-rotate static void LL(AvlNode **e) { AvlNode *p; p = (*e)->left; (*e)->left = p->right; p->right = (*e); (*e)->height = get_height((*e)->left, (*e)->right); p->height = get_height(p->left, *e); (*e) = p; } // right right case // left-rotate static void RR(AvlNode **e) { AvlNode *p; p = (*e)->right; (*e)->right = p->left; p->left = (*e); (*e)->height = get_height((*e)->left, (*e)->right); p->height = get_height(p->right, *e); (*e) = p; } // left right case // left-rotate, right-rotate -> RR, LL static void LR(AvlNode **e) { RR(&((*e)->left)); LL(e); } // right left case // right-rotate, left-rotate -> LL, RR static void RL(AvlNode **e) { LL(&((*e)->right)); RR(e); } static AvlNode *Find(AvlNode *e, int value) { if (is_nil(e)) { return &AVLNIL; } //二分查找 if (e->value == value) { return e; } else if (e->value > value) { return Find(e->left, value); } else { return Find(e->right, value); } } static void Fix(AvlNode *e) { e->height = get_height(e->left, e->right); int factor = e->left->height - e->right->height; if (factor > 1 && e->left->value > e->value) { LL(&e); } if (factor < -1 && e->right->value < e->value) { RR(&e); } if (factor > 1 && e->left->value < e->value) { LR(&e); } if (factor < -1 && e->right->value > e->value) { RL(&e); } } static void Insert(AvlNode **e, AvlNode *father, int value) { assert(e); assert(father); if (is_nil(*e)) { // *e is nil *e = new AvlNode(); set_nil((*e)->left); set_nil((*e)->right); (*e)->father = father; (*e)->value = value; (*e)->height = get_height((*e)->left, (*e)->right); return; } //利用二分查找找到适合value插入的位置e if ((*e)->value > value) { Insert(&(*e)->left, *e, value); } else if ((*e)->value < value) { Insert(&(*e)->right, *e, value); } else { // (*e)->value == value assert((*e)->value != value); } //叶子节点处完成插入后,沿着父结点向上的每一个节点都需要检查是否满足平衡性,若不平衡则旋转 //递归函数可以对每个节点*e在插入后进行检查 Fix(*e); } static AvlNode *Next(AvlNode *e) { if (is_nil(e->right)) { return &AVLNIL; } AvlNode *next = e->right; while (not_nil(next->left)) { next = next->left; } return next; } static AvlNode *Prev(AvlNode *e) { return e->left; } void AvlTreeErase(AvlTree *t, int value) { assert(not_nil(t->root)); AvlNode *e = Find(t->root, value); assert(not_nil(e)); AvlNode *fix; set_nil(fix); if (not_nil(e->right)) { //用后继节点next代替e AvlNode *next = Next(e); e->value = next->value; if (next->father->left == next) { next->father->left = next->right; } else if (next->father->right == next) { next->father->right = next->right; } else { assert(next->father->left != next && next->father->right != next); } next->right->father = next->father; delete next; fix = e; } else if (not_nil(e->left)) { AvlNode *prev = Prev(e); e->value = prev->value; e->left = prev->left; if (not_nil(e->left)) { e->left->father = e; } e->right = prev->right; if (not_nil(e->right)) { e->right->father = e; } delete prev; fix = e; } else { //直接删除叶子节点e if (not_nil(e->father)) { if (e->father->left == e) { set_nil(e->father->left); } else if (e->father->right == e) { set_nil(e->father->right); } else { assert(e->father->left != e && e->father->right != e); } } else { set_nil(t->root); } delete e; fix = e->father; } while (not_nil(fix)) { Fix(fix); fix = fix->father; } } AvlTree *AvlTreeNew() { AvlTree *t = new AvlTree(); set_nil(t->root); return t; } void AvlTreeFree(AvlTree *t) { assert(t); Free(t->root); delete t; } void AvlTreeInsert(AvlTree *t, int value) { Insert(&(t->root), &AVLNIL, value); } AvlNode *AvlTreeFind(AvlTree *t, int value) { return Find(t->root, value); } <commit_msg>fix erase the 'fix' pointer<commit_after>#include "AvlTree.h" #include <algorithm> #include <cassert> #include <utility> AvlNode AVLNIL = {-1, -1, &AVLNIL, &AVLNIL, &AVLNIL}; #define is_nil(e) ((e) == &AVLNIL) #define not_nil(e) ((e) != &AVLNIL) #define set_nil(e) ((e) = &AVLNIL) #define get_height(left, right) (std::max((left)->height, (right)->height) + 1) AvlNode::AvlNode() { value = -1; height = -1; set_nil(left); set_nil(right); set_nil(father); } AvlNode::AvlNode(int v, int h, AvlNode *l, AvlNode *r, AvlNode *f) { value = v; height = h; left = l; right = r; father = f; } static void Free(AvlNode *e) { if (is_nil(e)) return; Free(e->left); Free(e->right); delete e; } // left left case // right-rotate static void LL(AvlNode **e) { AvlNode *p; p = (*e)->left; (*e)->left = p->right; p->right = (*e); (*e)->height = get_height((*e)->left, (*e)->right); p->height = get_height(p->left, *e); (*e) = p; } // right right case // left-rotate static void RR(AvlNode **e) { AvlNode *p; p = (*e)->right; (*e)->right = p->left; p->left = (*e); (*e)->height = get_height((*e)->left, (*e)->right); p->height = get_height(p->right, *e); (*e) = p; } // left right case // left-rotate, right-rotate -> RR, LL static void LR(AvlNode **e) { RR(&((*e)->left)); LL(e); } // right left case // right-rotate, left-rotate -> LL, RR static void RL(AvlNode **e) { LL(&((*e)->right)); RR(e); } static AvlNode *Find(AvlNode *e, int value) { if (is_nil(e)) { return &AVLNIL; } //二分查找 if (e->value == value) { return e; } else if (e->value > value) { return Find(e->left, value); } else { return Find(e->right, value); } } static void Fix(AvlNode *e) { e->height = get_height(e->left, e->right); int factor = e->left->height - e->right->height; if (factor > 1 && e->left->value > e->value) { LL(&e); } if (factor < -1 && e->right->value < e->value) { RR(&e); } if (factor > 1 && e->left->value < e->value) { LR(&e); } if (factor < -1 && e->right->value > e->value) { RL(&e); } } static void Insert(AvlNode **e, AvlNode *father, int value) { assert(e); assert(father); if (is_nil(*e)) { // *e is nil *e = new AvlNode(); set_nil((*e)->left); set_nil((*e)->right); (*e)->father = father; (*e)->value = value; (*e)->height = get_height((*e)->left, (*e)->right); return; } //利用二分查找找到适合value插入的位置e if ((*e)->value > value) { Insert(&(*e)->left, *e, value); } else if ((*e)->value < value) { Insert(&(*e)->right, *e, value); } else { // (*e)->value == value assert((*e)->value != value); } //叶子节点处完成插入后,沿着父结点向上的每一个节点都需要检查是否满足平衡性,若不平衡则旋转 //递归函数可以对每个节点*e在插入后进行检查 Fix(*e); } static AvlNode *Next(AvlNode *e) { if (is_nil(e->right)) { return &AVLNIL; } AvlNode *next = e->right; while (not_nil(next->left)) { next = next->left; } return next; } static AvlNode *Prev(AvlNode *e) { return e->left; } void AvlTreeErase(AvlTree *t, int value) { assert(not_nil(t->root)); AvlNode *e = Find(t->root, value); assert(not_nil(e)); AvlNode *fix; set_nil(fix); if (not_nil(e->right)) { //用后继节点next代替e AvlNode *next = Next(e); e->value = next->value; if (next->father->left == next) { next->father->left = next->right; } else if (next->father->right == next) { next->father->right = next->right; } else { assert(next->father->left != next && next->father->right != next); } next->right->father = next->father; delete next; fix = e; } else if (not_nil(e->left)) { AvlNode *prev = Prev(e); e->value = prev->value; e->left = prev->left; if (not_nil(e->left)) { e->left->father = e; } e->right = prev->right; if (not_nil(e->right)) { e->right->father = e; } delete prev; fix = e; } else { //直接删除叶子节点e if (not_nil(e->father)) { if (e->father->left == e) { set_nil(e->father->left); } else if (e->father->right == e) { set_nil(e->father->right); } else { assert(e->father->left != e && e->father->right != e); } } else { set_nil(t->root); } fix = e->father; delete e; } while (not_nil(fix)) { Fix(fix); fix = fix->father; } } AvlTree *AvlTreeNew() { AvlTree *t = new AvlTree(); set_nil(t->root); return t; } void AvlTreeFree(AvlTree *t) { assert(t); Free(t->root); delete t; } void AvlTreeInsert(AvlTree *t, int value) { Insert(&(t->root), &AVLNIL, value); } AvlNode *AvlTreeFind(AvlTree *t, int value) { return Find(t->root, value); } <|endoftext|>
<commit_before>#include <Dpdk/DpdkNetInterface.h> #include <Packet.h> #include <string.h> extern "C" { #include <rte_config.h> #include <rte_common.h> #include <rte_eal.h> #include <rte_mbuf.h> #include <rte_ethdev.h> } namespace nshdev { constexpr size_t MAX_PKT_BURST = 32; struct EtherOriginInfo: public OriginInfo { struct rte_mbuf *mbuf; struct ether_hdr hdr; }; PacketRef MbufToPacketRef(struct rte_mbuf& mbuf, struct EtherOriginInfo& info) { struct ether_hdr *ether = rte_pktmbuf_mtod(&mbuf, struct ether_hdr *); info.mbuf = &mbuf; memcpy(&info.hdr, ether, sizeof(struct ether_hdr)); char *adjPkt = rte_pktmbuf_adj(&mbuf, sizeof(struct ether_hdr)); return PacketRef(reinterpret_cast<uint8_t*>(adjPkt), rte_pktmbuf_pkt_len(&mbuf), &info); } DpdkNetInterface::DpdkNetInterface(uint8_t portId): m_portId(portId) { } int DpdkNetInterface::GetWaitFD() const { // do not wait -- poll via run return -1; } void DpdkNetInterface::Run() { struct rte_mbuf *pkts_burst[MAX_PKT_BURST]; uint32_t numPackets = rte_eth_rx_burst(m_portId, m_rxQueueId, pkts_burst, MAX_PKT_BURST); EtherOriginInfo info; for(uint32_t i=0; i < numPackets; ++i) { PacketRef ref = MbufToPacketRef(*pkts_burst[i], info); // this will fail if we couldn't prepend if(ref.Data() != nullptr) { Forward(ref); } else { m_failedMbufCreations++; } } } void DpdkNetInterface::ReturnToSender(PacketRef& packetRef) { const EtherOriginInfo &info = static_cast<const EtherOriginInfo&>(*packetRef.From()); struct rte_mbuf *toSend = info.mbuf; // add on an ethernet header and swap the cached addresses char *pkt = rte_pktmbuf_prepend(toSend, sizeof(struct ether_hdr)); if(pkt == 0) { // Sadness. No room. :( m_numFailedPrepend++; rte_pktmbuf_free(toSend); return; } struct ether_hdr &toSendHdr = reinterpret_cast<struct ether_hdr&>(*pkt); ether_addr_copy(&info.hdr.s_addr, &toSendHdr.d_addr); ether_addr_copy(&info.hdr.d_addr, &toSendHdr.s_addr); toSendHdr.ether_type = info.hdr.ether_type; // Sending one at a time is not the most efficient, but without changes to // how things are scheduled, it's all we can do. uint16_t numTx = rte_eth_tx_burst(m_portId, m_txQueueId, &toSend, 1); if(numTx < 1) { // Full! How dare you! m_numOutDiscards++; rte_pktmbuf_free(info.mbuf); return; } } } <commit_msg>Make dpdk run loop run as long as it has packets<commit_after>#include <Dpdk/DpdkNetInterface.h> #include <Packet.h> #include <string.h> extern "C" { #include <rte_config.h> #include <rte_common.h> #include <rte_eal.h> #include <rte_mbuf.h> #include <rte_ethdev.h> } namespace nshdev { constexpr size_t MAX_PKT_BURST = 32; struct EtherOriginInfo: public OriginInfo { struct rte_mbuf *mbuf; struct ether_hdr hdr; }; PacketRef MbufToPacketRef(struct rte_mbuf& mbuf, struct EtherOriginInfo& info) { struct ether_hdr *ether = rte_pktmbuf_mtod(&mbuf, struct ether_hdr *); info.mbuf = &mbuf; memcpy(&info.hdr, ether, sizeof(struct ether_hdr)); char *adjPkt = rte_pktmbuf_adj(&mbuf, sizeof(struct ether_hdr)); return PacketRef(reinterpret_cast<uint8_t*>(adjPkt), rte_pktmbuf_pkt_len(&mbuf), &info); } DpdkNetInterface::DpdkNetInterface(uint8_t portId): m_portId(portId) { } int DpdkNetInterface::GetWaitFD() const { // do not wait -- poll via run return -1; } void DpdkNetInterface::Run() { struct rte_mbuf *pkts_burst[MAX_PKT_BURST]; uint32_t numPackets = 0; do { numPackets = rte_eth_rx_burst(m_portId, m_rxQueueId, pkts_burst, MAX_PKT_BURST); EtherOriginInfo info; for(uint32_t i=0; i < numPackets; ++i) { PacketRef ref = MbufToPacketRef(*pkts_burst[i], info); // this will fail if we couldn't prepend if(ref.Data() != nullptr) { Forward(ref); } else { m_failedMbufCreations++; } } } while (numPackets > 0); } void DpdkNetInterface::ReturnToSender(PacketRef& packetRef) { const EtherOriginInfo &info = static_cast<const EtherOriginInfo&>(*packetRef.From()); struct rte_mbuf *toSend = info.mbuf; // add on an ethernet header and swap the cached addresses char *pkt = rte_pktmbuf_prepend(toSend, sizeof(struct ether_hdr)); if(pkt == 0) { // Sadness. No room. :( m_numFailedPrepend++; rte_pktmbuf_free(toSend); return; } struct ether_hdr &toSendHdr = reinterpret_cast<struct ether_hdr&>(*pkt); ether_addr_copy(&info.hdr.s_addr, &toSendHdr.d_addr); ether_addr_copy(&info.hdr.d_addr, &toSendHdr.s_addr); toSendHdr.ether_type = info.hdr.ether_type; // Sending one at a time is not the most efficient, but without changes to // how things are scheduled, it's all we can do. uint16_t numTx = rte_eth_tx_burst(m_portId, m_txQueueId, &toSend, 1); if(numTx < 1) { // Full! How dare you! m_numOutDiscards++; rte_pktmbuf_free(info.mbuf); return; } } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Jürgen Riegel (juergen.riegel@web.de) 2002 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <iostream> # include <iterator> #include <Precision.hxx> #include <cmath> #endif #include <Base/Exception.h> #include <Base/Console.h> #include <Base/FileInfo.h> #include <Base/Parameter.h> #include <Base/UnitsApi.h> #include <App/Application.h> #include <App/Document.h> #include <boost/regex.hpp> #include "DrawPage.h" #include "DrawView.h" #include "DrawProjGroup.h" #include "DrawViewClip.h" #include "DrawTemplate.h" #include "DrawViewCollection.h" #include "DrawViewPart.h" #include "DrawViewDimension.h" #include <Mod/TechDraw/App/DrawPagePy.h> // generated from DrawPagePy.xml using namespace TechDraw; using namespace std; //=========================================================================== // DrawPage //=========================================================================== App::PropertyFloatConstraint::Constraints DrawPage::scaleRange = {Precision::Confusion(), std::numeric_limits<double>::max(), pow(10,- Base::UnitsApi::getDecimals())}; PROPERTY_SOURCE(TechDraw::DrawPage, App::DocumentObject) const char* DrawPage::ProjectionTypeEnums[] = { "First Angle", "Third Angle", NULL }; DrawPage::DrawPage(void) { static const char *group = "Page"; nowDeleting = false; ADD_PROPERTY_TYPE(Template, (0), group, (App::PropertyType)(App::Prop_None), "Attached Template"); ADD_PROPERTY_TYPE(Views, (0), group, (App::PropertyType)(App::Prop_None), "Attached Views"); // Projection Properties ProjectionType.setEnums(ProjectionTypeEnums); Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); // In preferences, 0 -> First Angle 1 -> Third Angle int projType = hGrp->GetInt("ProjectionAngle", -1); if (projType == -1) { ADD_PROPERTY(ProjectionType, ((long)0)); // Default to first angle } else { ADD_PROPERTY(ProjectionType, ((long)projType)); } ADD_PROPERTY_TYPE(Scale, (1.0), group, App::Prop_None, "Scale factor for this Page"); Scale.setConstraints(&scaleRange); } DrawPage::~DrawPage() { } void DrawPage::onBeforeChange(const App::Property* prop) { App::DocumentObject::onBeforeChange(prop); } void DrawPage::onChanged(const App::Property* prop) { if (prop == &Template) { if (!isRestoring() && !isDeleting()) { //TODO: reload if Template prop changes (ie different Template) } } else if (prop == &Views) { if (!isRestoring() && !isDeleting() ) { //TODO: reload if Views prop changes (ie adds/deletes) } } else if(prop == &Scale) { // touch all views in the Page as they may be dependent on this scale const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawView *view = dynamic_cast<TechDraw::DrawView *>(*it); if (view != NULL && view->ScaleType.isValue("Page")) { view->Scale.touch(); } } } else if (prop == &ProjectionType) { // touch all ortho views in the Page as they may be dependent on Projection Type const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawProjGroup *view = dynamic_cast<TechDraw::DrawProjGroup *>(*it); if (view != NULL && view->ProjectionType.isValue("Default")) { view->ProjectionType.touch(); } } // TODO: Also update Template graphic. } App::DocumentObject::onChanged(prop); //<<<< } App::DocumentObjectExecReturn *DrawPage::execute(void) { //Page is just a property storage area? no real logic involved? //all this does is trigger onChanged in this and ViewProviderPage Template.touch(); Views.touch(); return App::DocumentObject::StdReturn; } short DrawPage::mustExecute() const { if(Scale.isTouched()) return 1; // Check the value of template if this has been modified App::DocumentObject* tmpl = Template.getValue(); if(tmpl && tmpl->isTouched()) return 1; // Check if within this Page, any Views have been touched // Why does Page have to execute if a View changes? const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { if((*it)->isTouched()) { return 1; } } return App::DocumentObject::mustExecute(); } PyObject *DrawPage::getPyObject(void) { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 PythonObject = Py::Object(new DrawPagePy(this),true); } return Py::new_reference_to(PythonObject); } bool DrawPage::hasValidTemplate() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if(obj && obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); if (templ->getWidth() > 0. && templ->getHeight() > 0.) { return true; } } return false; } double DrawPage::getPageWidth() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if( obj && obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId()) ) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->getWidth(); } throw Base::Exception("Template not set for Page"); } double DrawPage::getPageHeight() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if(obj) { if(obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->getHeight(); } } throw Base::Exception("Template not set for Page"); } const char * DrawPage::getPageOrientation() const { App::DocumentObject *obj; obj = Template.getValue(); if(obj) { if(obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->Orientation.getValueAsString(); } } throw Base::Exception("Template not set for Page"); } int DrawPage::addView(App::DocumentObject *docObj) { if(!docObj->isDerivedFrom(TechDraw::DrawView::getClassTypeId())) return -1; DrawView* view = static_cast<DrawView*>(docObj); //position all new views in center of Page (exceptDVDimension) if (!docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())) { view->X.setValue(getPageWidth()/2.0); view->Y.setValue(getPageHeight()/2.0); } //add view to list const std::vector<App::DocumentObject *> currViews = Views.getValues(); std::vector<App::DocumentObject *> newViews(currViews); newViews.push_back(docObj); Views.setValues(newViews); //check if View fits on Page if ( !view->checkFit(this) ) { Base::Console().Warning("%s is larger than page. Will be scaled.\n",view->getNameInDocument()); view->ScaleType.setValue("Automatic"); } return Views.getSize(); } int DrawPage::removeView(App::DocumentObject *docObj) { if(!docObj->isDerivedFrom(TechDraw::DrawView::getClassTypeId())) return -1; const std::vector<App::DocumentObject*> currViews = Views.getValues(); std::vector<App::DocumentObject*> newViews; std::vector<App::DocumentObject*>::const_iterator it = currViews.begin(); for (; it != currViews.end(); it++) { std::string viewName = docObj->getNameInDocument(); if (viewName.compare((*it)->getNameInDocument()) != 0) { newViews.push_back((*it)); } } Views.setValues(newViews); return Views.getSize(); } void DrawPage::onDocumentRestored() { std::vector<App::DocumentObject*> featViews = Views.getValues(); std::vector<App::DocumentObject*>::const_iterator it = featViews.begin(); //first, make sure all the Parts have been executed so GeometryObjects exist for(; it != featViews.end(); ++it) { TechDraw::DrawViewPart *part = dynamic_cast<TechDraw::DrawViewPart *>(*it); if (part != nullptr && !part->hasGeometry()) { part->execute(); // std::vector<App::DocumentObject*> parent = part->getInList(); // for (auto& p: parent) { // p->touch(); // } } } //second, make sure all the Dimensions have been executed so Measurements have References for(it = featViews.begin(); it != featViews.end(); ++it) { TechDraw::DrawViewDimension *dim = dynamic_cast<TechDraw::DrawViewDimension *>(*it); if (dim != nullptr && !dim->has2DReferences()) { dim->execute(); } } recompute(); App::DocumentObject::onDocumentRestored(); } void DrawPage::unsetupObject() { nowDeleting = true; // Remove the Page's views & template from document App::Document* doc = getDocument(); std::string docName = doc->getName(); const std::vector<App::DocumentObject*> currViews = Views.getValues(); std::vector<App::DocumentObject*> emptyViews; std::vector<App::DocumentObject*>::const_iterator it = currViews.begin(); for (; it != currViews.end(); it++) { std::string viewName = (*it)->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", docName.c_str(), viewName.c_str()); } Views.setValues(emptyViews); //no template crash here?? if Template.getValue is null or invalid, this will fail. std::string templateName = Template.getValue()->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", docName.c_str(), templateName.c_str()); Template.setValue(nullptr); } void DrawPage::Restore(Base::XMLReader &reader) { reader.readElement("Properties"); int Cnt = reader.getAttributeAsInteger("Count"); for (int i=0 ;i<Cnt ;i++) { reader.readElement("Property"); const char* PropName = reader.getAttribute("name"); const char* TypeName = reader.getAttribute("type"); App::Property* schemaProp = getPropertyByName(PropName); try { if(schemaProp){ if (strcmp(schemaProp->getTypeId().getName(), TypeName) == 0){ //if the property type in obj == type in schema schemaProp->Restore(reader); //nothing special to do } else { if (strcmp(PropName, "Scale") == 0) { if (schemaProp->isDerivedFrom(App::PropertyFloatConstraint::getClassTypeId())){ //right property type schemaProp->Restore(reader); //nothing special to do } else { //Scale, but not PropertyFloatConstraint App::PropertyFloat tmp; if (strcmp(tmp.getTypeId().getName(),TypeName)) { //property in file is Float tmp.setContainer(this); tmp.Restore(reader); double tmpValue = tmp.getValue(); if (tmpValue > 0.0) { static_cast<App::PropertyFloatConstraint*>(schemaProp)->setValue(tmpValue); } else { static_cast<App::PropertyFloatConstraint*>(schemaProp)->setValue(1.0); } } else { // has Scale prop that isn't Float! Base::Console().Log("DrawPage::Restore - old Document Scale is Not Float!\n"); // no idea } } } else { Base::Console().Log("DrawPage::Restore - old Document has unknown Property\n"); } } } } catch (const Base::XMLParseException&) { throw; // re-throw } catch (const Base::Exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const std::exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const char* e) { Base::Console().Error("%s\n", e); } #ifndef FC_DEBUG catch (...) { Base::Console().Error("PropertyContainer::Restore: Unknown C++ exception thrown"); } #endif reader.readEndElement("Property"); } reader.readEndElement("Properties"); } <commit_msg>Fix 2884 crash on page delete<commit_after>/*************************************************************************** * Copyright (c) Jürgen Riegel (juergen.riegel@web.de) 2002 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <iostream> # include <iterator> #include <Precision.hxx> #include <cmath> #endif #include <Base/Exception.h> #include <Base/Console.h> #include <Base/FileInfo.h> #include <Base/Parameter.h> #include <Base/UnitsApi.h> #include <App/Application.h> #include <App/Document.h> #include <boost/regex.hpp> #include "DrawPage.h" #include "DrawView.h" #include "DrawProjGroup.h" #include "DrawViewClip.h" #include "DrawTemplate.h" #include "DrawViewCollection.h" #include "DrawViewPart.h" #include "DrawViewDimension.h" #include <Mod/TechDraw/App/DrawPagePy.h> // generated from DrawPagePy.xml using namespace TechDraw; using namespace std; //=========================================================================== // DrawPage //=========================================================================== App::PropertyFloatConstraint::Constraints DrawPage::scaleRange = {Precision::Confusion(), std::numeric_limits<double>::max(), pow(10,- Base::UnitsApi::getDecimals())}; PROPERTY_SOURCE(TechDraw::DrawPage, App::DocumentObject) const char* DrawPage::ProjectionTypeEnums[] = { "First Angle", "Third Angle", NULL }; DrawPage::DrawPage(void) { static const char *group = "Page"; nowDeleting = false; ADD_PROPERTY_TYPE(Template, (0), group, (App::PropertyType)(App::Prop_None), "Attached Template"); ADD_PROPERTY_TYPE(Views, (0), group, (App::PropertyType)(App::Prop_None), "Attached Views"); // Projection Properties ProjectionType.setEnums(ProjectionTypeEnums); Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); // In preferences, 0 -> First Angle 1 -> Third Angle int projType = hGrp->GetInt("ProjectionAngle", -1); if (projType == -1) { ADD_PROPERTY(ProjectionType, ((long)0)); // Default to first angle } else { ADD_PROPERTY(ProjectionType, ((long)projType)); } ADD_PROPERTY_TYPE(Scale, (1.0), group, App::Prop_None, "Scale factor for this Page"); Scale.setConstraints(&scaleRange); } DrawPage::~DrawPage() { } void DrawPage::onBeforeChange(const App::Property* prop) { App::DocumentObject::onBeforeChange(prop); } void DrawPage::onChanged(const App::Property* prop) { if (prop == &Template) { if (!isRestoring() && !isDeleting()) { //TODO: reload if Template prop changes (ie different Template) } } else if (prop == &Views) { if (!isRestoring() && !isDeleting() ) { //TODO: reload if Views prop changes (ie adds/deletes) } } else if(prop == &Scale) { // touch all views in the Page as they may be dependent on this scale const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawView *view = dynamic_cast<TechDraw::DrawView *>(*it); if (view != NULL && view->ScaleType.isValue("Page")) { view->Scale.touch(); } } } else if (prop == &ProjectionType) { // touch all ortho views in the Page as they may be dependent on Projection Type const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawProjGroup *view = dynamic_cast<TechDraw::DrawProjGroup *>(*it); if (view != NULL && view->ProjectionType.isValue("Default")) { view->ProjectionType.touch(); } } // TODO: Also update Template graphic. } App::DocumentObject::onChanged(prop); //<<<< } App::DocumentObjectExecReturn *DrawPage::execute(void) { //Page is just a property storage area? no real logic involved? //all this does is trigger onChanged in this and ViewProviderPage Template.touch(); Views.touch(); return App::DocumentObject::StdReturn; } short DrawPage::mustExecute() const { if(Scale.isTouched()) return 1; // Check the value of template if this has been modified App::DocumentObject* tmpl = Template.getValue(); if(tmpl && tmpl->isTouched()) return 1; // Check if within this Page, any Views have been touched // Why does Page have to execute if a View changes? const std::vector<App::DocumentObject*> &vals = Views.getValues(); for(std::vector<App::DocumentObject *>::const_iterator it = vals.begin(); it < vals.end(); ++it) { if((*it)->isTouched()) { return 1; } } return App::DocumentObject::mustExecute(); } PyObject *DrawPage::getPyObject(void) { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 PythonObject = Py::Object(new DrawPagePy(this),true); } return Py::new_reference_to(PythonObject); } bool DrawPage::hasValidTemplate() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if(obj && obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); if (templ->getWidth() > 0. && templ->getHeight() > 0.) { return true; } } return false; } double DrawPage::getPageWidth() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if( obj && obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId()) ) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->getWidth(); } throw Base::Exception("Template not set for Page"); } double DrawPage::getPageHeight() const { App::DocumentObject *obj = 0; obj = Template.getValue(); if(obj) { if(obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->getHeight(); } } throw Base::Exception("Template not set for Page"); } const char * DrawPage::getPageOrientation() const { App::DocumentObject *obj; obj = Template.getValue(); if(obj) { if(obj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) { TechDraw::DrawTemplate *templ = static_cast<TechDraw::DrawTemplate *>(obj); return templ->Orientation.getValueAsString(); } } throw Base::Exception("Template not set for Page"); } int DrawPage::addView(App::DocumentObject *docObj) { if(!docObj->isDerivedFrom(TechDraw::DrawView::getClassTypeId())) return -1; DrawView* view = static_cast<DrawView*>(docObj); //position all new views in center of Page (exceptDVDimension) if (!docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())) { view->X.setValue(getPageWidth()/2.0); view->Y.setValue(getPageHeight()/2.0); } //add view to list const std::vector<App::DocumentObject *> currViews = Views.getValues(); std::vector<App::DocumentObject *> newViews(currViews); newViews.push_back(docObj); Views.setValues(newViews); //check if View fits on Page if ( !view->checkFit(this) ) { Base::Console().Warning("%s is larger than page. Will be scaled.\n",view->getNameInDocument()); view->ScaleType.setValue("Automatic"); } return Views.getSize(); } int DrawPage::removeView(App::DocumentObject *docObj) { if(!docObj->isDerivedFrom(TechDraw::DrawView::getClassTypeId())) return -1; const std::vector<App::DocumentObject*> currViews = Views.getValues(); std::vector<App::DocumentObject*> newViews; std::vector<App::DocumentObject*>::const_iterator it = currViews.begin(); for (; it != currViews.end(); it++) { std::string viewName = docObj->getNameInDocument(); if (viewName.compare((*it)->getNameInDocument()) != 0) { newViews.push_back((*it)); } } Views.setValues(newViews); return Views.getSize(); } void DrawPage::onDocumentRestored() { std::vector<App::DocumentObject*> featViews = Views.getValues(); std::vector<App::DocumentObject*>::const_iterator it = featViews.begin(); //first, make sure all the Parts have been executed so GeometryObjects exist for(; it != featViews.end(); ++it) { TechDraw::DrawViewPart *part = dynamic_cast<TechDraw::DrawViewPart *>(*it); if (part != nullptr && !part->hasGeometry()) { part->execute(); // std::vector<App::DocumentObject*> parent = part->getInList(); // for (auto& p: parent) { // p->touch(); // } } } //second, make sure all the Dimensions have been executed so Measurements have References for(it = featViews.begin(); it != featViews.end(); ++it) { TechDraw::DrawViewDimension *dim = dynamic_cast<TechDraw::DrawViewDimension *>(*it); if (dim != nullptr && !dim->has2DReferences()) { dim->execute(); } } recompute(); App::DocumentObject::onDocumentRestored(); } void DrawPage::unsetupObject() { nowDeleting = true; // Remove the Page's views & template from document App::Document* doc = getDocument(); std::string docName = doc->getName(); const std::vector<App::DocumentObject*> currViews = Views.getValues(); std::vector<App::DocumentObject*> emptyViews; std::vector<App::DocumentObject*>::const_iterator it = currViews.begin(); for (; it != currViews.end(); it++) { std::string viewName = (*it)->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", docName.c_str(), viewName.c_str()); } Views.setValues(emptyViews); App::DocumentObject* tmp = Template.getValue(); if (tmp != nullptr) { std::string templateName = Template.getValue()->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", docName.c_str(), templateName.c_str()); } Template.setValue(nullptr); } void DrawPage::Restore(Base::XMLReader &reader) { reader.readElement("Properties"); int Cnt = reader.getAttributeAsInteger("Count"); for (int i=0 ;i<Cnt ;i++) { reader.readElement("Property"); const char* PropName = reader.getAttribute("name"); const char* TypeName = reader.getAttribute("type"); App::Property* schemaProp = getPropertyByName(PropName); try { if(schemaProp){ if (strcmp(schemaProp->getTypeId().getName(), TypeName) == 0){ //if the property type in obj == type in schema schemaProp->Restore(reader); //nothing special to do } else { if (strcmp(PropName, "Scale") == 0) { if (schemaProp->isDerivedFrom(App::PropertyFloatConstraint::getClassTypeId())){ //right property type schemaProp->Restore(reader); //nothing special to do } else { //Scale, but not PropertyFloatConstraint App::PropertyFloat tmp; if (strcmp(tmp.getTypeId().getName(),TypeName)) { //property in file is Float tmp.setContainer(this); tmp.Restore(reader); double tmpValue = tmp.getValue(); if (tmpValue > 0.0) { static_cast<App::PropertyFloatConstraint*>(schemaProp)->setValue(tmpValue); } else { static_cast<App::PropertyFloatConstraint*>(schemaProp)->setValue(1.0); } } else { // has Scale prop that isn't Float! Base::Console().Log("DrawPage::Restore - old Document Scale is Not Float!\n"); // no idea } } } else { Base::Console().Log("DrawPage::Restore - old Document has unknown Property\n"); } } } } catch (const Base::XMLParseException&) { throw; // re-throw } catch (const Base::Exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const std::exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const char* e) { Base::Console().Error("%s\n", e); } #ifndef FC_DEBUG catch (...) { Base::Console().Error("PropertyContainer::Restore: Unknown C++ exception thrown"); } #endif reader.readEndElement("Property"); } reader.readEndElement("Properties"); } <|endoftext|>
<commit_before> /*************************************************************************** * Copyright (c) 2015 WandererFan <wandererfan@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <cstring> # include <cstdlib> # include <exception> # include <boost/regex.hpp> # include <QString> # include <QStringList> # include <QRegExp> #include <QChar> #include <BRep_Tool.hxx> #include <gp_Pnt.hxx> #include <Precision.hxx> #include <BRepLProp_CLProps.hxx> #include <TopExp_Explorer.hxx> #include <BRepAdaptor_Curve.hxx> #include <BRepLProp_CurveTool.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <BRepGProp.hxx> #include <GProp_GProps.hxx> #endif #include <App/Application.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Parameter.h> #include "DrawUtil.h" using namespace TechDraw; /*static*/ int DrawUtil::getIndexFromName(std::string geomName) { boost::regex re("\\d+$"); // one of more digits at end of string boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; char* endChar; std::string::const_iterator begin = geomName.begin(); std::string::const_iterator end = geomName.end(); std::stringstream ErrorMsg; if (!geomName.empty()) { if (boost::regex_search(begin, end, what, re, flags)) { return int (std::strtol(what.str().c_str(), &endChar, 10)); //TODO: use std::stoi() in c++11 } else { ErrorMsg << "getIndexFromName: malformed geometry name - " << geomName; throw Base::Exception(ErrorMsg.str()); } } else { throw Base::Exception("getIndexFromName - empty geometry name"); } } std::string DrawUtil::getGeomTypeFromName(std::string geomName) { boost::regex re("^[a-zA-Z]*"); //one or more letters at start of string boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; std::string::const_iterator begin = geomName.begin(); std::string::const_iterator end = geomName.end(); std::stringstream ErrorMsg; if (!geomName.empty()) { if (boost::regex_search(begin, end, what, re, flags)) { return what.str(); //TODO: use std::stoi() in c++11 } else { ErrorMsg << "In getGeomTypeFromName: malformed geometry name - " << geomName; throw Base::Exception(ErrorMsg.str()); } } else { throw Base::Exception("getGeomTypeFromName - empty geometry name"); } } std::string DrawUtil::makeGeomName(std::string geomType, int index) { std::stringstream newName; newName << geomType << index; return newName.str(); } bool DrawUtil::isSamePoint(TopoDS_Vertex v1, TopoDS_Vertex v2) { bool result = false; gp_Pnt p1 = BRep_Tool::Pnt(v1); gp_Pnt p2 = BRep_Tool::Pnt(v2); if (p1.IsEqual(p2,Precision::Confusion())) { result = true; } return result; } bool DrawUtil::isZeroEdge(TopoDS_Edge e) { TopoDS_Vertex vStart = TopExp::FirstVertex(e); TopoDS_Vertex vEnd = TopExp::LastVertex(e); bool result = isSamePoint(vStart,vEnd); if (result) { //closed edge will have same V's but non-zero length GProp_GProps props; BRepGProp::LinearProperties(e, props); double len = props.Mass(); if (len > Precision::Confusion()) { result = false; } } return result; } //based on Function provided by Joe Dowsett, 2014 double DrawUtil::sensibleScale(double working_scale) { double result = 1.0; //which gives the largest scale for which the min_space requirements can be met, but we want a 'sensible' scale, rather than 0.28457239... //eg if working_scale = 0.115, then we want to use 0.1, similarly 7.65 -> 5, and 76.5 -> 50 float exponent = std::floor(std::log10(working_scale)); //if working_scale = a * 10^b, what is b? working_scale *= std::pow(10, -exponent); //now find what 'a' is. //int choices = 10; float valid_scales[2][10] = {{1.0, 1.25, 2.0, 2.5, 3.75, 5.0, 7.5, 10.0, 50.0, 100.0}, //equate to 1:10, 1:8, 1:5, 1:4, 3:8, 1:2, 3:4, 1:1 // .1 .125 .375 .75 {1.0, 1.5 , 2.0, 3.0, 4.0 , 5.0, 8.0, 10.0, 50.0, 100.0}}; //equate to 1:1, 3:2, 2:1, 3:1, 4:1, 5:1, 8:1, 10:1 // 1.5:1 //int i = choices - 1; int i = 9; while (valid_scales[(exponent >= 0)][i] > working_scale) //choose closest value smaller than 'a' from list. i -= 1; //choosing top list if exponent -ve, bottom list for +ve exponent //now have the appropriate scale, reapply the *10^b result = valid_scales[(exponent >= 0)][i] * pow(10, exponent); return result; } //============================ // various debugging routines. void DrawUtil::dumpVertexes(const char* text, const TopoDS_Shape& s) { Base::Console().Message("DUMP - %s\n",text); TopExp_Explorer expl(s, TopAbs_VERTEX); int i; for (i = 1 ; expl.More(); expl.Next(),i++) { const TopoDS_Vertex& v = TopoDS::Vertex(expl.Current()); gp_Pnt pnt = BRep_Tool::Pnt(v); Base::Console().Message("v%d: (%.3f,%.3f,%.3f)\n",i,pnt.X(),pnt.Y(),pnt.Z()); } } void DrawUtil::countFaces(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(s, TopAbs_FACE, mapOfFaces); int num = mapOfFaces.Extent(); Base::Console().Message("COUNT - %s has %d Faces\n",text,num); } //count # of unique Wires in shape. void DrawUtil::countWires(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(s, TopAbs_WIRE, mapOfWires); int num = mapOfWires.Extent(); Base::Console().Message("COUNT - %s has %d wires\n",text,num); } void DrawUtil::countEdges(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfEdges; TopExp::MapShapes(s, TopAbs_EDGE, mapOfEdges); int num = mapOfEdges.Extent(); Base::Console().Message("COUNT - %s has %d edges\n",text,num); } void DrawUtil::dump1Vertex(const char* text, const TopoDS_Vertex& v) { Base::Console().Message("DUMP - dump1Vertex - %s\n",text); gp_Pnt pnt = BRep_Tool::Pnt(v); Base::Console().Message("%s: (%.3f,%.3f,%.3f)\n",text,pnt.X(),pnt.Y(),pnt.Z()); } void DrawUtil::dumpEdge(char* label, int i, TopoDS_Edge e) { BRepAdaptor_Curve adapt(e); double start = BRepLProp_CurveTool::FirstParameter(adapt); double end = BRepLProp_CurveTool::LastParameter(adapt); BRepLProp_CLProps propStart(adapt,start,0,Precision::Confusion()); const gp_Pnt& vStart = propStart.Value(); BRepLProp_CLProps propEnd(adapt,end,0,Precision::Confusion()); const gp_Pnt& vEnd = propEnd.Value(); //Base::Console().Message("%s edge:%d start:(%.3f,%.3f,%.3f)/%0.3f end:(%.2f,%.3f,%.3f)/%.3f\n",label,i, // vStart.X(),vStart.Y(),vStart.Z(),start,vEnd.X(),vEnd.Y(),vEnd.Z(),end); Base::Console().Message("%s edge:%d start:(%.3f,%.3f,%.3f) end:(%.2f,%.3f,%.3f)\n",label,i, vStart.X(),vStart.Y(),vStart.Z(),vEnd.X(),vEnd.Y(),vEnd.Z()); } const char* DrawUtil::printBool(bool b) { return (b ? "True" : "False"); } QString DrawUtil::qbaToDebug(const QByteArray & line) { QString s; uchar c; for ( int i=0 ; i < line.size() ; i++ ){ c = line[i]; if ( c >= 0x20 and c <= 126 ) { s.append(QChar::fromLatin1(c)); } else { s.append(QString::fromUtf8("<%1>").arg(c, 2, 16, QChar::fromLatin1('0'))); } } return s; } //================================== <commit_msg>MSVC syntax fix<commit_after> /*************************************************************************** * Copyright (c) 2015 WandererFan <wandererfan@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <cstring> # include <cstdlib> # include <exception> # include <boost/regex.hpp> # include <QString> # include <QStringList> # include <QRegExp> #include <QChar> #include <BRep_Tool.hxx> #include <gp_Pnt.hxx> #include <Precision.hxx> #include <BRepLProp_CLProps.hxx> #include <TopExp_Explorer.hxx> #include <BRepAdaptor_Curve.hxx> #include <BRepLProp_CurveTool.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <BRepGProp.hxx> #include <GProp_GProps.hxx> #endif #include <App/Application.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Parameter.h> #include "DrawUtil.h" using namespace TechDraw; /*static*/ int DrawUtil::getIndexFromName(std::string geomName) { boost::regex re("\\d+$"); // one of more digits at end of string boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; char* endChar; std::string::const_iterator begin = geomName.begin(); std::string::const_iterator end = geomName.end(); std::stringstream ErrorMsg; if (!geomName.empty()) { if (boost::regex_search(begin, end, what, re, flags)) { return int (std::strtol(what.str().c_str(), &endChar, 10)); //TODO: use std::stoi() in c++11 } else { ErrorMsg << "getIndexFromName: malformed geometry name - " << geomName; throw Base::Exception(ErrorMsg.str()); } } else { throw Base::Exception("getIndexFromName - empty geometry name"); } } std::string DrawUtil::getGeomTypeFromName(std::string geomName) { boost::regex re("^[a-zA-Z]*"); //one or more letters at start of string boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; std::string::const_iterator begin = geomName.begin(); std::string::const_iterator end = geomName.end(); std::stringstream ErrorMsg; if (!geomName.empty()) { if (boost::regex_search(begin, end, what, re, flags)) { return what.str(); //TODO: use std::stoi() in c++11 } else { ErrorMsg << "In getGeomTypeFromName: malformed geometry name - " << geomName; throw Base::Exception(ErrorMsg.str()); } } else { throw Base::Exception("getGeomTypeFromName - empty geometry name"); } } std::string DrawUtil::makeGeomName(std::string geomType, int index) { std::stringstream newName; newName << geomType << index; return newName.str(); } bool DrawUtil::isSamePoint(TopoDS_Vertex v1, TopoDS_Vertex v2) { bool result = false; gp_Pnt p1 = BRep_Tool::Pnt(v1); gp_Pnt p2 = BRep_Tool::Pnt(v2); if (p1.IsEqual(p2,Precision::Confusion())) { result = true; } return result; } bool DrawUtil::isZeroEdge(TopoDS_Edge e) { TopoDS_Vertex vStart = TopExp::FirstVertex(e); TopoDS_Vertex vEnd = TopExp::LastVertex(e); bool result = isSamePoint(vStart,vEnd); if (result) { //closed edge will have same V's but non-zero length GProp_GProps props; BRepGProp::LinearProperties(e, props); double len = props.Mass(); if (len > Precision::Confusion()) { result = false; } } return result; } //based on Function provided by Joe Dowsett, 2014 double DrawUtil::sensibleScale(double working_scale) { double result = 1.0; //which gives the largest scale for which the min_space requirements can be met, but we want a 'sensible' scale, rather than 0.28457239... //eg if working_scale = 0.115, then we want to use 0.1, similarly 7.65 -> 5, and 76.5 -> 50 float exponent = std::floor(std::log10(working_scale)); //if working_scale = a * 10^b, what is b? working_scale *= std::pow(10, -exponent); //now find what 'a' is. //int choices = 10; float valid_scales[2][10] = {{1.0, 1.25, 2.0, 2.5, 3.75, 5.0, 7.5, 10.0, 50.0, 100.0}, //equate to 1:10, 1:8, 1:5, 1:4, 3:8, 1:2, 3:4, 1:1 // .1 .125 .375 .75 {1.0, 1.5 , 2.0, 3.0, 4.0 , 5.0, 8.0, 10.0, 50.0, 100.0}}; //equate to 1:1, 3:2, 2:1, 3:1, 4:1, 5:1, 8:1, 10:1 // 1.5:1 //int i = choices - 1; int i = 9; while (valid_scales[(exponent >= 0)][i] > working_scale) //choose closest value smaller than 'a' from list. i -= 1; //choosing top list if exponent -ve, bottom list for +ve exponent //now have the appropriate scale, reapply the *10^b result = valid_scales[(exponent >= 0)][i] * pow(10, exponent); return result; } //============================ // various debugging routines. void DrawUtil::dumpVertexes(const char* text, const TopoDS_Shape& s) { Base::Console().Message("DUMP - %s\n",text); TopExp_Explorer expl(s, TopAbs_VERTEX); int i; for (i = 1 ; expl.More(); expl.Next(),i++) { const TopoDS_Vertex& v = TopoDS::Vertex(expl.Current()); gp_Pnt pnt = BRep_Tool::Pnt(v); Base::Console().Message("v%d: (%.3f,%.3f,%.3f)\n",i,pnt.X(),pnt.Y(),pnt.Z()); } } void DrawUtil::countFaces(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(s, TopAbs_FACE, mapOfFaces); int num = mapOfFaces.Extent(); Base::Console().Message("COUNT - %s has %d Faces\n",text,num); } //count # of unique Wires in shape. void DrawUtil::countWires(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(s, TopAbs_WIRE, mapOfWires); int num = mapOfWires.Extent(); Base::Console().Message("COUNT - %s has %d wires\n",text,num); } void DrawUtil::countEdges(const char* text, const TopoDS_Shape& s) { TopTools_IndexedMapOfShape mapOfEdges; TopExp::MapShapes(s, TopAbs_EDGE, mapOfEdges); int num = mapOfEdges.Extent(); Base::Console().Message("COUNT - %s has %d edges\n",text,num); } void DrawUtil::dump1Vertex(const char* text, const TopoDS_Vertex& v) { Base::Console().Message("DUMP - dump1Vertex - %s\n",text); gp_Pnt pnt = BRep_Tool::Pnt(v); Base::Console().Message("%s: (%.3f,%.3f,%.3f)\n",text,pnt.X(),pnt.Y(),pnt.Z()); } void DrawUtil::dumpEdge(char* label, int i, TopoDS_Edge e) { BRepAdaptor_Curve adapt(e); double start = BRepLProp_CurveTool::FirstParameter(adapt); double end = BRepLProp_CurveTool::LastParameter(adapt); BRepLProp_CLProps propStart(adapt,start,0,Precision::Confusion()); const gp_Pnt& vStart = propStart.Value(); BRepLProp_CLProps propEnd(adapt,end,0,Precision::Confusion()); const gp_Pnt& vEnd = propEnd.Value(); //Base::Console().Message("%s edge:%d start:(%.3f,%.3f,%.3f)/%0.3f end:(%.2f,%.3f,%.3f)/%.3f\n",label,i, // vStart.X(),vStart.Y(),vStart.Z(),start,vEnd.X(),vEnd.Y(),vEnd.Z(),end); Base::Console().Message("%s edge:%d start:(%.3f,%.3f,%.3f) end:(%.2f,%.3f,%.3f)\n",label,i, vStart.X(),vStart.Y(),vStart.Z(),vEnd.X(),vEnd.Y(),vEnd.Z()); } const char* DrawUtil::printBool(bool b) { return (b ? "True" : "False"); } QString DrawUtil::qbaToDebug(const QByteArray & line) { QString s; uchar c; for ( int i=0 ; i < line.size() ; i++ ){ c = line[i]; if (( c >= 0x20) && (c <= 126) ) { s.append(QChar::fromLatin1(c)); } else { s.append(QString::fromUtf8("<%1>").arg(c, 2, 16, QChar::fromLatin1('0'))); } } return s; } //================================== <|endoftext|>
<commit_before>#include "ProtocolSimpleNisse.h" #include "NisseService.h" using namespace ThorsAnvil::Nisse::ProtocolSimple; ReadMessageHandler::ReadMessageHandler(NisseService& parent, LibEventBase* base, ThorsAnvil::Socket::DataSocket&& so) : NisseHandler(parent, base, so.getSocketId(), EV_READ) , socket(std::move(so)) , readSizeObject(0) , readBuffer(0) {} void ReadMessageHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { bool more; if (readSizeObject != sizeof(readSizeObject)) { std::tie(more, readSizeObject) = socket.getMessageData(reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize), readSizeObject); if (!more) { dropHandler(); return; } if (readSizeObject != sizeof(readSizeObject)) { return; } buffer.resize(bufferSize); } std::tie(more, readBuffer) = socket.getMessageData(&buffer[0], bufferSize, readBuffer); if (!more) { dropHandler(); return; } if (readBuffer != bufferSize) { return; } moveHandler<WriteMessageHandler>(std::move(socket), buffer); } WriteMessageHandler::WriteMessageHandler(NisseService& parent, LibEventBase* base, ThorsAnvil::Socket::DataSocket&& so, std::string const& m) : NisseHandler(parent, base, so.getSocketId(), EV_WRITE) , socket(std::move(so)) , writeSizeObject(0) , writeBuffer(0) , message(m) { message += " -> OK"; } void WriteMessageHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { bool more; if (writeSizeObject != sizeof(writeSizeObject)) { std::size_t bufferSize = message.size(); std::tie(more, writeSizeObject) = socket.putMessageData(reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize), writeSizeObject); if (!more) { dropHandler(); return; } if (writeSizeObject != sizeof(writeSizeObject)) { return; } } std::tie(more, writeBuffer) = socket.putMessageData(message.c_str(), message.size(), writeBuffer); if (!more) { dropHandler(); return; } if (writeBuffer != message.size()) { return; } dropHandler(); } <commit_msg>Fix simple bug<commit_after>#include "ProtocolSimpleNisse.h" #include "NisseService.h" using namespace ThorsAnvil::Nisse::ProtocolSimple; ReadMessageHandler::ReadMessageHandler(NisseService& parent, LibEventBase* base, ThorsAnvil::Socket::DataSocket&& so) : NisseHandler(parent, base, so.getSocketId(), EV_READ) , socket(std::move(so)) , readSizeObject(0) , readBuffer(0) {} void ReadMessageHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { bool more; if (readSizeObject != sizeof(readSizeObject)) { std::tie(more, readSizeObject) = socket.getMessageData(reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize), readSizeObject); if (!more) { dropHandler(); return; } if (readSizeObject != sizeof(readSizeObject)) { return; } buffer.resize(bufferSize); } std::tie(more, readBuffer) = socket.getMessageData(&buffer[0], bufferSize, readBuffer); if (!more) { dropHandler(); return; } if (readBuffer != bufferSize) { return; } moveHandler<WriteMessageHandler>(std::move(socket), std::move(buffer)); } WriteMessageHandler::WriteMessageHandler(NisseService& parent, LibEventBase* base, ThorsAnvil::Socket::DataSocket&& so, std::string const& m) : NisseHandler(parent, base, so.getSocketId(), EV_WRITE) , socket(std::move(so)) , writeSizeObject(0) , writeBuffer(0) , message(m) { message += " -> OK"; } void WriteMessageHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { bool more; if (writeSizeObject != sizeof(writeSizeObject)) { std::size_t bufferSize = message.size(); std::tie(more, writeSizeObject) = socket.putMessageData(reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize), writeSizeObject); if (!more) { dropHandler(); return; } if (writeSizeObject != sizeof(writeSizeObject)) { return; } } std::tie(more, writeBuffer) = socket.putMessageData(message.c_str(), message.size(), writeBuffer); if (!more) { dropHandler(); return; } if (writeBuffer != message.size()) { return; } dropHandler(); } <|endoftext|>
<commit_before>//#define RemCorReaPri_DEBUG #include <stdexcept> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <config.hh> #ifdef USE_DBXML #include <dbxml/DbXml.hpp> #endif // USE_DBXML #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "RemoteCorpusReaderPrivate.hh" #include "util/GetUrl.hh" #include "util/parseString.hh" #include "util/url.hh" #ifdef RemCorReaPri_DEBUG #include <iostream> #endif namespace alpinocorpus { // done RemoteCorpusReaderPrivate::RemoteCorpusReaderPrivate(std::string const &url) : d_validSize(true) { if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") throw OpenError(url, "Not a valid URL"); size_t i = url.find_last_of('/'); if (i == std::string::npos) throw std::invalid_argument("Invalid argument, must be http://host/name"); d_name = url.substr(i + 1); d_url = url; bool OK = false; util::GetUrl p1(url.substr(0, i) + "/corpora"); std::vector<std::string> lines; std::vector<std::string> words; boost::algorithm::split(lines, p1.body(), boost::algorithm::is_any_of("\n"), boost::algorithm::token_compress_on); for (std::vector<std::string>::const_iterator iter = lines.begin(); iter != lines.end(); ++iter) { boost::algorithm::split(words, *iter, boost::algorithm::is_any_of("\t")); if (words.size() == 4 && words[0] == d_name) { OK = true; try { d_size = util::parseString<size_t>(words[1]); } catch (std::invalid_argument &) { d_size = 0; d_validSize = false; } } } if (!OK) throw std::invalid_argument("URL is not a valid corpus: " + d_url); // why a reset here? d_geturl.reset(new util::GetUrl(d_url + "/entries")); } RemoteCorpusReaderPrivate::~RemoteCorpusReaderPrivate() { } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::getBegin() const { if (d_geturl->interrupted() && ! d_geturl->completed()) const_cast<RemoteCorpusReaderPrivate *>(this)->d_geturl->resume(); return EntryIterator(new RemoteIter(d_geturl, 0, false)); } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::getEnd() const { return EntryIterator(new RemoteIter(d_geturl, 0, true)); } // done? TODO: alleen naam van corpus of complete url? (nu: complete url) std::string RemoteCorpusReaderPrivate::getName() const { // return d_name; return d_url; } // done size_t RemoteCorpusReaderPrivate::getSize() const { if (d_validSize) return d_size; else throw std::runtime_error("RemoteCorpusReader: size is unknown"); } bool RemoteCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { #ifdef USE_DBXML try { DbXml::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (DbXml::XmlException const &e) { return false; } return true; #else util::GetUrl p(d_url + "/validQuery?query=" + util::toPercentEncoding(query)); std::string result = p.body(); boost::to_lower(result); boost::trim(result); return (result == "true" || result == "yes" || result == "1"); #endif } // done std::string RemoteCorpusReaderPrivate::readEntry(std::string const &filename) const { // util::GetUrl p(d_url + "/entry/" + escape(filename)); util::GetUrl p(d_url + "/entry/" + filename); return p.body(); } // TODO: multiple queries (now: only the first is used) std::string RemoteCorpusReaderPrivate::readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const { std::list<MarkerQuery>::const_iterator iter = queries.begin(); if (iter == queries.end()) return readEntry(entry); util::GetUrl p(d_url + "/entry/" + entry + // escape(entry) + "?markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value)); ++iter; if (iter != queries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return p.body(); } // TODO: multiple queries (now: only the first is used) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runQueryWithStylesheet( QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const { std::list<MarkerQuery>::const_iterator iter = markerQueries.begin(); if (iter == markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Missing query"); std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries?query=" + util::toPercentEncoding(q) + "&markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value) + "&contents=1", stylesheet)); ++iter; if (iter != markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return EntryIterator(new RemoteIter(p, 0, false, true)); } // TODO: multiple queries (now: only the first is used) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::beginWithStylesheet( std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const { std::list<MarkerQuery>::const_iterator iter = markerQueries.begin(); if (iter == markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Missing query"); std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries" + "?markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value) + "&contents=1", stylesheet)); ++iter; if (iter != markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return EntryIterator(new RemoteIter(p, 0, false, true)); } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runXPath( std::string const &query) const { std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries?query=" + util::toPercentEncoding(query) + "&contents=1")); return EntryIterator(new RemoteIter(p, 0, false, true)); } // done? TODO: klopt dit? (blijkbaar wel) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runXQuery( std::string const &query) const { return runXPath(query); } // done RemoteCorpusReaderPrivate::RemoteIter::RemoteIter(std::tr1::shared_ptr<util::GetUrl> geturl, size_t n, bool end, bool isquery) : d_geturl(geturl), d_idx(n), d_end(end), d_isquery(isquery), d_active(false) { d_interrupted = std::tr1::shared_ptr<bool>(new bool(false)); } // done RemoteCorpusReaderPrivate::RemoteIter::~RemoteIter() { } void RemoteCorpusReaderPrivate::RemoteIter::activate() const { if (d_active) return; if (d_end) { d_active = true; return; } d_geturl->line(d_idx); if (d_geturl->eof()) d_end = true; d_active = true; } // done std::string RemoteCorpusReaderPrivate::RemoteIter::current() const { activate(); if (!d_end) { std::string s = d_geturl->line(d_idx); if (d_isquery) { size_t i = s.find('\t'); if (i == std::string::npos) return s; else return s.substr(0, i); } else return s; } else return std::string(); } // done void RemoteCorpusReaderPrivate::RemoteIter::next() { activate(); if (*d_interrupted) { #ifdef RemCorReaPri_DEBUG std::cerr << "[RemoteCorpusReaderPrivate] Calling next on interrupted RemoteIter" << std::endl; #endif throw alpinocorpus::IterationInterrupted(); } if (!d_end) { ++d_idx; d_geturl->line(d_idx); if (d_geturl->eof()) d_end = true; } } // done bool RemoteCorpusReaderPrivate::RemoteIter::equals(IterImpl const &other) const { RemoteIter const &that = (RemoteIter const &)other; activate(); that.activate(); if (d_end && that.d_end) return true; else return (d_end == that.d_end && d_idx == that.d_idx); } // done IterImpl *RemoteCorpusReaderPrivate::RemoteIter::copy() const { RemoteIter *other = new RemoteIter(d_geturl, d_idx, d_end, d_isquery); other->d_interrupted = d_interrupted; return other; } // done void RemoteCorpusReaderPrivate::RemoteIter::interrupt() { #ifdef RemCorReaPri_DEBUG std::cerr << "[RemoteCorpusReaderPrivate] interrupting..." << std::endl; #endif d_geturl->interrupt(); *d_interrupted = true; } // TODO ????? parameter rdr not used, what is this for? std::string RemoteCorpusReaderPrivate::RemoteIter::contents( CorpusReader const &rdr) const { activate(); if (d_end) return std::string(); if (!d_isquery) return std::string(); std::string s = d_geturl->line(d_idx); size_t i = s.find('\t'); s = s.substr(i + 1); std::string result; size_t e; for (;;) { e = s.find('\\'); if (e > s.size() - 2) { result += s; break; } result += s.substr(0, e); switch (s[e + 1]) { case 'f': result += '\f'; break; case 'n': result += '\n'; break; case 'r': result += '\r'; break; case 't': result += '\t'; break; default: result += s[e + 1]; } s = s.substr(e + 2); } return result; } } // namespace alpinocorpus <commit_msg>[RemoteCorpusReader] minor edit<commit_after>//#define RemCorReaPri_DEBUG #include <stdexcept> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <config.hh> #ifdef USE_DBXML #include <dbxml/DbXml.hpp> #endif // USE_DBXML #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "RemoteCorpusReaderPrivate.hh" #include "util/GetUrl.hh" #include "util/parseString.hh" #include "util/url.hh" #ifdef RemCorReaPri_DEBUG #include <iostream> #endif namespace alpinocorpus { // done RemoteCorpusReaderPrivate::RemoteCorpusReaderPrivate(std::string const &url) : d_validSize(true) { if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") throw OpenError(url, "Not a valid URL"); size_t i = url.find_last_of('/'); if (i == std::string::npos) throw std::invalid_argument("Invalid argument, must be http://host/name"); d_name = url.substr(i + 1); d_url = url; bool OK = false; util::GetUrl p1(url.substr(0, i) + "/corpora"); std::vector<std::string> lines; std::vector<std::string> words; boost::algorithm::split(lines, p1.body(), boost::algorithm::is_any_of("\n"), boost::algorithm::token_compress_on); for (std::vector<std::string>::const_iterator iter = lines.begin(); iter != lines.end(); ++iter) { boost::algorithm::split(words, *iter, boost::algorithm::is_any_of("\t")); if (words.size() == 4 && words[0] == d_name) { OK = true; try { d_size = util::parseString<size_t>(words[1]); } catch (std::invalid_argument &) { d_size = 0; d_validSize = false; } } } if (!OK) throw std::invalid_argument("URL is not a valid corpus: " + d_url); // why a reset here? d_geturl.reset(new util::GetUrl(d_url + "/entries")); } RemoteCorpusReaderPrivate::~RemoteCorpusReaderPrivate() { } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::getBegin() const { if (d_geturl->interrupted() && ! d_geturl->completed()) const_cast<RemoteCorpusReaderPrivate *>(this)->d_geturl->resume(); return EntryIterator(new RemoteIter(d_geturl, 0)); } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::getEnd() const { return EntryIterator(new RemoteIter(d_geturl, 0, true)); } // done? TODO: alleen naam van corpus of complete url? (nu: complete url) std::string RemoteCorpusReaderPrivate::getName() const { // return d_name; return d_url; } // done size_t RemoteCorpusReaderPrivate::getSize() const { if (d_validSize) return d_size; else throw std::runtime_error("RemoteCorpusReader: size is unknown"); } bool RemoteCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { #ifdef USE_DBXML try { DbXml::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (DbXml::XmlException const &e) { return false; } return true; #else util::GetUrl p(d_url + "/validQuery?query=" + util::toPercentEncoding(query)); std::string result = p.body(); boost::to_lower(result); boost::trim(result); return (result == "true" || result == "yes" || result == "1"); #endif } // done std::string RemoteCorpusReaderPrivate::readEntry(std::string const &filename) const { // util::GetUrl p(d_url + "/entry/" + escape(filename)); util::GetUrl p(d_url + "/entry/" + filename); return p.body(); } // TODO: multiple queries (now: only the first is used) std::string RemoteCorpusReaderPrivate::readEntryMarkQueries(std::string const &entry, std::list<MarkerQuery> const &queries) const { std::list<MarkerQuery>::const_iterator iter = queries.begin(); if (iter == queries.end()) return readEntry(entry); util::GetUrl p(d_url + "/entry/" + entry + // escape(entry) + "?markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value)); ++iter; if (iter != queries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return p.body(); } // TODO: multiple queries (now: only the first is used) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runQueryWithStylesheet( QueryDialect d, std::string const &q, std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const { std::list<MarkerQuery>::const_iterator iter = markerQueries.begin(); if (iter == markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Missing query"); std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries?query=" + util::toPercentEncoding(q) + "&markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value) + "&contents=1", stylesheet)); ++iter; if (iter != markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return EntryIterator(new RemoteIter(p, 0, false, true)); } // TODO: multiple queries (now: only the first is used) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::beginWithStylesheet( std::string const &stylesheet, std::list<MarkerQuery> const &markerQueries) const { std::list<MarkerQuery>::const_iterator iter = markerQueries.begin(); if (iter == markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Missing query"); std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries" + "?markerQuery=" + util::toPercentEncoding(iter->query) + "&markerAttr=" + util::toPercentEncoding(iter->attr) + "&markerValue=" + util::toPercentEncoding(iter->value) + "&contents=1", stylesheet)); ++iter; if (iter != markerQueries.end()) throw Error("RemoteCorpusReaderPrivate: Multiple queries not implemented"); return EntryIterator(new RemoteIter(p, 0, false, true)); } // done CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runXPath( std::string const &query) const { std::tr1::shared_ptr<util::GetUrl> p(new util::GetUrl(d_url + "/entries?query=" + util::toPercentEncoding(query) + "&contents=1")); return EntryIterator(new RemoteIter(p, 0, false, true)); } // done? TODO: klopt dit? (blijkbaar wel) CorpusReader::EntryIterator RemoteCorpusReaderPrivate::runXQuery( std::string const &query) const { return runXPath(query); } // done RemoteCorpusReaderPrivate::RemoteIter::RemoteIter(std::tr1::shared_ptr<util::GetUrl> geturl, size_t n, bool end, bool isquery) : d_geturl(geturl), d_idx(n), d_end(end), d_isquery(isquery), d_active(false) { d_interrupted = std::tr1::shared_ptr<bool>(new bool(false)); } // done RemoteCorpusReaderPrivate::RemoteIter::~RemoteIter() { } void RemoteCorpusReaderPrivate::RemoteIter::activate() const { if (d_active) return; if (d_end) { d_active = true; return; } d_geturl->line(d_idx); if (d_geturl->eof()) d_end = true; d_active = true; } // done std::string RemoteCorpusReaderPrivate::RemoteIter::current() const { activate(); if (!d_end) { std::string s = d_geturl->line(d_idx); if (d_isquery) { size_t i = s.find('\t'); if (i == std::string::npos) return s; else return s.substr(0, i); } else return s; } else return std::string(); } // done void RemoteCorpusReaderPrivate::RemoteIter::next() { activate(); if (*d_interrupted) { #ifdef RemCorReaPri_DEBUG std::cerr << "[RemoteCorpusReaderPrivate] Calling next on interrupted RemoteIter" << std::endl; #endif throw alpinocorpus::IterationInterrupted(); } if (!d_end) { ++d_idx; d_geturl->line(d_idx); if (d_geturl->eof()) d_end = true; } } // done bool RemoteCorpusReaderPrivate::RemoteIter::equals(IterImpl const &other) const { RemoteIter const &that = (RemoteIter const &)other; activate(); that.activate(); if (d_end && that.d_end) return true; else return (d_end == that.d_end && d_idx == that.d_idx); } // done IterImpl *RemoteCorpusReaderPrivate::RemoteIter::copy() const { RemoteIter *other = new RemoteIter(d_geturl, d_idx, d_end, d_isquery); other->d_interrupted = d_interrupted; return other; } // done void RemoteCorpusReaderPrivate::RemoteIter::interrupt() { #ifdef RemCorReaPri_DEBUG std::cerr << "[RemoteCorpusReaderPrivate] interrupting..." << std::endl; #endif d_geturl->interrupt(); *d_interrupted = true; } // TODO ????? parameter rdr not used, what is this for? std::string RemoteCorpusReaderPrivate::RemoteIter::contents( CorpusReader const &rdr) const { activate(); if (d_end) return std::string(); if (!d_isquery) return std::string(); std::string s = d_geturl->line(d_idx); size_t i = s.find('\t'); s = s.substr(i + 1); std::string result; size_t e; for (;;) { e = s.find('\\'); if (e > s.size() - 2) { result += s; break; } result += s.substr(0, e); switch (s[e + 1]) { case 'f': result += '\f'; break; case 'n': result += '\n'; break; case 'r': result += '\r'; break; case 't': result += '\t'; break; default: result += s[e + 1]; } s = s.substr(e + 2); } return result; } } // namespace alpinocorpus <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include "usb_pipe.h" #include <cstdlib> #include <cstring> #include <zconf.h> #include "usbhost.h" #include "usb_endpoint.h" #include <linux/usbdevice_fs.h> #include "android_uvc.h" #include <chrono> #include "../../types.h" #define INTERRUPT_BUFFER_SIZE 1024 #define CLEAR_FEATURE 0x01 #define UVC_FEATURE 0x02 #define INTERRUPT_PACKET_SIZE 5 #define INTERRUPT_NOTIFICATION_INDEX 5 #define DEPTH_SENSOR_OVERFLOW_NOTIFICATION 11 #define COLOR_SENSOR_OVERFLOW_NOTIFICATION 13 using namespace librealsense::usb_host; usb_pipe::usb_pipe(usb_device *usb_device, usb_endpoint endpoint) : _endpoint(endpoint), _device(usb_device) { _request = std::shared_ptr<usb_request>(usb_request_new(_device, _endpoint.get_descriptor()), [](usb_request* req) {usb_request_free(req);}); } usb_pipe::~usb_pipe() { usb_request_cancel(_request.get()); } bool usb_pipe::reset() { int requestType = UVC_FEATURE; int request = CLEAR_FEATURE; int value = 0; int index = _endpoint.get_endpoint_address(); void* buffer = NULL; int length = 0; unsigned int timeout = 10; bool rv = usb_device_control_transfer(_device, requestType, request, value, index, buffer, length, timeout) == UVC_SUCCESS; if(rv) LOG_DEBUG("USB pipe " << (int)_endpoint.get_endpoint_address() << " reset successfully"); else LOG_DEBUG("Failed to reset the USB pipe " << (int)_endpoint.get_endpoint_address()); return rv; } size_t usb_pipe::read_pipe(uint8_t *buffer, size_t buffer_len, unsigned int timeout_ms) { return usb_device_bulk_transfer(_device, _endpoint.get_endpoint_address(), buffer, buffer_len, timeout_ms); } void usb_pipe::queue_finished_request(usb_request* response) { assert (response->endpoint == _endpoint.get_endpoint_address()); std::unique_lock<std::mutex> lk(_mutex); _received = true; lk.unlock(); _cv.notify_all(); if(_interrupt_buffer.size() > 0) { //Log fatal notifications, this is currently handles only D4xx devices. //TODO push HW notifications to librealsense if(response->actual_length > 0){ std::string buff = ""; for(int i = 0; i < response->actual_length; i++) buff += std::to_string(((uint8_t*)response->buffer)[i]) + ", "; LOG_DEBUG("interrupt_request: " << buff.c_str()); if(response->actual_length == INTERRUPT_PACKET_SIZE){ auto sts = ((uint8_t*)response->buffer)[INTERRUPT_NOTIFICATION_INDEX]; if(sts == DEPTH_SENSOR_OVERFLOW_NOTIFICATION || sts == COLOR_SENSOR_OVERFLOW_NOTIFICATION) LOG_ERROR("overflow status sent from the device"); } } queue_interrupt_request(); } } void usb_pipe::submit_request(uint8_t *buffer, size_t buffer_len) { _request->buffer = buffer; _request->buffer_length = buffer_len; int res = usb_request_queue(_request.get()); if(res < 0) { LOG_ERROR("Cannot queue request: " << strerror(errno)); } } void usb_pipe::queue_interrupt_request() { std::lock_guard<std::mutex> lock(_mutex); submit_request(_interrupt_buffer.data(), _interrupt_buffer.size()); } void usb_pipe::listen_to_interrupts() { auto attr = _endpoint.get_descriptor()->bmAttributes; if(attr == USB_ENDPOINT_XFER_INT) { _interrupt_buffer = std::vector<uint8_t>(INTERRUPT_BUFFER_SIZE); queue_interrupt_request(); } }<commit_msg>Update usb_pipe.cpp<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include "usb_pipe.h" #include <cstdlib> #include <cstring> #include <zconf.h> #include "usbhost.h" #include "usb_endpoint.h" #include <linux/usbdevice_fs.h> #include "android_uvc.h" #include <chrono> #include "../../types.h" #define INTERRUPT_BUFFER_SIZE 1024 #define CLEAR_FEATURE 0x01 #define UVC_FEATURE 0x02 #define INTERRUPT_PACKET_SIZE 6 #define INTERRUPT_NOTIFICATION_INDEX 5 #define DEPTH_SENSOR_OVERFLOW_NOTIFICATION 11 #define COLOR_SENSOR_OVERFLOW_NOTIFICATION 13 using namespace librealsense::usb_host; usb_pipe::usb_pipe(usb_device *usb_device, usb_endpoint endpoint) : _endpoint(endpoint), _device(usb_device) { _request = std::shared_ptr<usb_request>(usb_request_new(_device, _endpoint.get_descriptor()), [](usb_request* req) {usb_request_free(req);}); } usb_pipe::~usb_pipe() { usb_request_cancel(_request.get()); } bool usb_pipe::reset() { int requestType = UVC_FEATURE; int request = CLEAR_FEATURE; int value = 0; int index = _endpoint.get_endpoint_address(); void* buffer = NULL; int length = 0; unsigned int timeout = 10; bool rv = usb_device_control_transfer(_device, requestType, request, value, index, buffer, length, timeout) == UVC_SUCCESS; if(rv) LOG_DEBUG("USB pipe " << (int)_endpoint.get_endpoint_address() << " reset successfully"); else LOG_DEBUG("Failed to reset the USB pipe " << (int)_endpoint.get_endpoint_address()); return rv; } size_t usb_pipe::read_pipe(uint8_t *buffer, size_t buffer_len, unsigned int timeout_ms) { return usb_device_bulk_transfer(_device, _endpoint.get_endpoint_address(), buffer, buffer_len, timeout_ms); } void usb_pipe::queue_finished_request(usb_request* response) { assert (response->endpoint == _endpoint.get_endpoint_address()); std::unique_lock<std::mutex> lk(_mutex); _received = true; lk.unlock(); _cv.notify_all(); if(_interrupt_buffer.size() > 0) { //Log fatal notifications, this is currently handles only D4xx devices. //TODO push HW notifications to librealsense if(response->actual_length > 0){ std::string buff = ""; for(int i = 0; i < response->actual_length; i++) buff += std::to_string(((uint8_t*)response->buffer)[i]) + ", "; LOG_DEBUG("interrupt_request: " << buff.c_str()); if(response->actual_length == INTERRUPT_PACKET_SIZE){ auto sts = ((uint8_t*)response->buffer)[INTERRUPT_NOTIFICATION_INDEX]; if(sts == DEPTH_SENSOR_OVERFLOW_NOTIFICATION || sts == COLOR_SENSOR_OVERFLOW_NOTIFICATION) LOG_ERROR("overflow status sent from the device"); } } queue_interrupt_request(); } } void usb_pipe::submit_request(uint8_t *buffer, size_t buffer_len) { _request->buffer = buffer; _request->buffer_length = buffer_len; int res = usb_request_queue(_request.get()); if(res < 0) { LOG_ERROR("Cannot queue request: " << strerror(errno)); } } void usb_pipe::queue_interrupt_request() { std::lock_guard<std::mutex> lock(_mutex); submit_request(_interrupt_buffer.data(), _interrupt_buffer.size()); } void usb_pipe::listen_to_interrupts() { auto attr = _endpoint.get_descriptor()->bmAttributes; if(attr == USB_ENDPOINT_XFER_INT) { _interrupt_buffer = std::vector<uint8_t>(INTERRUPT_BUFFER_SIZE); queue_interrupt_request(); } } <|endoftext|>
<commit_before>// OpenLieroX // Input box // Created 30/3/03 // Jason Boettcher // code under LGPL #include "LieroX.h" #include "MathLib.h" #include "DeprecatedGUI/Menu.h" #include "GfxPrimitives.h" #include "StringUtils.h" #include "DeprecatedGUI/CBox.h" namespace DeprecatedGUI { /////////////////// // Draw the frame into a buffer void CBox::PreDraw() { // TODO: clean up this function (eg, to much different usage of same var, too much most-upper-level vars, ...) // If the width or height of the box has changed, create new buffer if (bmpBuffer.get()) { if (iWidth != bmpBuffer.get()->w || iHeight != bmpBuffer.get()->h) { bmpBuffer = NULL; } } // Create the buffer, if needed if (!bmpBuffer.get()) { SDL_PixelFormat *fmt = getMainPixelFormat(); if (fmt) bmpBuffer = gfxCreateSurface(iWidth, iHeight); else bmpBuffer = NULL; if (!bmpBuffer.get()) return; } // Set the whole buffer transparent SetColorKey(bmpBuffer.get()); FillSurfaceTransparent(bmpBuffer.get()); // Clip the border and radius if (iRound < 0 || iBorder < 0) return; iRound = MIN(MIN(iWidth,iHeight)/2,iRound); iBorder = MIN(MIN(iWidth,iHeight)/2,iBorder); // // 1. Draw the lines // int line_left,line_right,line_top,line_bottom; // Line positions line_left = MAX(iRound,iBorder); line_right = iWidth - MAX(iRound,iBorder); line_top = MAX(iRound,iBorder); line_bottom = iHeight - MAX(iRound,iBorder); // Color handling Color cur_col = iDarkColour; // Create gradient int rstep=0,gstep=0,bstep=0; if (iBorder) { rstep = (iLightColour.r-iDarkColour.r)/iBorder; rstep = (iLightColour.g-iDarkColour.g)/iBorder; rstep = (iLightColour.b-iDarkColour.b)/iBorder; } // Top line int j; for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer.get(),line_left,line_right,j,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Bottom line for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer.get(),line_left,line_right,iHeight-j-1,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Left line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer.get(),line_top,line_bottom,j,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Right line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer.get(),line_top,line_bottom,iWidth-j-1,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } // // 2. Draw the round borders // int x,y; // Radius has to be bigger than or equal to border iRound = MAX(iBorder,iRound); // Step for circle drawing float step = (float)(1/(PI*(iRound+0.00000001)*(iBorder+0.000000001))); LOCK_OR_QUIT(bmpBuffer); // Top left // (PI,3/2*PI) float i; for (i=1.00f;i<1.5f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Top right // (PI/2,PI) for (i=0.50f;i<1.0f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Bottom left // (3/2*PI,2PI) for (i=1.50f;i<2.0f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Bottom right // (0,PI) for (i=-0.01f;i<0.5f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // // Draw the background // if (iBgColour == tLX->clPink) return; // Draw the center rectangle DrawRectFill(bmpBuffer.get(),line_left,iBorder,line_right,iHeight-iBorder,iBgColour); // No need to draw more if (iRound <= iBorder) return; DrawRectFill(bmpBuffer.get(),iBorder,line_top,line_left,line_bottom,iBgColour); DrawRectFill(bmpBuffer.get(),line_right,line_top,iWidth-iBorder,line_bottom,iBgColour); // Top left // (1,3/2*PI) for (i=1.01f;i<1.49;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Top right // (PI/2,PI) for (i=0.51f;i<0.99;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Bottom left // (3/2*PI,2PI) for (i=1.51f;i<1.99;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Bottom right // (0,PI) for (i=0.01f;i<0.499;i+=step) { for (j=iBorder; j<=iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } UnlockSurface(bmpBuffer); } ///////////////// // Draw the frame void CBox::Draw(SDL_Surface * bmpDest) { if (bmpBuffer.get()) DrawImage(bmpDest,bmpBuffer,iX,iY); } ///////////////// // Free the widget void CBox::Destroy() { bmpBuffer = NULL; } ////////////////// // Checks if any mouse event happened int CBox::CheckEvent() { // If the mouse is over transparent area, don't fire any event // CGuiLayout will then continue processing events for other widgets // Get the mouse pos mouse_t *Mouse = GetMouse(); if (!Mouse) return BOX_NONE; int x = Mouse->X - iX; int y = Mouse->Y - iY; // Mouse in the buffer if (x < iWidth && y < iHeight) { // Mouse over transparent pixel? No event if (!LockSurface(bmpBuffer)) return BOX_NONE; if(Color(bmpBuffer.get()->format, GetPixel(bmpBuffer.get(),x,y)) == tLX->clPink) { UnlockSurface(bmpBuffer); return BOX_NOEVENT; } UnlockSurface(bmpBuffer); return BOX_MOUSEOVER; } else return BOX_NONE; } }; // namespace DeprecatedGUI <commit_msg>fixed possible crash<commit_after>// OpenLieroX // Input box // Created 30/3/03 // Jason Boettcher // code under LGPL #include "LieroX.h" #include "MathLib.h" #include "DeprecatedGUI/Menu.h" #include "GfxPrimitives.h" #include "StringUtils.h" #include "DeprecatedGUI/CBox.h" namespace DeprecatedGUI { /////////////////// // Draw the frame into a buffer void CBox::PreDraw() { // TODO: clean up this function (eg, to much different usage of same var, too much most-upper-level vars, ...) // If the width or height of the box has changed, create new buffer if (bmpBuffer.get()) { if (iWidth != bmpBuffer.get()->w || iHeight != bmpBuffer.get()->h) { bmpBuffer = NULL; } } // Create the buffer, if needed if (!bmpBuffer.get()) { SDL_PixelFormat *fmt = getMainPixelFormat(); if (fmt) bmpBuffer = gfxCreateSurface(iWidth, iHeight); else bmpBuffer = NULL; if (!bmpBuffer.get()) return; } // Set the whole buffer transparent SetColorKey(bmpBuffer.get()); FillSurfaceTransparent(bmpBuffer.get()); // Clip the border and radius if (iRound < 0 || iBorder < 0) return; iRound = MIN(MIN(iWidth,iHeight)/2,iRound); iBorder = MIN(MIN(iWidth,iHeight)/2,iBorder); // // 1. Draw the lines // int line_left,line_right,line_top,line_bottom; // Line positions line_left = MAX(iRound,iBorder); line_right = iWidth - MAX(iRound,iBorder); line_top = MAX(iRound,iBorder); line_bottom = iHeight - MAX(iRound,iBorder); // Color handling Color cur_col = iDarkColour; // Create gradient int rstep=0,gstep=0,bstep=0; if (iBorder) { rstep = (iLightColour.r-iDarkColour.r)/iBorder; rstep = (iLightColour.g-iDarkColour.g)/iBorder; rstep = (iLightColour.b-iDarkColour.b)/iBorder; } // Top line int j; for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer.get(),line_left,line_right,j,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Bottom line for (j=0; j<iBorder; j++) { DrawHLine(bmpBuffer.get(),line_left,line_right,iHeight-j-1,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Left line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer.get(),line_top,line_bottom,j,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } cur_col = iDarkColour; // Right line for (j=0; j<iBorder; j++) { DrawVLine(bmpBuffer.get(),line_top,line_bottom,iWidth-j-1,cur_col); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } // // 2. Draw the round borders // int x,y; // Radius has to be bigger than or equal to border iRound = MAX(iBorder,iRound); // Step for circle drawing float step = (float)(1/(PI*(iRound+0.00000001)*(iBorder+0.000000001))); LOCK_OR_QUIT(bmpBuffer); // Top left // (PI,3/2*PI) float i; for (i=1.00f;i<1.5f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Top right // (PI/2,PI) for (i=0.50f;i<1.0f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Bottom left // (3/2*PI,2PI) for (i=1.50f;i<2.0f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // Bottom right // (0,PI) for (i=-0.01f;i<0.5f;i+=step) { cur_col = iDarkColour; for (j=0; j<iBorder; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,cur_col.get(bmpBuffer->format)); cur_col = Color(iDarkColour.r+rstep*(j+1),iDarkColour.g+gstep*(j+1),iDarkColour.b+bstep*(j+1)); } } // // Draw the background // if (iBgColour == tLX->clPink) return; // Draw the center rectangle DrawRectFill(bmpBuffer.get(),line_left,iBorder,line_right,iHeight-iBorder,iBgColour); // No need to draw more if (iRound <= iBorder) return; DrawRectFill(bmpBuffer.get(),iBorder,line_top,line_left,line_bottom,iBgColour); DrawRectFill(bmpBuffer.get(),line_right,line_top,iWidth-iBorder,line_bottom,iBgColour); // Top left // (1,3/2*PI) for (i=1.01f;i<1.49;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Top right // (PI/2,PI) for (i=0.51f;i<0.99;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))-1+iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Bottom left // (3/2*PI,2PI) for (i=1.51f;i<1.99;i+=step) { for (j=iBorder; j<iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))-1+iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } // Bottom right // (0,PI) for (i=0.01f;i<0.499;i+=step) { for (j=iBorder; j<=iRound-iBorder+2; j++) { x = CLAMP( (int)((iRound-j)*sin(PI*i))+iWidth-iRound, 0, iWidth-1); y = CLAMP( (int)((iRound-j)*cos(PI*i))+iHeight-iRound, 0, iHeight-1); PutPixel(bmpBuffer.get(),x,y,iBgColour.get(bmpBuffer->format)); } } UnlockSurface(bmpBuffer); } ///////////////// // Draw the frame void CBox::Draw(SDL_Surface * bmpDest) { if (bmpBuffer.get()) DrawImage(bmpDest,bmpBuffer,iX,iY); } ///////////////// // Free the widget void CBox::Destroy() { bmpBuffer = NULL; } ////////////////// // Checks if any mouse event happened int CBox::CheckEvent() { // If the mouse is over transparent area, don't fire any event // CGuiLayout will then continue processing events for other widgets if(bmpBuffer.get() == NULL) { errors << "CBox::CheckEvent: bmpBuffer == NULL" << endl; return BOX_NONE; } // Get the mouse pos mouse_t *Mouse = GetMouse(); if (!Mouse) return BOX_NONE; int x = Mouse->X - iX; int y = Mouse->Y - iY; // Mouse in the buffer if (x < iWidth && y < iHeight) { // Mouse over transparent pixel? No event if (!LockSurface(bmpBuffer)) return BOX_NONE; if(Color(bmpBuffer.get()->format, GetPixel(bmpBuffer.get(),x,y)) == tLX->clPink) { UnlockSurface(bmpBuffer); return BOX_NOEVENT; } UnlockSurface(bmpBuffer); return BOX_MOUSEOVER; } else return BOX_NONE; } }; // namespace DeprecatedGUI <|endoftext|>
<commit_before>/*** * Copyright (c) 2013, Dan Hasting * 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 organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ***/ #include "emulatorhandler.h" #include "../global.h" #include "../common.h" #include <QFile> #include <QMessageBox> #include <QProcess> #include <QCryptographicHash> #include <quazip5/quazip.h> #include <quazip5/quazipfile.h> EmulatorHandler::EmulatorHandler(QWidget *parent) : QObject(parent) { this->parent = parent; lastOutput = ""; } void EmulatorHandler::checkStatus(int status) { if (status > 0) { QMessageBox exitDialog(parent); exitDialog.setWindowTitle(tr("Warning")); exitDialog.setText(tr("<ParentName> quit unexpectedly. Check the log for more information.") .replace("<ParentName>",ParentName)); exitDialog.setIcon(QMessageBox::Warning); exitDialog.addButton(QMessageBox::Ok); exitDialog.addButton(tr("View Log..."), QMessageBox::HelpRole); int ret = exitDialog.exec(); if (ret == 0) emit showLog(); } updateStatus(tr("Emulation stopped"), 3000); } void EmulatorHandler::cleanTemp() { QFile::remove(QDir::tempPath() + "/" + AppNameLower + "/" + qgetenv("USER") + "/temp.bin"); QFile::remove(QDir::tempPath() + "/" + AppNameLower + "/" + qgetenv("USER") + "/64dd-temp.bin"); } void EmulatorHandler::emitFinished() { emit finished(); } QStringList EmulatorHandler::parseArgString(QString argString) { QStringList result; QString arg; bool inQuote = false; bool inApos = false; for (int i = 0; i < argString.size(); i++) { // Check if inside of a quote if (argString.at(i) == QLatin1Char('"')) { inQuote = !inQuote; // Only continue if outside of both quotes and apostrophes if (arg.isEmpty() || (!inQuote && !inApos)) continue; } // Same check for apostrophes if (argString.at(i) == QLatin1Char('\'')) { inApos = !inApos; if (arg.isEmpty() || (!inQuote && !inApos)) continue; } if (!inQuote && !inApos && argString.at(i).isSpace()) { if (!arg.isEmpty()) { result += arg; arg.clear(); } } else arg += argString.at(i); } if (!arg.isEmpty()) result += arg; return result; } void EmulatorHandler::readOutput() { QString output = emulatorProc->readAllStandardOutput(); QStringList outputList = output.split("\n"); int lastIndex = outputList.lastIndexOf(QRegExp("^.*VI/s.*MHz$")); if (lastIndex >= 0) updateStatus(outputList[lastIndex]); lastOutput.append(output); } void EmulatorHandler::startEmulator(QDir romDir, QString romFileName, QString zipFileName, QDir ddDir, QString ddFileName, QString ddZipName) { QString completeRomPath = "", complete64DDPath = ""; bool zip = false, ddZip = false; //If zipped file, extract and write to temp location for loading QStringList zippedFiles; zippedFiles << zipFileName << ddZipName; bool ddZipCheck = false; foreach (QString zippedFile, zippedFiles) { if (zippedFile != "") { QString fileInZip, tempName, romPath, zipFile; if (!ddZipCheck) { zip = true; tempName = "/temp.bin"; fileInZip = romFileName; zipFile = romDir.absoluteFilePath(zippedFile); } else { ddZip = true; tempName = "/64dd-temp.bin"; fileInZip = ddFileName; zipFile = ddDir.absoluteFilePath(zippedFile); } QByteArray *romData = getZippedRom(fileInZip, zipFile); QString tempDir = QDir::tempPath() + "/" + AppNameLower + "/" + qgetenv("USER"); QDir().mkpath(tempDir); romPath = tempDir + tempName; QFile tempRom(romPath); tempRom.open(QIODevice::WriteOnly); tempRom.write(*romData); tempRom.close(); delete romData; if (!ddZipCheck) completeRomPath = romPath; else complete64DDPath = romPath; } ddZipCheck = true; } if (zipFileName == "" && romFileName != "") completeRomPath = romDir.absoluteFilePath(romFileName); if (ddZipName == "" && ddFileName != "") complete64DDPath = ddDir.absoluteFilePath(ddFileName); QString emulatorPath = SETTINGS.value("Paths/cen64", "").toString(); QString pifPath = SETTINGS.value("Paths/pifrom", "").toString(); QString ddIPLPath = SETTINGS.value("Paths/ddiplrom", "").toString(); bool ddMode = false; if (SETTINGS.value("Emulation/64dd", "").toString() == "true") ddMode = true; QFile emulatorFile(emulatorPath); QFile pifFile(pifPath); QFile ddIPL(ddIPLPath); QFile romFile(completeRomPath); QFile ddFile(complete64DDPath); //Sanity checks if (!emulatorFile.exists() || QFileInfo(emulatorFile).isDir() || !QFileInfo(emulatorFile).isExecutable()) { QMessageBox::warning(parent, tr("Warning"), tr("<ParentName> executable not found.").replace("<ParentName>",ParentName)); if (zip || ddZip) cleanTemp(); return; } if (!pifFile.exists() || QFileInfo(pifFile).isDir()) { QMessageBox::warning(parent, tr("Warning"), tr("PIF IPL file not found.")); if (zip || ddZip) cleanTemp(); return; } if (ddIPLPath != "" && (!ddIPL.exists() || QFileInfo(ddIPL).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("64DD IPL file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath != "" && (!romFile.exists() || QFileInfo(romFile).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("ROM file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath == "" && complete64DDPath != "" && (!ddFile.exists() || QFileInfo(ddFile).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("64DD ROM file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath == "" && complete64DDPath == "") { QMessageBox::warning(parent, tr("Warning"), tr("No ROM selected.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath != "") { romFile.open(QIODevice::ReadOnly); QByteArray romCheck = romFile.read(4); romFile.close(); if (romCheck.toHex() != "80371240") { if (romCheck.toHex() == "e848d316") { // 64DD file instead if (complete64DDPath == "" && ddMode) { complete64DDPath = completeRomPath; ddFile.setFileName(complete64DDPath); completeRomPath = ""; } else { QMessageBox::warning(parent, tr("Warning"), tr("64DD not enabled.")); if (zip || ddZip) cleanTemp(); return; } } else { QMessageBox::warning(parent, tr("Warning"), tr("Not a valid Z64 File.")); if (zip || ddZip) cleanTemp(); return; } } } if (complete64DDPath != "" && ddMode) { ddFile.open(QIODevice::ReadOnly); QByteArray romCheck = ddFile.read(4); ddFile.close(); if (romCheck.toHex() != "e848d316") { QMessageBox::warning(parent, tr("Warning"), tr("Not a valid 64DD File.")); if (zip || ddZip) cleanTemp(); return; } } QStringList args; if (SETTINGS.value("Saves/individualsave", "").toString() == "true") { QString eeprom4kPath = SETTINGS.value("Saves/eeprom4k", "").toString(); QString eeprom16kPath = SETTINGS.value("Saves/eeprom16k", "").toString(); QString sramPath = SETTINGS.value("Saves/sram", "").toString(); QString flashPath = SETTINGS.value("Saves/flash", "").toString(); if (eeprom4kPath != "") args << "-eep4k" << eeprom4kPath; if (eeprom16kPath != "") args << "-eep16k" << eeprom16kPath; if (sramPath != "") args << "-sram" << sramPath; if (flashPath != "") args << "-flash" << flashPath; } else { QString savesPath = SETTINGS.value("Saves/directory", "").toString(); if (savesPath != "") { QDir savesDir(savesPath); if (savesDir.exists()) { romFile.open(QIODevice::ReadOnly); QByteArray *romData = new QByteArray(romFile.readAll()); romFile.close(); QString romMD5 = QString(QCryptographicHash::hash(*romData, QCryptographicHash::Md5).toHex()); QString romBaseName = QFileInfo(romFile).completeBaseName(); QString eeprom4kFileName = romBaseName + "." + romMD5 + ".eep4k"; QString eeprom16kFileName = romBaseName + "." + romMD5 + ".eep16k"; QString sramFileName = romBaseName + "." + romMD5 + ".sram"; QString flashFileName = romBaseName + "." + romMD5 + ".flash"; QString eeprom4kPath = savesDir.absoluteFilePath(eeprom4kFileName); QString eeprom16kPath = savesDir.absoluteFilePath(eeprom16kFileName); QString sramPath = savesDir.absoluteFilePath(sramFileName); QString flashPath = savesDir.absoluteFilePath(flashFileName); // Check ROM catalog to determine save type QString catalogFile = SETTINGS.value("Paths/catalog", "").toString(); if (QFileInfo(catalogFile).exists()) { QSettings romCatalog(catalogFile, QSettings::IniFormat, parent); QString saveType = romCatalog.value(romMD5.toUpper()+"/SaveType","").toString(); if (saveType == "Eeprom 4KB") args << "-eep4k" << eeprom4kPath; else if (saveType == "Eeprom 16KB") args << "-eep16k" << eeprom16kPath; else if (saveType == "SRAM") args << "-sram" << sramPath; else if (saveType == "Flash RAM") args << "-flash" << flashPath; else if (saveType == "Controller Pack"); else args << "-eep4k" << eeprom4kPath << "-eep16k" << eeprom16kPath << "-sram" << sramPath << "-flash" << flashPath; } else { args << "-eep4k" << eeprom4kPath << "-eep16k" << eeprom16kPath << "-sram" << sramPath << "-flash" << flashPath; } delete romData; } } } for (int i = 1; i <= 4; i++) { QString ctrl = "Controller"+QString::number(i); if (SETTINGS.value(ctrl+"/enabled", "").toString() == "true") { args << "-controller"; QString options = "num="+QString::number(i); int accessory = SETTINGS.value(ctrl+"/accessory", 0).toInt(); QString memPak = SETTINGS.value(ctrl+"/mempak", "").toString(); QString tPakROM = SETTINGS.value(ctrl+"/tpakrom", "").toString(); QString tPakSave = SETTINGS.value(ctrl+"/tpaksave", "").toString(); if (accessory == 1) //Rumble Pak options += ",pak=rumble"; else if (accessory == 2 && memPak != "") //Controller Pak options += ",mempak="+memPak; else if (accessory == 3 && tPakROM != "" && tPakSave != "") //Transfer Pak options += ",tpak_rom="+tPakROM+",tpak_save="+tPakSave; args << options; } } if (SETTINGS.value("Emulation/multithread", "").toString() == "true") args << "-multithread"; if (SETTINGS.value("Emulation/noaudio", "").toString() == "true") args << "-noaudio"; if (SETTINGS.value("Emulation/novideo", "").toString() == "true") args << "-novideo"; if (ddIPLPath != "" && complete64DDPath != "" && ddMode) args << "-ddipl" << ddIPLPath << "-ddrom" << complete64DDPath; else if (completeRomPath == "") { QMessageBox::warning(parent, tr("Warning"), tr("No ROM selected or 64DD not enabled.")); if (zip || ddZip) cleanTemp(); return; } QString otherParameters = SETTINGS.value("Other/parameters", "").toString(); if (otherParameters != "") args.append(parseArgString(otherParameters)); args << pifPath; if (completeRomPath != "") args << completeRomPath; emulatorProc = new QProcess(this); connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(emitFinished())); connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(checkStatus(int))); if (zip || ddZip) connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(cleanTemp())); if (SETTINGS.value("Other/consoleoutput", "").toString() == "true") emulatorProc->setProcessChannelMode(QProcess::ForwardedChannels); else { connect(emulatorProc, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput())); emulatorProc->setProcessChannelMode(QProcess::MergedChannels); } //clear log lastOutput = ""; emulatorProc->start(emulatorPath, args); //Add command to log QString executable = emulatorPath; if (executable.contains(" ")) executable = '"' + executable + '"'; QString argString; foreach(QString arg, args) { if (arg.contains(" ")) argString += " \"" + arg + "\""; else argString += " " + arg; } lastOutput.append(executable + argString + "\n\n"); updateStatus(tr("Emulation started"), 3000); emit started(); } void EmulatorHandler::stopEmulator() { emulatorProc->terminate(); } void EmulatorHandler::updateStatus(QString message, int timeout) { emit statusUpdate(message, timeout); } <commit_msg>Fix temp directory path for multi user setup (dh4/mupen64plus-qt#50)<commit_after>/*** * Copyright (c) 2013, Dan Hasting * 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 organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ***/ #include "emulatorhandler.h" #include "../global.h" #include "../common.h" #include <QFile> #include <QMessageBox> #include <QProcess> #include <QCryptographicHash> #include <quazip5/quazip.h> #include <quazip5/quazipfile.h> EmulatorHandler::EmulatorHandler(QWidget *parent) : QObject(parent) { this->parent = parent; lastOutput = ""; } void EmulatorHandler::checkStatus(int status) { if (status > 0) { QMessageBox exitDialog(parent); exitDialog.setWindowTitle(tr("Warning")); exitDialog.setText(tr("<ParentName> quit unexpectedly. Check the log for more information.") .replace("<ParentName>",ParentName)); exitDialog.setIcon(QMessageBox::Warning); exitDialog.addButton(QMessageBox::Ok); exitDialog.addButton(tr("View Log..."), QMessageBox::HelpRole); int ret = exitDialog.exec(); if (ret == 0) emit showLog(); } updateStatus(tr("Emulation stopped"), 3000); } void EmulatorHandler::cleanTemp() { QFile::remove(QDir::tempPath() + "/" + AppNameLower + "-" + qgetenv("USER") + "/temp.bin"); QFile::remove(QDir::tempPath() + "/" + AppNameLower + "-" + qgetenv("USER") + "/64dd-temp.bin"); } void EmulatorHandler::emitFinished() { emit finished(); } QStringList EmulatorHandler::parseArgString(QString argString) { QStringList result; QString arg; bool inQuote = false; bool inApos = false; for (int i = 0; i < argString.size(); i++) { // Check if inside of a quote if (argString.at(i) == QLatin1Char('"')) { inQuote = !inQuote; // Only continue if outside of both quotes and apostrophes if (arg.isEmpty() || (!inQuote && !inApos)) continue; } // Same check for apostrophes if (argString.at(i) == QLatin1Char('\'')) { inApos = !inApos; if (arg.isEmpty() || (!inQuote && !inApos)) continue; } if (!inQuote && !inApos && argString.at(i).isSpace()) { if (!arg.isEmpty()) { result += arg; arg.clear(); } } else arg += argString.at(i); } if (!arg.isEmpty()) result += arg; return result; } void EmulatorHandler::readOutput() { QString output = emulatorProc->readAllStandardOutput(); QStringList outputList = output.split("\n"); int lastIndex = outputList.lastIndexOf(QRegExp("^.*VI/s.*MHz$")); if (lastIndex >= 0) updateStatus(outputList[lastIndex]); lastOutput.append(output); } void EmulatorHandler::startEmulator(QDir romDir, QString romFileName, QString zipFileName, QDir ddDir, QString ddFileName, QString ddZipName) { QString completeRomPath = "", complete64DDPath = ""; bool zip = false, ddZip = false; //If zipped file, extract and write to temp location for loading QStringList zippedFiles; zippedFiles << zipFileName << ddZipName; bool ddZipCheck = false; foreach (QString zippedFile, zippedFiles) { if (zippedFile != "") { QString fileInZip, tempName, romPath, zipFile; if (!ddZipCheck) { zip = true; tempName = "/temp.bin"; fileInZip = romFileName; zipFile = romDir.absoluteFilePath(zippedFile); } else { ddZip = true; tempName = "/64dd-temp.bin"; fileInZip = ddFileName; zipFile = ddDir.absoluteFilePath(zippedFile); } QByteArray *romData = getZippedRom(fileInZip, zipFile); QString tempDir = QDir::tempPath() + "/" + AppNameLower + "-" + qgetenv("USER"); QDir().mkpath(tempDir); romPath = tempDir + tempName; QFile tempRom(romPath); tempRom.open(QIODevice::WriteOnly); tempRom.write(*romData); tempRom.close(); delete romData; if (!ddZipCheck) completeRomPath = romPath; else complete64DDPath = romPath; } ddZipCheck = true; } if (zipFileName == "" && romFileName != "") completeRomPath = romDir.absoluteFilePath(romFileName); if (ddZipName == "" && ddFileName != "") complete64DDPath = ddDir.absoluteFilePath(ddFileName); QString emulatorPath = SETTINGS.value("Paths/cen64", "").toString(); QString pifPath = SETTINGS.value("Paths/pifrom", "").toString(); QString ddIPLPath = SETTINGS.value("Paths/ddiplrom", "").toString(); bool ddMode = false; if (SETTINGS.value("Emulation/64dd", "").toString() == "true") ddMode = true; QFile emulatorFile(emulatorPath); QFile pifFile(pifPath); QFile ddIPL(ddIPLPath); QFile romFile(completeRomPath); QFile ddFile(complete64DDPath); //Sanity checks if (!emulatorFile.exists() || QFileInfo(emulatorFile).isDir() || !QFileInfo(emulatorFile).isExecutable()) { QMessageBox::warning(parent, tr("Warning"), tr("<ParentName> executable not found.").replace("<ParentName>",ParentName)); if (zip || ddZip) cleanTemp(); return; } if (!pifFile.exists() || QFileInfo(pifFile).isDir()) { QMessageBox::warning(parent, tr("Warning"), tr("PIF IPL file not found.")); if (zip || ddZip) cleanTemp(); return; } if (ddIPLPath != "" && (!ddIPL.exists() || QFileInfo(ddIPL).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("64DD IPL file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath != "" && (!romFile.exists() || QFileInfo(romFile).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("ROM file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath == "" && complete64DDPath != "" && (!ddFile.exists() || QFileInfo(ddFile).isDir())) { QMessageBox::warning(parent, tr("Warning"), tr("64DD ROM file not found.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath == "" && complete64DDPath == "") { QMessageBox::warning(parent, tr("Warning"), tr("No ROM selected.")); if (zip || ddZip) cleanTemp(); return; } if (completeRomPath != "") { romFile.open(QIODevice::ReadOnly); QByteArray romCheck = romFile.read(4); romFile.close(); if (romCheck.toHex() != "80371240") { if (romCheck.toHex() == "e848d316") { // 64DD file instead if (complete64DDPath == "" && ddMode) { complete64DDPath = completeRomPath; ddFile.setFileName(complete64DDPath); completeRomPath = ""; } else { QMessageBox::warning(parent, tr("Warning"), tr("64DD not enabled.")); if (zip || ddZip) cleanTemp(); return; } } else { QMessageBox::warning(parent, tr("Warning"), tr("Not a valid Z64 File.")); if (zip || ddZip) cleanTemp(); return; } } } if (complete64DDPath != "" && ddMode) { ddFile.open(QIODevice::ReadOnly); QByteArray romCheck = ddFile.read(4); ddFile.close(); if (romCheck.toHex() != "e848d316") { QMessageBox::warning(parent, tr("Warning"), tr("Not a valid 64DD File.")); if (zip || ddZip) cleanTemp(); return; } } QStringList args; if (SETTINGS.value("Saves/individualsave", "").toString() == "true") { QString eeprom4kPath = SETTINGS.value("Saves/eeprom4k", "").toString(); QString eeprom16kPath = SETTINGS.value("Saves/eeprom16k", "").toString(); QString sramPath = SETTINGS.value("Saves/sram", "").toString(); QString flashPath = SETTINGS.value("Saves/flash", "").toString(); if (eeprom4kPath != "") args << "-eep4k" << eeprom4kPath; if (eeprom16kPath != "") args << "-eep16k" << eeprom16kPath; if (sramPath != "") args << "-sram" << sramPath; if (flashPath != "") args << "-flash" << flashPath; } else { QString savesPath = SETTINGS.value("Saves/directory", "").toString(); if (savesPath != "") { QDir savesDir(savesPath); if (savesDir.exists()) { romFile.open(QIODevice::ReadOnly); QByteArray *romData = new QByteArray(romFile.readAll()); romFile.close(); QString romMD5 = QString(QCryptographicHash::hash(*romData, QCryptographicHash::Md5).toHex()); QString romBaseName = QFileInfo(romFile).completeBaseName(); QString eeprom4kFileName = romBaseName + "." + romMD5 + ".eep4k"; QString eeprom16kFileName = romBaseName + "." + romMD5 + ".eep16k"; QString sramFileName = romBaseName + "." + romMD5 + ".sram"; QString flashFileName = romBaseName + "." + romMD5 + ".flash"; QString eeprom4kPath = savesDir.absoluteFilePath(eeprom4kFileName); QString eeprom16kPath = savesDir.absoluteFilePath(eeprom16kFileName); QString sramPath = savesDir.absoluteFilePath(sramFileName); QString flashPath = savesDir.absoluteFilePath(flashFileName); // Check ROM catalog to determine save type QString catalogFile = SETTINGS.value("Paths/catalog", "").toString(); if (QFileInfo(catalogFile).exists()) { QSettings romCatalog(catalogFile, QSettings::IniFormat, parent); QString saveType = romCatalog.value(romMD5.toUpper()+"/SaveType","").toString(); if (saveType == "Eeprom 4KB") args << "-eep4k" << eeprom4kPath; else if (saveType == "Eeprom 16KB") args << "-eep16k" << eeprom16kPath; else if (saveType == "SRAM") args << "-sram" << sramPath; else if (saveType == "Flash RAM") args << "-flash" << flashPath; else if (saveType == "Controller Pack"); else args << "-eep4k" << eeprom4kPath << "-eep16k" << eeprom16kPath << "-sram" << sramPath << "-flash" << flashPath; } else { args << "-eep4k" << eeprom4kPath << "-eep16k" << eeprom16kPath << "-sram" << sramPath << "-flash" << flashPath; } delete romData; } } } for (int i = 1; i <= 4; i++) { QString ctrl = "Controller"+QString::number(i); if (SETTINGS.value(ctrl+"/enabled", "").toString() == "true") { args << "-controller"; QString options = "num="+QString::number(i); int accessory = SETTINGS.value(ctrl+"/accessory", 0).toInt(); QString memPak = SETTINGS.value(ctrl+"/mempak", "").toString(); QString tPakROM = SETTINGS.value(ctrl+"/tpakrom", "").toString(); QString tPakSave = SETTINGS.value(ctrl+"/tpaksave", "").toString(); if (accessory == 1) //Rumble Pak options += ",pak=rumble"; else if (accessory == 2 && memPak != "") //Controller Pak options += ",mempak="+memPak; else if (accessory == 3 && tPakROM != "" && tPakSave != "") //Transfer Pak options += ",tpak_rom="+tPakROM+",tpak_save="+tPakSave; args << options; } } if (SETTINGS.value("Emulation/multithread", "").toString() == "true") args << "-multithread"; if (SETTINGS.value("Emulation/noaudio", "").toString() == "true") args << "-noaudio"; if (SETTINGS.value("Emulation/novideo", "").toString() == "true") args << "-novideo"; if (ddIPLPath != "" && complete64DDPath != "" && ddMode) args << "-ddipl" << ddIPLPath << "-ddrom" << complete64DDPath; else if (completeRomPath == "") { QMessageBox::warning(parent, tr("Warning"), tr("No ROM selected or 64DD not enabled.")); if (zip || ddZip) cleanTemp(); return; } QString otherParameters = SETTINGS.value("Other/parameters", "").toString(); if (otherParameters != "") args.append(parseArgString(otherParameters)); args << pifPath; if (completeRomPath != "") args << completeRomPath; emulatorProc = new QProcess(this); connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(emitFinished())); connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(checkStatus(int))); if (zip || ddZip) connect(emulatorProc, SIGNAL(finished(int)), this, SLOT(cleanTemp())); if (SETTINGS.value("Other/consoleoutput", "").toString() == "true") emulatorProc->setProcessChannelMode(QProcess::ForwardedChannels); else { connect(emulatorProc, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput())); emulatorProc->setProcessChannelMode(QProcess::MergedChannels); } //clear log lastOutput = ""; emulatorProc->start(emulatorPath, args); //Add command to log QString executable = emulatorPath; if (executable.contains(" ")) executable = '"' + executable + '"'; QString argString; foreach(QString arg, args) { if (arg.contains(" ")) argString += " \"" + arg + "\""; else argString += " " + arg; } lastOutput.append(executable + argString + "\n\n"); updateStatus(tr("Emulation started"), 3000); emit started(); } void EmulatorHandler::stopEmulator() { emulatorProc->terminate(); } void EmulatorHandler::updateStatus(QString message, int timeout) { emit statusUpdate(message, timeout); } <|endoftext|>
<commit_before>#include "hierarchy.h" #include "engine/blob.h" #include "engine/engine.h" #include "engine/hash_map.h" #include "engine/json_serializer.h" #include "engine/property_register.h" #include "universe.h" namespace Lumix { static const ComponentType HIERARCHY_TYPE_HANDLE = PropertyRegister::getComponentType("hierarchy"); class HierarchyImpl LUMIX_FINAL : public Hierarchy { private: typedef HashMap<Entity, Entity> Parents; public: HierarchyImpl(IPlugin& system, Universe& universe, IAllocator& allocator) : m_universe(universe) , m_parents(allocator) , m_children(allocator) , m_allocator(allocator) , m_system(system) { universe.registerComponentTypeScene(HIERARCHY_TYPE_HANDLE, this); m_is_processing = false; universe.entityDestroyed().bind<HierarchyImpl, &HierarchyImpl::onEntityDestroyed>(this); universe.entityTransformed().bind<HierarchyImpl, &HierarchyImpl::onEntityMoved>(this); } void clear() override { auto iter = m_children.begin(), end = m_children.end(); while (iter != end) { LUMIX_DELETE(m_allocator, iter.value()); ++iter; } m_children.clear(); m_parents.clear(); } ComponentHandle createComponent(ComponentType type, Entity entity) override { if (HIERARCHY_TYPE_HANDLE == type) { m_parents.insert(entity, INVALID_ENTITY); m_universe.addComponent(entity, type, this, {entity.index}); return {entity.index}; } return INVALID_COMPONENT; } void destroyComponent(ComponentHandle component, ComponentType type) override { if (HIERARCHY_TYPE_HANDLE == type) { Entity entity = {component.index}; auto parent_iter = m_parents.find(entity); if (parent_iter.isValid()) { auto iter = m_children.find(parent_iter.value()); if (iter != m_children.end()) { auto& children = *iter.value(); if (children.size() == 1) { LUMIX_DELETE(m_allocator, iter.value()); m_children.erase(iter); } else { for (int i = 0; i < children.size(); ++i) { if (children[i].m_entity == entity) { children.eraseFast(i); break; } } } } m_parents.erase(parent_iter); } m_universe.destroyComponent(entity, type, this, component); } } IPlugin& getPlugin() const override { return m_system; } void update(float time_delta, bool paused) override {} Universe& getUniverse() override { return m_universe; } IAllocator& getAllocator() { return m_allocator; } ComponentHandle getComponent(Entity entity, ComponentType type) override { ComponentHandle cmp = {entity.index}; return m_parents.find(entity) != m_parents.end() ? cmp : INVALID_COMPONENT; } void onEntityDestroyed(Entity entity) { auto iter = m_children.find(entity); if (iter != m_children.end()) { for (auto& x : *iter.value()) { m_parents.erase(x.m_entity); } LUMIX_DELETE(m_allocator, iter.value()); m_children.erase(iter); } } void onEntityMoved(Entity entity) { bool was_processing = m_is_processing; m_is_processing = true; Children::iterator iter = m_children.find(entity); if (iter.isValid()) { Transform parent_transform = m_universe.getTransform(entity); Array<Child>& children = *iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { m_universe.setTransform(children[i].m_entity, parent_transform * children[i].m_local_transform); } } m_is_processing = was_processing; if (m_is_processing) return; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid()) { Entity parent(parent_iter.value()); Children::iterator child_iter = m_children.find(parent); if (child_iter.isValid()) { Array<Child>& children = *child_iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { if (children[i].m_entity == entity) { Transform parent_transform = m_universe.getTransform(parent); children[i].m_local_transform = parent_transform.inverted() * m_universe.getTransform(entity); break; } } } } } void setLocalPosition(ComponentHandle cmp, const Vec3& position) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && Lumix::isValid(parent_iter.value())) { Quat parent_rot = m_universe.getRotation(parent_iter.value()); Vec3 parent_pos = m_universe.getPosition(parent_iter.value()); m_universe.setPosition(entity, parent_pos + parent_rot.rotate(position)); return; } m_universe.setPosition(entity, position); } Vec3 getLocalPosition(ComponentHandle cmp) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { auto child_iter = m_children.find(parent_iter.value()); ASSERT(child_iter.isValid()); for (auto& child : *child_iter.value()) { if (child.m_entity == entity) { return child.m_local_transform.pos; } } } return m_universe.getPosition(entity); } void setLocalRotationEuler(ComponentHandle cmp, const Vec3& rotation) override { Quat q; q.fromEuler(rotation); setLocalRotation(cmp, q); } Vec3 getLocalRotationEuler(ComponentHandle cmp) override { return getLocalRotation(cmp).toEuler(); } void setLocalRotation(ComponentHandle cmp, const Quat& rotation) override { Entity entity = { cmp.index }; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid()) { Quat parent_rot = m_universe.getRotation(parent_iter.value()); m_universe.setRotation(entity, parent_rot * rotation); return; } m_universe.setRotation(entity, rotation); } Quat getLocalRotation(ComponentHandle cmp) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { auto child_iter = m_children.find(parent_iter.value()); ASSERT(child_iter.isValid()); for (auto& child : *child_iter.value()) { if (child.m_entity == entity) { Quat rot = child.m_local_transform.rot; return rot; } } } return m_universe.getRotation(entity); } const Children& getAllChildren() const override { return m_children; } void setParent(ComponentHandle child, Entity parent) override { Entity child_entity = {child.index}; Parents::iterator old_parent_iter = m_parents.find(child_entity); if (old_parent_iter.isValid()) { if (isValid(old_parent_iter.value())) { Children::iterator child_iter = m_children.find(old_parent_iter.value()); ASSERT(child_iter.isValid()); Array<Child>& children = *child_iter.value(); for (int i = 0; i < children.size(); ++i) { if (children[i].m_entity == child_entity) { children.erase(i); break; } } } m_parents.erase(old_parent_iter); } if (isValid(parent)) { m_parents.insert(child_entity, parent); Children::iterator child_iter = m_children.find(parent); if (!child_iter.isValid()) { m_children.insert(parent, LUMIX_NEW(m_allocator, Array<Child>)(m_allocator)); child_iter = m_children.find(parent); } Child& c = child_iter.value()->emplace(); c.m_entity = child_entity; Transform parent_transform = m_universe.getTransform(parent); c.m_local_transform = parent_transform.inverted() * m_universe.getTransform(child_entity); } } Entity getParent(ComponentHandle child) override { Entity child_entity = {child.index}; Parents::iterator parent_iter = m_parents.find(child_entity); if (parent_iter.isValid()) { return Entity(parent_iter.value()); } return INVALID_ENTITY; } void serialize(OutputBlob& serializer) override { int size = m_parents.size(); serializer.write((int32)size); Parents::iterator iter = m_parents.begin(), end = m_parents.end(); while (iter != end) { serializer.write(iter.key()); serializer.write(iter.value()); ++iter; } } void deserialize(InputBlob& serializer, int /*version*/) override { int32 size; serializer.read(size); for (int i = 0; i < size; ++i) { Entity child, parent; serializer.read(child); serializer.read(parent); ComponentHandle cmp = {child.index}; setParent(cmp, parent); m_universe.addComponent(child, HIERARCHY_TYPE_HANDLE, this, cmp); } } Array<Child>* getChildren(Entity parent) override { Children::iterator iter = m_children.find(parent); if (iter.isValid()) { return iter.value(); } return nullptr; } private: IAllocator& m_allocator; Universe& m_universe; Parents m_parents; Children m_children; IPlugin& m_system; bool m_is_processing; }; IScene* HierarchyPlugin::createScene(Universe& ctx) { return Hierarchy::create(*this, ctx, m_allocator); } void HierarchyPlugin::destroyScene(IScene* scene) { Hierarchy::destroy(static_cast<Hierarchy*>(scene)); } Hierarchy* Hierarchy::create(IPlugin& system, Universe& universe, IAllocator& allocator) { return LUMIX_NEW(allocator, HierarchyImpl)(system, universe, allocator); } void Hierarchy::destroy(Hierarchy* hierarchy) { LUMIX_DELETE(static_cast<HierarchyImpl*>(hierarchy)->getAllocator(), hierarchy); } } // namespace Lumix <commit_msg>fixed hierarchy crash when parent entity is destroyed and then child is destroyed - closes #1026<commit_after>#include "hierarchy.h" #include "engine/blob.h" #include "engine/engine.h" #include "engine/hash_map.h" #include "engine/json_serializer.h" #include "engine/property_register.h" #include "universe.h" namespace Lumix { static const ComponentType HIERARCHY_TYPE_HANDLE = PropertyRegister::getComponentType("hierarchy"); class HierarchyImpl LUMIX_FINAL : public Hierarchy { private: typedef HashMap<Entity, Entity> Parents; public: HierarchyImpl(IPlugin& system, Universe& universe, IAllocator& allocator) : m_universe(universe) , m_parents(allocator) , m_children(allocator) , m_allocator(allocator) , m_system(system) { universe.registerComponentTypeScene(HIERARCHY_TYPE_HANDLE, this); m_is_processing = false; universe.entityDestroyed().bind<HierarchyImpl, &HierarchyImpl::onEntityDestroyed>(this); universe.entityTransformed().bind<HierarchyImpl, &HierarchyImpl::onEntityMoved>(this); } void clear() override { auto iter = m_children.begin(), end = m_children.end(); while (iter != end) { LUMIX_DELETE(m_allocator, iter.value()); ++iter; } m_children.clear(); m_parents.clear(); } ComponentHandle createComponent(ComponentType type, Entity entity) override { if (HIERARCHY_TYPE_HANDLE == type) { m_parents.insert(entity, INVALID_ENTITY); m_universe.addComponent(entity, type, this, {entity.index}); return {entity.index}; } return INVALID_COMPONENT; } void destroyComponent(ComponentHandle component, ComponentType type) override { if (HIERARCHY_TYPE_HANDLE == type) { Entity entity = {component.index}; auto parent_iter = m_parents.find(entity); ASSERT(parent_iter.isValid()); if (isValid(parent_iter.value())) { auto iter = m_children.find(parent_iter.value()); if (iter != m_children.end()) { auto& children = *iter.value(); if (children.size() == 1) { LUMIX_DELETE(m_allocator, iter.value()); m_children.erase(iter); } else { for (int i = 0; i < children.size(); ++i) { if (children[i].m_entity == entity) { children.eraseFast(i); break; } } } } } m_parents.erase(parent_iter); m_universe.destroyComponent(entity, type, this, component); } } IPlugin& getPlugin() const override { return m_system; } void update(float time_delta, bool paused) override {} Universe& getUniverse() override { return m_universe; } IAllocator& getAllocator() { return m_allocator; } ComponentHandle getComponent(Entity entity, ComponentType type) override { ComponentHandle cmp = {entity.index}; return m_parents.find(entity) != m_parents.end() ? cmp : INVALID_COMPONENT; } void onEntityDestroyed(Entity entity) { auto iter = m_children.find(entity); if (iter != m_children.end()) { for (auto& x : *iter.value()) { m_parents[x.m_entity] = INVALID_ENTITY; } LUMIX_DELETE(m_allocator, iter.value()); m_children.erase(iter); } } void onEntityMoved(Entity entity) { bool was_processing = m_is_processing; m_is_processing = true; Children::iterator iter = m_children.find(entity); if (iter.isValid()) { Transform parent_transform = m_universe.getTransform(entity); Array<Child>& children = *iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { m_universe.setTransform(children[i].m_entity, parent_transform * children[i].m_local_transform); } } m_is_processing = was_processing; if (m_is_processing) return; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { Entity parent(parent_iter.value()); Children::iterator child_iter = m_children.find(parent); if (child_iter.isValid()) { Array<Child>& children = *child_iter.value(); for (int i = 0, c = children.size(); i < c; ++i) { if (children[i].m_entity == entity) { Transform parent_transform = m_universe.getTransform(parent); children[i].m_local_transform = parent_transform.inverted() * m_universe.getTransform(entity); break; } } } } } void setLocalPosition(ComponentHandle cmp, const Vec3& position) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { Quat parent_rot = m_universe.getRotation(parent_iter.value()); Vec3 parent_pos = m_universe.getPosition(parent_iter.value()); m_universe.setPosition(entity, parent_pos + parent_rot.rotate(position)); return; } m_universe.setPosition(entity, position); } Vec3 getLocalPosition(ComponentHandle cmp) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { auto child_iter = m_children.find(parent_iter.value()); ASSERT(child_iter.isValid()); for (auto& child : *child_iter.value()) { if (child.m_entity == entity) { return child.m_local_transform.pos; } } } return m_universe.getPosition(entity); } void setLocalRotationEuler(ComponentHandle cmp, const Vec3& rotation) override { Quat q; q.fromEuler(rotation); setLocalRotation(cmp, q); } Vec3 getLocalRotationEuler(ComponentHandle cmp) override { return getLocalRotation(cmp).toEuler(); } void setLocalRotation(ComponentHandle cmp, const Quat& rotation) override { Entity entity = { cmp.index }; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { Quat parent_rot = m_universe.getRotation(parent_iter.value()); m_universe.setRotation(entity, parent_rot * rotation); return; } m_universe.setRotation(entity, rotation); } Quat getLocalRotation(ComponentHandle cmp) override { Entity entity = {cmp.index}; Parents::iterator parent_iter = m_parents.find(entity); if (parent_iter.isValid() && isValid(parent_iter.value())) { auto child_iter = m_children.find(parent_iter.value()); ASSERT(child_iter.isValid()); for (auto& child : *child_iter.value()) { if (child.m_entity == entity) { Quat rot = child.m_local_transform.rot; return rot; } } } return m_universe.getRotation(entity); } const Children& getAllChildren() const override { return m_children; } void setParent(ComponentHandle child, Entity parent) override { Entity child_entity = {child.index}; Parents::iterator old_parent_iter = m_parents.find(child_entity); if (old_parent_iter.isValid()) { if (isValid(old_parent_iter.value())) { Children::iterator child_iter = m_children.find(old_parent_iter.value()); ASSERT(child_iter.isValid()); Array<Child>& children = *child_iter.value(); for (int i = 0; i < children.size(); ++i) { if (children[i].m_entity == child_entity) { children.erase(i); break; } } } m_parents.erase(old_parent_iter); } m_parents.insert(child_entity, parent); if (isValid(parent)) { Children::iterator child_iter = m_children.find(parent); if (!child_iter.isValid()) { m_children.insert(parent, LUMIX_NEW(m_allocator, Array<Child>)(m_allocator)); child_iter = m_children.find(parent); } Child& c = child_iter.value()->emplace(); c.m_entity = child_entity; Transform parent_transform = m_universe.getTransform(parent); c.m_local_transform = parent_transform.inverted() * m_universe.getTransform(child_entity); } } Entity getParent(ComponentHandle child) override { Entity child_entity = {child.index}; Parents::iterator parent_iter = m_parents.find(child_entity); if (parent_iter.isValid()) { return parent_iter.value(); } return INVALID_ENTITY; } void serialize(OutputBlob& serializer) override { int size = m_parents.size(); serializer.write((int32)size); Parents::iterator iter = m_parents.begin(), end = m_parents.end(); while (iter != end) { serializer.write(iter.key()); serializer.write(iter.value()); ++iter; } } void deserialize(InputBlob& serializer, int /*version*/) override { int32 size; serializer.read(size); for (int i = 0; i < size; ++i) { Entity child, parent; serializer.read(child); serializer.read(parent); ComponentHandle cmp = {child.index}; setParent(cmp, parent); m_universe.addComponent(child, HIERARCHY_TYPE_HANDLE, this, cmp); } } Array<Child>* getChildren(Entity parent) override { Children::iterator iter = m_children.find(parent); if (iter.isValid()) { return iter.value(); } return nullptr; } private: IAllocator& m_allocator; Universe& m_universe; Parents m_parents; Children m_children; IPlugin& m_system; bool m_is_processing; }; IScene* HierarchyPlugin::createScene(Universe& ctx) { return Hierarchy::create(*this, ctx, m_allocator); } void HierarchyPlugin::destroyScene(IScene* scene) { Hierarchy::destroy(static_cast<Hierarchy*>(scene)); } Hierarchy* Hierarchy::create(IPlugin& system, Universe& universe, IAllocator& allocator) { return LUMIX_NEW(allocator, HierarchyImpl)(system, universe, allocator); } void Hierarchy::destroy(Hierarchy* hierarchy) { LUMIX_DELETE(static_cast<HierarchyImpl*>(hierarchy)->getAllocator(), hierarchy); } } // namespace Lumix <|endoftext|>
<commit_before> namespace cusim { namespace detail { template< typename tCount > __device__ inline tCount warp_prefix( unsigned aWTID, tCount aValue ) { /* The PTX version results in much tighter code than the C version. * The C version produces four instructions per step (a ISETP, * IADD, SHFL and SEL); the inline PTX version gets it down to two * (SHFL + predicated IADD). * * Incidentally, the PTX code is shown as an example for the shfl * instruction in the PTX ISA document. See * http://docs.nvidia.com/cuda/parallel-thread-execution/index.html */ # if 0 auto x0 = __shfl_up( aValue, 1 ); aValue += (aWTID >= 1) ? x0 : 0; auto x1 = __shfl_up( aValue, 2 ); aValue += (aWTID >= 2) ? x1 : 0; auto x2 = __shfl_up( aValue, 4 ); aValue += (aWTID >= 4) ? x2 : 0; auto x3 = __shfl_up( aValue, 8 ); aValue += (aWTID >= 8) ? x3 : 0; auto x4 = __shfl_up( aValue, 16 ); aValue += (aWTID >= 16) ? x4 : 0; # else __asm__ volatile( "{\n\t" ".reg .u32 t0;\n\t" ".reg .pred valid;\n\t" "shfl.up.b32 t0|valid, %0, 1, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 2, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 4, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 8, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 16, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "}\n\t" : "+r"(aValue) ); # endif return aValue; } template< typename tReal > __device__ inline tReal reduce0( tReal aValue ) { aValue += __shfl_down_sync( ~0u, aValue, 16 ); aValue += __shfl_down_sync( ~0u, aValue, 8 ); aValue += __shfl_down_sync( ~0u, aValue, 4 ); aValue += __shfl_down_sync( ~0u, aValue, 2 ); aValue += __shfl_down_sync( ~0u, aValue, 1 ); return aValue; } } template< typename tReal, typename tCount > __global__ void /*__launch_bounds__(1024,1)*/ K_distance( tReal* aDistance, unsigned aN, unsigned aM, tCount* aCur, tCount const* aRef ) { __shared__ tReal totals[32]; //XXX-FIXME: number of warps in block. auto const warp = threadIdx.y; auto const wtid = threadIdx.x; auto const n32 = (aN+32-1)/32*32; auto const m32 = (aM+32-1)/32*32; // init if( 0 == warp ) { totals[wtid] = tReal(0); } __syncthreads(); // column-wise prefix sums for( auto row = warp; row < aN; row += blockDim.y ) { tCount base = 0; for( auto col = wtid; col < m32; col += 32 ) { tCount const val = col < aM ? aCur[row*aM+col] : 0 ; tCount const sum = base + detail::warp_prefix( wtid, val ); if( col < aM ) aCur[row*aM+col] = sum; base = __shfl_sync( ~0u, sum, 31 ); } } __syncthreads(); // row-wise prefix sums, and accumulate the squared difference to the reference tReal acc = tReal(0); for( auto col = warp; col < aM; col += blockDim.y ) { tCount base = 0; tReal a2 = tReal(0); for( auto row = wtid; row < n32; row += 32 ) { tCount const val = row < aN ? aCur[row*aM+col] : 0 ; tCount const sum = base + detail::warp_prefix( wtid, val ); base = __shfl_sync( ~0u, sum, 31 ); if( row < aN ) { tCount const ref = aRef[row*aM+col]; tReal const dd = tReal(sum) - ref; a2 += dd*dd; } } acc += a2; } // reduce the per-thread sums in each warp tReal const wsum = detail::reduce0( acc ); if( 0 == wtid ) totals[warp] = wsum; __syncthreads(); // have one warp reduce the per-warp sums to the final sum if( 0 == warp ) { tReal const tsum = wtid < 32 //XXX ? totals[wtid] : 0 ; tReal const fin = detail::reduce0( tsum ); if( 0 == wtid ) *aDistance = fin; } // zero out the histogram for the next invocation for( auto row = warp; row < aN; row += blockDim.y ) { for( auto col = wtid; col < aM; col += 32 ) { aCur[row*aM+col] = 0; } } } } <commit_msg>Compat: use non-sync __shfl() intrinsics before CUDA9<commit_after>namespace cusim { /* In CUDA v9.x, __shfl*_sync() are introduced, and the old __shfl*() are * immediately deprecated. Unfortunately, the __shfl*_sync() are not * available before CUDA v9. */ # if __CUDACC_VER_MAJOR__ < 9 # define __shfl_sync( mask, ... ) __shfl( __VA_ARGS__ ) # define __shfl_down_sync( mask, ... ) __shfl_down( __VA_ARGS__ ) # endif // ~ CUDA before version 9 namespace detail { template< typename tCount > __device__ inline tCount warp_prefix( unsigned aWTID, tCount aValue ) { /* The PTX version results in much tighter code than the C version. * The C version produces four instructions per step (a ISETP, * IADD, SHFL and SEL); the inline PTX version gets it down to two * (SHFL + predicated IADD). * * Incidentally, the PTX code is shown as an example for the shfl * instruction in the PTX ISA document. See * http://docs.nvidia.com/cuda/parallel-thread-execution/index.html */ # if 0 auto x0 = __shfl_up( aValue, 1 ); aValue += (aWTID >= 1) ? x0 : 0; auto x1 = __shfl_up( aValue, 2 ); aValue += (aWTID >= 2) ? x1 : 0; auto x2 = __shfl_up( aValue, 4 ); aValue += (aWTID >= 4) ? x2 : 0; auto x3 = __shfl_up( aValue, 8 ); aValue += (aWTID >= 8) ? x3 : 0; auto x4 = __shfl_up( aValue, 16 ); aValue += (aWTID >= 16) ? x4 : 0; # else __asm__ volatile( "{\n\t" ".reg .u32 t0;\n\t" ".reg .pred valid;\n\t" "shfl.up.b32 t0|valid, %0, 1, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 2, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 4, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 8, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "shfl.up.b32 t0|valid, %0, 16, 0;\n\t" "@valid add.s32 %0, t0, %0;\n\t" "}\n\t" : "+r"(aValue) ); # endif return aValue; } template< typename tReal > __device__ inline tReal reduce0( tReal aValue ) { aValue += __shfl_down_sync( ~0u, aValue, 16 ); aValue += __shfl_down_sync( ~0u, aValue, 8 ); aValue += __shfl_down_sync( ~0u, aValue, 4 ); aValue += __shfl_down_sync( ~0u, aValue, 2 ); aValue += __shfl_down_sync( ~0u, aValue, 1 ); return aValue; } } template< typename tReal, typename tCount > __global__ void /*__launch_bounds__(1024,1)*/ K_distance( tReal* aDistance, unsigned aN, unsigned aM, tCount* aCur, tCount const* aRef ) { __shared__ tReal totals[32]; //XXX-FIXME: number of warps in block. auto const warp = threadIdx.y; auto const wtid = threadIdx.x; auto const n32 = (aN+32-1)/32*32; auto const m32 = (aM+32-1)/32*32; // init if( 0 == warp ) { totals[wtid] = tReal(0); } __syncthreads(); // column-wise prefix sums for( auto row = warp; row < aN; row += blockDim.y ) { tCount base = 0; for( auto col = wtid; col < m32; col += 32 ) { tCount const val = col < aM ? aCur[row*aM+col] : 0 ; tCount const sum = base + detail::warp_prefix( wtid, val ); if( col < aM ) aCur[row*aM+col] = sum; base = __shfl_sync( ~0u, sum, 31 ); } } __syncthreads(); // row-wise prefix sums, and accumulate the squared difference to the reference tReal acc = tReal(0); for( auto col = warp; col < aM; col += blockDim.y ) { tCount base = 0; tReal a2 = tReal(0); for( auto row = wtid; row < n32; row += 32 ) { tCount const val = row < aN ? aCur[row*aM+col] : 0 ; tCount const sum = base + detail::warp_prefix( wtid, val ); base = __shfl_sync( ~0u, sum, 31 ); if( row < aN ) { tCount const ref = aRef[row*aM+col]; tReal const dd = tReal(sum) - ref; a2 += dd*dd; } } acc += a2; } // reduce the per-thread sums in each warp tReal const wsum = detail::reduce0( acc ); if( 0 == wtid ) totals[warp] = wsum; __syncthreads(); // have one warp reduce the per-warp sums to the final sum if( 0 == warp ) { tReal const tsum = wtid < 32 //XXX ? totals[wtid] : 0 ; tReal const fin = detail::reduce0( tsum ); if( 0 == wtid ) *aDistance = fin; } // zero out the histogram for the next invocation for( auto row = warp; row < aN; row += blockDim.y ) { for( auto col = wtid; col < aM; col += 32 ) { aCur[row*aM+col] = 0; } } } } <|endoftext|>
<commit_before><commit_msg>Complete the solution to the second part of question 3.7<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 The WebM 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 in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #ifndef WEBMIDS_HPP #define WEBMIDS_HPP namespace mkvmuxer { enum MkvId { kMkvEBML = 0x1A45DFA3, kMkvEBMLVersion = 0x4286, kMkvEBMLReadVersion = 0x42F7, kMkvEBMLMaxIDLength = 0x42F2, kMkvEBMLMaxSizeLength = 0x42F3, kMkvDocType = 0x4282, kMkvDocTypeVersion = 0x4287, kMkvDocTypeReadVersion = 0x4285, kMkvVoid = 0xEC, kMkvSignatureSlot = 0x1B538667, kMkvSignatureAlgo = 0x7E8A, kMkvSignatureHash = 0x7E9A, kMkvSignaturePublicKey = 0x7EA5, kMkvSignature = 0x7EB5, kMkvSignatureElements = 0x7E5B, kMkvSignatureElementList = 0x7E7B, kMkvSignedElement = 0x6532, //segment kMkvSegment = 0x18538067, //Meta Seek Information kMkvSeekHead = 0x114D9B74, kMkvSeek = 0x4DBB, kMkvSeekID = 0x53AB, kMkvSeekPosition = 0x53AC, //Segment Information kMkvInfo = 0x1549A966, kMkvTimecodeScale = 0x2AD7B1, kMkvDuration = 0x4489, kMkvDateUTC = 0x4461, kMkvMuxingApp = 0x4D80, kMkvWritingApp = 0x5741, //Cluster kMkvCluster = 0x1F43B675, kMkvTimecode = 0xE7, kMkvPrevSize = 0xAB, kMkvBlockGroup = 0xA0, kMkvBlock = 0xA1, kMkvBlockDuration = 0x9B, kMkvReferenceBlock = 0xFB, kMkvLaceNumber = 0xCC, kMkvSimpleBlock = 0xA3, kMkvBlockAdditions = 0x75A1, kMkvBlockMore = 0xA6, kMkvBlockAddID = 0xEE, kMkvBlockAdditional = 0xA5, //Track kMkvTracks = 0x1654AE6B, kMkvTrackEntry = 0xAE, kMkvTrackNumber = 0xD7, kMkvTrackUID = 0x73C5, kMkvTrackType = 0x83, kMkvFlagEnabled = 0xB9, kMkvFlagDefault = 0x88, kMkvFlagForced = 0x55AA, kMkvFlagLacing = 0x9C, kMkvDefaultDuration = 0x23E383, kMkvName = 0x536E, kMkvLanguage = 0x22B59C, kMkvCodecID = 0x86, kMkvCodecPrivate = 0x63A2, kMkvCodecName = 0x258688, kMkvMaxBlockAdditionID = 0x55EE, kMkvCodecDelay = 0x56AA, kMkvSeekPreRoll = 0x56BB, //video kMkvVideo = 0xE0, kMkvFlagInterlaced = 0x9A, kMkvStereoMode = 0x53B8, kMkvAlphaMode = 0x53C0, kMkvPixelWidth = 0xB0, kMkvPixelHeight = 0xBA, kMkvPixelCropBottom = 0x54AA, kMkvPixelCropTop = 0x54BB, kMkvPixelCropLeft = 0x54CC, kMkvPixelCropRight = 0x54DD, kMkvDisplayWidth = 0x54B0, kMkvDisplayHeight = 0x54BA, kMkvDisplayUnit = 0x54B2, kMkvAspectRatioType = 0x54B3, kMkvFrameRate = 0x2383E3, //end video //audio kMkvAudio = 0xE1, kMkvSamplingFrequency = 0xB5, kMkvOutputSamplingFrequency = 0x78B5, kMkvChannels = 0x9F, kMkvBitDepth = 0x6264, //end audio //ContentEncodings kMkvContentEncodings = 0x6D80, kMkvContentEncoding = 0x6240, kMkvContentEncodingOrder = 0x5031, kMkvContentEncodingScope = 0x5032, kMkvContentEncodingType = 0x5033, kMkvContentEncryption = 0x5035, kMkvContentEncAlgo = 0x47E1, kMkvContentEncKeyID = 0x47E2, kMkvContentEncAESSettings = 0x47E7, kMkvAESSettingsCipherMode = 0x47E8, kMkvAESSettingsCipherInitData = 0x47E9, //end ContentEncodings //Cueing Data kMkvCues = 0x1C53BB6B, kMkvCuePoint = 0xBB, kMkvCueTime = 0xB3, kMkvCueTrackPositions = 0xB7, kMkvCueTrack = 0xF7, kMkvCueClusterPosition = 0xF1, kMkvCueBlockNumber = 0x5378, //Chapters kMkvChapters = 0x1043A770, kMkvEditionEntry = 0x45B9, kMkvChapterAtom = 0xB6, kMkvChapterUID = 0x73C4, kMkvChapterStringUID = 0x5654, kMkvChapterTimeStart = 0x91, kMkvChapterTimeEnd = 0x92, kMkvChapterDisplay = 0x80, kMkvChapString = 0x85, kMkvChapLanguage = 0x437C, kMkvChapCountry = 0x437E }; } // end namespace mkvmuxer #endif // WEBMIDS_HPP <commit_msg>mkvmuxer: CRLF->LF webmids.h.<commit_after>// Copyright (c) 2012 The WebM 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 in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #ifndef WEBMIDS_HPP #define WEBMIDS_HPP namespace mkvmuxer { enum MkvId { kMkvEBML = 0x1A45DFA3, kMkvEBMLVersion = 0x4286, kMkvEBMLReadVersion = 0x42F7, kMkvEBMLMaxIDLength = 0x42F2, kMkvEBMLMaxSizeLength = 0x42F3, kMkvDocType = 0x4282, kMkvDocTypeVersion = 0x4287, kMkvDocTypeReadVersion = 0x4285, kMkvVoid = 0xEC, kMkvSignatureSlot = 0x1B538667, kMkvSignatureAlgo = 0x7E8A, kMkvSignatureHash = 0x7E9A, kMkvSignaturePublicKey = 0x7EA5, kMkvSignature = 0x7EB5, kMkvSignatureElements = 0x7E5B, kMkvSignatureElementList = 0x7E7B, kMkvSignedElement = 0x6532, //segment kMkvSegment = 0x18538067, //Meta Seek Information kMkvSeekHead = 0x114D9B74, kMkvSeek = 0x4DBB, kMkvSeekID = 0x53AB, kMkvSeekPosition = 0x53AC, //Segment Information kMkvInfo = 0x1549A966, kMkvTimecodeScale = 0x2AD7B1, kMkvDuration = 0x4489, kMkvDateUTC = 0x4461, kMkvMuxingApp = 0x4D80, kMkvWritingApp = 0x5741, //Cluster kMkvCluster = 0x1F43B675, kMkvTimecode = 0xE7, kMkvPrevSize = 0xAB, kMkvBlockGroup = 0xA0, kMkvBlock = 0xA1, kMkvBlockDuration = 0x9B, kMkvReferenceBlock = 0xFB, kMkvLaceNumber = 0xCC, kMkvSimpleBlock = 0xA3, kMkvBlockAdditions = 0x75A1, kMkvBlockMore = 0xA6, kMkvBlockAddID = 0xEE, kMkvBlockAdditional = 0xA5, //Track kMkvTracks = 0x1654AE6B, kMkvTrackEntry = 0xAE, kMkvTrackNumber = 0xD7, kMkvTrackUID = 0x73C5, kMkvTrackType = 0x83, kMkvFlagEnabled = 0xB9, kMkvFlagDefault = 0x88, kMkvFlagForced = 0x55AA, kMkvFlagLacing = 0x9C, kMkvDefaultDuration = 0x23E383, kMkvMaxBlockAdditionID = 0x55EE, kMkvName = 0x536E, kMkvLanguage = 0x22B59C, kMkvCodecID = 0x86, kMkvCodecPrivate = 0x63A2, kMkvCodecName = 0x258688, kMkvCodecDelay = 0x56AA, kMkvSeekPreRoll = 0x56BB, //video kMkvVideo = 0xE0, kMkvFlagInterlaced = 0x9A, kMkvStereoMode = 0x53B8, kMkvAlphaMode = 0x53C0, kMkvPixelWidth = 0xB0, kMkvPixelHeight = 0xBA, kMkvPixelCropBottom = 0x54AA, kMkvPixelCropTop = 0x54BB, kMkvPixelCropLeft = 0x54CC, kMkvPixelCropRight = 0x54DD, kMkvDisplayWidth = 0x54B0, kMkvDisplayHeight = 0x54BA, kMkvDisplayUnit = 0x54B2, kMkvAspectRatioType = 0x54B3, kMkvFrameRate = 0x2383E3, //end video //audio kMkvAudio = 0xE1, kMkvSamplingFrequency = 0xB5, kMkvOutputSamplingFrequency = 0x78B5, kMkvChannels = 0x9F, kMkvBitDepth = 0x6264, //end audio //ContentEncodings kMkvContentEncodings = 0x6D80, kMkvContentEncoding = 0x6240, kMkvContentEncodingOrder = 0x5031, kMkvContentEncodingScope = 0x5032, kMkvContentEncodingType = 0x5033, kMkvContentEncryption = 0x5035, kMkvContentEncAlgo = 0x47E1, kMkvContentEncKeyID = 0x47E2, kMkvContentEncAESSettings = 0x47E7, kMkvAESSettingsCipherMode = 0x47E8, kMkvAESSettingsCipherInitData = 0x47E9, //end ContentEncodings //Cueing Data kMkvCues = 0x1C53BB6B, kMkvCuePoint = 0xBB, kMkvCueTime = 0xB3, kMkvCueTrackPositions = 0xB7, kMkvCueTrack = 0xF7, kMkvCueClusterPosition = 0xF1, kMkvCueBlockNumber = 0x5378, //Chapters kMkvChapters = 0x1043A770, kMkvEditionEntry = 0x45B9, kMkvChapterAtom = 0xB6, kMkvChapterUID = 0x73C4, kMkvChapterStringUID = 0x5654, kMkvChapterTimeStart = 0x91, kMkvChapterTimeEnd = 0x92, kMkvChapterDisplay = 0x80, kMkvChapString = 0x85, kMkvChapLanguage = 0x437C, kMkvChapCountry = 0x437E }; } // end namespace mkvmuxer #endif // WEBMIDS_HPP <|endoftext|>
<commit_before>#include <lug/Graphic/Vulkan/Loader.hpp> namespace lug { namespace Graphic { namespace Vulkan { // TODO: Handle errors Loader::Loader() { #if defined(LUG_SYSTEM_WINDOWS) _handle = System::Library::open("vulkan-1.dll"); #else _handle = System::Library::open("libvulkan.so.1"); #endif #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = System::Library::sym<PFN_##name>(_handle, #name); LUG_EXPORTED_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(nullptr, #name)); LUG_CORE_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS } Loader::~Loader() { #define LUG_UNLOAD_VULKAN_FUNCTIONS(name) name = nullptr; LUG_EXPORTED_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_CORE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_INSTANCE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_DEVICE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); #undef LUG_UNLOAD_VULKAN_FUNCTIONS System::Library::close(_handle); } // TODO: Handle errors void Loader::loadInstanceFunctions(VkInstance instance) { #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(instance, #name)); LUG_INSTANCE_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS } } // Vulkan } // Graphic } // lug <commit_msg>Fix android vulkan loader name<commit_after>#include <lug/Graphic/Vulkan/Loader.hpp> namespace lug { namespace Graphic { namespace Vulkan { // TODO: Handle errors Loader::Loader() { #if defined(LUG_SYSTEM_WINDOWS) _handle = System::Library::open("vulkan-1.dll"); #elsif defined(LUG_SYSTEM_ANDROID) _handle = System::Library::open("libvulkan.so"); #else _handle = System::Library::open("libvulkan.so.1"); #endif #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = System::Library::sym<PFN_##name>(_handle, #name); LUG_EXPORTED_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(nullptr, #name)); LUG_CORE_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS } Loader::~Loader() { #define LUG_UNLOAD_VULKAN_FUNCTIONS(name) name = nullptr; LUG_EXPORTED_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_CORE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_INSTANCE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); LUG_DEVICE_VULKAN_FUNCTIONS(LUG_UNLOAD_VULKAN_FUNCTIONS); #undef LUG_UNLOAD_VULKAN_FUNCTIONS System::Library::close(_handle); } // TODO: Handle errors void Loader::loadInstanceFunctions(VkInstance instance) { #define LUG_LOAD_VULKAN_FUNCTIONS(name) name = reinterpret_cast<PFN_##name>(vkGetInstanceProcAddr(instance, #name)); LUG_INSTANCE_VULKAN_FUNCTIONS(LUG_LOAD_VULKAN_FUNCTIONS); #undef LUG_LOAD_VULKAN_FUNCTIONS } } // Vulkan } // Graphic } // lug <|endoftext|>
<commit_before>#include "ws2812b.h" int WS2812B_init(WS2812B *self, int pin, Colour *pixels, int flags, unsigned int columns, unsigned int rows) { if (digitalPinToPort(pin) == NOT_A_PIN) return 1; self->port = portOutputRegister(digitalPinToPort(pin)); self->bit = digitalPinToBitMask(pin); self->pin = pin; self->count = columns*rows; self->pixels = pixels; self->flags = flags; self->columns = columns; self->rows = rows; return 0; } void WS2812B_sync(WS2812B *self) { // https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf volatile uint16_t count = self->count*3; uint8_t *ptr = (uint8_t*)self->pixels; // Next byte ptr (initialized to first here) uint8_t byte = *ptr++; // Current byte uint8_t hi = *self->port | self->bit; // Cached high state uint8_t lo = *self->port & ~self->bit; // Cached low state volatile uint8_t next = lo; volatile uint8_t bit = 8; if (!count) return; cli(); // Disable interrupts // @TODO: Go through instruction set to see if we can relax the timing. // Note that the C code on the side is pseudo-pseudocode. // Some of the C code on the side would get optimsed, while some of it // can't be optimsed as effectively, which would significantly skew // the signal timing a WS281X chip expects. The timing here is on a very // tight schedule anyway, so we need to be careful. // // // See footnotes for extended descriptions. asm volatile ( "__colour_bit: \n\t" // __colour_bit: "st %a[port], %[hi] \n\t" // *port = hi; "sbrc %[byte], 7 \n\t\t" // if (byte & 0x80) "mov %[next], %[hi] \n\t" // next = hi; "dec %[bit] \n\t" // --bit; "st %a[port], %[next] \n\t" // *port = next; "mov %[next], %[lo] \n\t" // next = lo; "breq __colour_byte \n\t" // if (bit == 0) goto __colour_byte; // See [0] "lsl %[byte] \n\t" // byte = (byte << 1); "nop; nop; nop \n\t" // sleep_cycles(3); "st %a[port], %[lo] \n\t" // *port = lo; "nop; nop; nop \n\t" // sleep_cycles(3); "rjmp __colour_bit \n" // goto __colour_bit; // "__colour_byte: \n\t" // __colour_byte: "ldi %[bit], 8 \n\t" // bit = 8; "ld %[byte], %a[ptr]+ \n\t" // byte = *ptr++; "st %a[port], %[lo] \n\t" // *port = lo; "nop \n\t" // sleep_cycles(1); "sbiw %[count], 1 \n\t" // --count; "brne __colour_bit \n" // if (bit != 0) goto __colour_bit; // See [1] // The benefit of extended ASM is that we can define registers and // operands elegantly: : [port] "+e" (self->port), [count] "+w" (count), [bit] "+r" (bit), [byte] "+r" (byte), [next] "+r" (next) : [ptr] "e" (ptr), [hi] "r" (hi), [lo] "r" (lo) ); // Enable interrupts sei(); // Wait for *at least* 50µs; this causes the chip to latch the voltage onto // the individual LEDs contained within the RGB component. _delay_us(51); /** * # 1. `breq __colour_byte` * What this effectively does is test whether the Z flag in SREG register is * set to `1`, and if so, jumps to the defined symbol (`__colour_byte`). * * The Z flag (Zero flag) gets set when the previous arithmetic expression * evaluated to `0`. In our case, the last arithmetic expression was the * subtraction `dec %[bit]` (`--bit`). * * # 2. `brne __colour_bit` * This is similar to `breq`, but tests whether the Z flag in SREG is *not* * `1` before jumping. The flag gets cleared after the prevous arithmetic * expression evaluates to anything but `0`. * * --- * PS: "expression" is used as a synonym for "instruction" * * More detailed documentation can be found [here][doclink]. * * [doclink]: http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html */ } int WS2812B_set_pixel(WS2812B *self, unsigned int x, unsigned int y, Colour c) { return _WS2812B_spf(self, x, y, _WS2812B_cc(c, self->flags & WS2812B_SCHEMES)); } int WS2812B_set_pixel_at_offset(WS2812B *self, uint16_t offset, Colour c) { if (offset >= self->count) return 1; self->pixels[offset] = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); return 0; } int WS2812B_set_all(WS2812B *self, Colour c) { Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); uint16_t count = self->count; while (--count) self->pixels[count] = _c; return 0; } Colour WS2812B_get_pixel(WS2812B *self, unsigned int x, unsigned int y) { uint16_t offset = 0; if (x >= self->columns || y >= self->rows) return {0,0,0}; if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0) x = self->columns - x - 1; if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0) x = self->columns - x - 1; if(_WS2812B_addr(x, y, self->columns, &offset)) return {0,0,0}; return self->pixels[offset]; } int WS2812B_set_row(WS2812B *self, int row, Colour c) { if (row >= self->rows || row < 0) return 1; Colour _c = c; for (unsigned int i = 0; i < self->columns; i++) _WS2812B_spf(self, i, row, _c); return 0; } int WS2812B_set_column(WS2812B *self, int col, Colour c) { if (col >= self->columns || col < 0) return 1; Colour _c = c; for (unsigned int i = 0; i < self->rows; i++) _WS2812B_spf(self, col, i, _c); return 0; } /* Helper functions */ int _WS2812B_addr(unsigned int x, unsigned int y, unsigned int c, unsigned int *addr) { if (x >= c) return 1; *addr = c * y + x; return 0; } int _WS2812B_spf(WS2812B *self, unsigned int x, unsigned int y, Colour c) { uint16_t offset = 0; if (x >= self->columns || y >= self->rows) return 1; if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0) x = self->columns - x - 1; if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0) x = self->columns - x - 1; if(_WS2812B_addr(x, y, self->columns, &offset)) return 1; self->pixels[offset] = c; return 0; } unsigned int _WS2812B_x(unsigned int addr, unsigned int c) { return addr % c; } unsigned int _WS2812B_y(unsigned int addr, int c) { return addr / c; } Colour _WS2812B_cc(Colour c, int order) { switch (order) { case WS2812B_RBG: return {c.red, c.blue, c.green}; case WS2812B_GRB: return {c.green, c.red, c.blue}; case WS2812B_GBR: return {c.green, c.blue, c.red}; case WS2812B_BRG: return {c.blue, c.red, c.green}; case WS2812B_BGR: return {c.blue, c.green, c.red}; default /* RGB */: return c; } } <commit_msg>fix bug in column and row setting<commit_after>#include "ws2812b.h" int WS2812B_init(WS2812B *self, int pin, Colour *pixels, int flags, unsigned int columns, unsigned int rows) { if (digitalPinToPort(pin) == NOT_A_PIN) return 1; self->port = portOutputRegister(digitalPinToPort(pin)); self->bit = digitalPinToBitMask(pin); self->pin = pin; self->count = columns*rows; self->pixels = pixels; self->flags = flags; self->columns = columns; self->rows = rows; return 0; } void WS2812B_sync(WS2812B *self) { // https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf volatile uint16_t count = self->count*3; uint8_t *ptr = (uint8_t*)self->pixels; // Next byte ptr (initialized to first here) uint8_t byte = *ptr++; // Current byte uint8_t hi = *self->port | self->bit; // Cached high state uint8_t lo = *self->port & ~self->bit; // Cached low state volatile uint8_t next = lo; volatile uint8_t bit = 8; if (!count) return; cli(); // Disable interrupts // @TODO: Go through instruction set to see if we can relax the timing. // Note that the C code on the side is pseudo-pseudocode. // Some of the C code on the side would get optimsed, while some of it // can't be optimsed as effectively, which would significantly skew // the signal timing a WS281X chip expects. The timing here is on a very // tight schedule anyway, so we need to be careful. // // // See footnotes for extended descriptions. asm volatile ( "__colour_bit: \n\t" // __colour_bit: "st %a[port], %[hi] \n\t" // *port = hi; "sbrc %[byte], 7 \n\t\t" // if (byte & 0x80) "mov %[next], %[hi] \n\t" // next = hi; "dec %[bit] \n\t" // --bit; "st %a[port], %[next] \n\t" // *port = next; "mov %[next], %[lo] \n\t" // next = lo; "breq __colour_byte \n\t" // if (bit == 0) goto __colour_byte; // See [0] "lsl %[byte] \n\t" // byte = (byte << 1); "nop; nop; nop \n\t" // sleep_cycles(3); "st %a[port], %[lo] \n\t" // *port = lo; "nop; nop; nop \n\t" // sleep_cycles(3); "rjmp __colour_bit \n" // goto __colour_bit; // "__colour_byte: \n\t" // __colour_byte: "ldi %[bit], 8 \n\t" // bit = 8; "ld %[byte], %a[ptr]+ \n\t" // byte = *ptr++; "st %a[port], %[lo] \n\t" // *port = lo; "nop \n\t" // sleep_cycles(1); "sbiw %[count], 1 \n\t" // --count; "brne __colour_bit \n" // if (bit != 0) goto __colour_bit; // See [1] // The benefit of extended ASM is that we can define registers and // operands elegantly: : [port] "+e" (self->port), [count] "+w" (count), [bit] "+r" (bit), [byte] "+r" (byte), [next] "+r" (next) : [ptr] "e" (ptr), [hi] "r" (hi), [lo] "r" (lo) ); // Enable interrupts sei(); // Wait for *at least* 50µs; this causes the chip to latch the voltage onto // the individual LEDs contained within the RGB component. _delay_us(51); /** * # 1. `breq __colour_byte` * What this effectively does is test whether the Z flag in SREG register is * set to `1`, and if so, jumps to the defined symbol (`__colour_byte`). * * The Z flag (Zero flag) gets set when the previous arithmetic expression * evaluated to `0`. In our case, the last arithmetic expression was the * subtraction `dec %[bit]` (`--bit`). * * # 2. `brne __colour_bit` * This is similar to `breq`, but tests whether the Z flag in SREG is *not* * `1` before jumping. The flag gets cleared after the prevous arithmetic * expression evaluates to anything but `0`. * * --- * PS: "expression" is used as a synonym for "instruction" * * More detailed documentation can be found [here][doclink]. * * [doclink]: http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html */ } int WS2812B_set_pixel(WS2812B *self, unsigned int x, unsigned int y, Colour c) { return _WS2812B_spf(self, x, y, _WS2812B_cc(c, self->flags & WS2812B_SCHEMES)); } int WS2812B_set_pixel_at_offset(WS2812B *self, uint16_t offset, Colour c) { if (offset >= self->count) return 1; self->pixels[offset] = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); return 0; } int WS2812B_set_all(WS2812B *self, Colour c) { Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); uint16_t count = self->count; while (--count) self->pixels[count] = _c; return 0; } Colour WS2812B_get_pixel(WS2812B *self, unsigned int x, unsigned int y) { uint16_t offset = 0; if (x >= self->columns || y >= self->rows) return {0,0,0}; if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0) x = self->columns - x - 1; if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0) x = self->columns - x - 1; if(_WS2812B_addr(x, y, self->columns, &offset)) return {0,0,0}; return self->pixels[offset]; } int WS2812B_set_row(WS2812B *self, int row, Colour c) { if (row >= self->rows || row < 0) return 1; Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); for (unsigned int i = 0; i < self->columns; i++) _WS2812B_spf(self, i, row, _c); return 0; } int WS2812B_set_column(WS2812B *self, int col, Colour c) { if (col >= self->columns || col < 0) return 1; Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES); for (unsigned int i = 0; i < self->rows; i++) _WS2812B_spf(self, col, i, _c); return 0; } /* Helper functions */ int _WS2812B_addr(unsigned int x, unsigned int y, unsigned int c, unsigned int *addr) { if (x >= c) return 1; *addr = c * y + x; return 0; } int _WS2812B_spf(WS2812B *self, unsigned int x, unsigned int y, Colour c) { uint16_t offset = 0; if (x >= self->columns || y >= self->rows) return 1; if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0) x = self->columns - x - 1; if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0) x = self->columns - x - 1; if(_WS2812B_addr(x, y, self->columns, &offset)) return 1; self->pixels[offset] = c; return 0; } unsigned int _WS2812B_x(unsigned int addr, unsigned int c) { return addr % c; } unsigned int _WS2812B_y(unsigned int addr, int c) { return addr / c; } Colour _WS2812B_cc(Colour c, int order) { switch (order) { case WS2812B_RBG: return {c.red, c.blue, c.green}; case WS2812B_GRB: return {c.green, c.red, c.blue}; case WS2812B_GBR: return {c.green, c.blue, c.red}; case WS2812B_BRG: return {c.blue, c.red, c.green}; case WS2812B_BGR: return {c.blue, c.green, c.red}; default /* RGB */: return c; } } <|endoftext|>
<commit_before><?hh // strict /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Hprose/Service.hh * * * * hprose service library for hack. * * * * LastModified: Mar 8, 2015 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ namespace Hprose { class RemoteCall { public array<\ReflectionParameter> $params; public bool $byref; public function __construct(public mixed $func, public ResultMode $mode, public ?bool $simple) { if (is_array($func)) { $this->params = (new \ReflectionMethod($func[0], $func[1]))->getParameters(); } else { $this->params = (new \ReflectionFunction($func))->getParameters(); } $this->byref = false; foreach($this->params as $param) { if ($param->isPassedByReference()) { $this->byref = true; break; } } } } abstract class Service { private static array<string> $magic_methods = array( "__construct", "__destruct", "__call", "__callStatic", "__get", "__set", "__isset", "__unset", "__sleep", "__wakeup", "__toString", "__invoke", "__set_state", "__clone" ); private Map<string, RemoteCall> $calls = Map {}; private Vector<string> $names = Vector {}; private Vector<Filter> $filters = Vector {}; private bool $simple = false; protected bool $debug = false; protected int $error_types = E_ALL & ~E_NOTICE; public ?(function(string, array<mixed>, bool, \stdClass): void) $onBeforeInvoke = null; public ?(function(string, array<mixed>, bool, mixed, \stdClass): void) $onAfterInvoke = null; public ?(function(string, \stdClass): void) $onSendError = null; protected function inputFilter(string $data, \stdClass $context): string { $count = count($this->filters); for ($i = $count - 1; $i >= 0; $i--) { $data = $this->filters[$i]->inputFilter($data, $context); } return $data; } protected function outputFilter(string $data, \stdClass $context): string { $count = count($this->filters); for ($i = 0; $i < $count; $i++) { $data = $this->filters[$i]->outputFilter($data, $context); } return $data; } protected function sendError(string $error, \stdClass $context): string { if ($this->onSendError !== null) { $sendError = $this->onSendError; $sendError($error, $context); } $stream = new BytesIO(); $writer = new Writer($stream, true); $stream->write(Tags::TagError); $writer->writeString($error); $stream->write(Tags::TagEnd); $data = $stream->toString(); $stream->close(); return $this->outputFilter($data, $context); } protected function doInvoke(BytesIO $input, \stdClass $context): string { $output = new BytesIO(); $reader = new Reader($input); do { $reader->reset(); $name = (string)$reader->readString(); $alias = strtolower($name); if ($this->calls->contains($alias)) { $call = $this->calls[$alias]; } elseif ($this->calls->contains('*')) { $call = $this->calls['*']; } else { throw new \Exception("Can't find this function " . $name . "()."); } $mode = $call->mode; $simple = $call->simple; if ($simple === null) { $simple = $this->simple; } $args = array(); $byref = false; $tag = $input->getc(); if ($tag == Tags::TagList) { $reader->reset(); $args = $reader->readListWithoutTag()->toArray(); $tag = $input->getc(); if ($tag == Tags::TagTrue) { $byref = true; $tag = $input->getc(); } if ($call->byref) { $_args = array(); foreach($args as $i => &$arg) { if ($call->params[$i]->isPassedByReference()) { $_args[] = &$arg; } else { $_args[] = $arg; } } $args = $_args; } } if (($tag != Tags::TagEnd) && ($tag != Tags::TagCall)) { throw new \Exception('Unknown tag: ' . $tag . "\r\n" . 'with following data: ' . $input->toString()); } if ($this->onBeforeInvoke !== null) { $beforeInvoke = $this->onBeforeInvoke; $beforeInvoke($name, $args, $byref, $context); } if ($this->calls->contains('*') && $call === $this->calls['*']) { $args = array($name, $args); } $result = call_user_func_array($call->func, $args); if ($this->onAfterInvoke !== null) { $afterInvoke = $this->onAfterInvoke; $afterInvoke($name, $args, $byref, $result, $context); } // some service functions/methods may echo content, we need clean it @ob_clean(); if ($mode == ResultMode::RawWithEndTag) { return $this->outputFilter($result, $context); } elseif ($mode == ResultMode::Raw) { $output->write($result); } else { $writer = new Writer($output, $simple); $output->write(Tags::TagResult); if ($mode == ResultMode::Serialized) { $output->write($result); } else { $writer->reset(); $writer->serialize($result); } if ($byref) { $output->write(Tags::TagArgument); $writer->reset(); $writer->writeArray($args); } } } while ($tag == Tags::TagCall); $output->write(Tags::TagEnd); return $this->outputFilter($output->toString(), $context); } protected function doFunctionList(\stdClass $context): string { $stream = new BytesIO(); $writer = new Writer($stream, true); $stream->write(Tags::TagFunctions); $writer->writeList($this->names); $stream->write(Tags::TagEnd); $data = $stream->toString(); $stream->close(); return $this->outputFilter($data, $context); } private static function getDeclaredOnlyMethods(string $class): array<string> { $result = get_class_methods($class); if ($parent_class = get_parent_class($class)) { $inherit = get_class_methods($parent_class); $result = array_diff($result, $inherit); } $result = array_diff($result, self::$magic_methods); return $result; } public function addMissingFunction(mixed $func, ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $this->addFunction($func, '*', $mode, $simple); } public function addFunction(mixed $func, string $alias = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if (!is_callable($func)) { throw new \Exception('Argument func is not callable.'); } if ($alias == '') { if (is_string($func)) { $alias = $func; } elseif (is_array($func)) { $alias = $func[1]; } else { throw new \Exception('alias must be a string.'); } } $name = strtolower($alias); if (!$this->calls->contains($name)) { $this->names->add($alias); } $this->calls[$name] = new RemoteCall($func, $mode, $simple); } public function addFunctions(array<mixed> $funcs, array<string> $aliases = array(), ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $count = count($aliases); if ($count == 0) { foreach ($funcs as $func) { $this->addFunction($func, '', $mode, $simple); } } elseif ($count == count($funcs)) { foreach ($funcs as $i => $func) { $this->addFunction($func, $aliases[$i], $mode, $simple); } } else { throw new \Exception('The count of functions is not matched with aliases'); } } public function addMethod(string $methodname, mixed $belongto, string $alias = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $func = array($belongto, $methodname); $this->addFunction($func, $alias, $mode, $simple); } public function addMethods(array<string> $methods, mixed $belongto, mixed $aliases = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($aliases === null || count($aliases) == 0) { $aliases = ''; } $_aliases = array(); if (is_string($aliases)) { $aliasPrefix = $aliases; if ($aliasPrefix !== '') { $aliasPrefix .= '_'; } foreach ($methods as $k => $method) { $_aliases[$k] = $aliasPrefix . $method; } } elseif (is_array($aliases)) { $_aliases = $aliases; } elseif ($aliases instanceof \Indexish) { $_aliases = $aliases; } if (count($methods) != count($_aliases)) { throw new \Exception('The count of methods is not matched with aliases'); } foreach($methods as $k => $method) { $func = array($belongto, $method); $this->addFunction($func, $_aliases[$k], $mode, $simple); } } public function addInstanceMethods(mixed $object, string $class = '', string $aliasPrefix = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($class == '') { $class = get_class($object); } $this->addMethods(self::getDeclaredOnlyMethods($class), $object, $aliasPrefix, $mode, $simple); } public function addClassMethods(string $class, string $execclass = '', string $aliasPrefix = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($execclass == '') { $execclass = $class; } $this->addMethods(self::getDeclaredOnlyMethods($class), $execclass, $aliasPrefix, $mode, $simple); } public function add(...): void { $args_num = func_num_args(); $args = func_get_args(); switch ($args_num) { case 1: { if (is_callable($args[0])) { $this->addFunction($args[0]); return; } elseif (is_array($args[0])) { $this->addFunctions($args[0]); return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0]); return; } elseif (is_string($args[0])) { $this->addClassMethods($args[0]); return; } break; } case 2: { if (is_callable($args[0]) && is_string($args[1])) { $this->addFunction($args[0], $args[1]); return; } elseif (is_string($args[0])) { if (is_string($args[1]) && !is_callable(array($args[1], $args[0]))) { if (class_exists($args[1])) { $this->addClassMethods($args[0], $args[1]); } else { $this->addClassMethods($args[0], '', $args[1]); } } else { $this->addMethod($args[0], $args[1]); } return; } elseif (is_array($args[0])) { if (is_array($args[1])) { $this->addFunctions($args[0], $args[1]); } else { $this->addMethods($args[0], $args[1]); } return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0], $args[1]); return; } break; } case 3: { if (is_callable($args[0]) && $args[1] == '' && is_string($args[2])) { $this->addFunction($args[0], $args[2]); return; } elseif (is_string($args[0]) && is_string($args[2])) { if (is_string($args[1]) && !is_callable(array($args[0], $args[1]))) { $this->addClassMethods($args[0], $args[1], $args[2]); } else { $this->addMethod($args[0], $args[1], $args[2]); } return; } elseif (is_array($args[0])) { if ($args[1] == '' && is_array($args[2])) { $this->addFunctions($args[0], $args[2]); } else { $this->addMethods($args[0], $args[1], $args[2]); } return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0], $args[1], $args[2]); return; } break; } throw new \Exception('Wrong arguments'); } } public function isDebugEnabled(): bool { return $this->debug; } public function setDebugEnabled(bool $enable = true): void { $this->debug = $enable; } public function getFilter(): ?Filter { if (count($this->filters) === 0) { return null; } return $this->filters[0]; } public function setFilter(Filter $filter): void { $this->filters->clear(); if ($filter !== null) { $this->filters->add($filter); } } public function addFilter(Filter $filter): void { $this->filters->add($filter); } public function removeFilter(Filter $filter): bool { $i = $this->filters->linearSearch($filter); if ($i === -1) { return false; } $this->filters->removeKey($i); return true; } public function getSimpleMode(): bool { return $this->simple; } public function setSimpleMode(bool $simple = true): void { $this->simple = $simple; } public function getErrorTypes(): int { return $this->error_types; } public function setErrorTypes(int $error_types): void { $this->error_types = $error_types; } public function defaultHandle(string $request, \stdClass $context): string { $input = new BytesIO($this->inputFilter($request, $context)); try { switch ($input->getc()) { case Tags::TagCall: return $this->doInvoke($input, $context); case Tags::TagEnd: return $this->doFunctionList($context); default: throw new \Exception("Wrong Request: \r\n" . $request); } } catch (\Exception $e) { $error = $e->getMessage(); if ($this->debug) { $error .= "\nfile: " . $e->getFile() . "\nline: " . $e->getLine() . "\ntrace: " . $e->getTraceAsString(); } return $this->sendError($error, $context); } } } } <commit_msg>Removed unnecessary ob_clean()<commit_after><?hh // strict /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Hprose/Service.hh * * * * hprose service library for hack. * * * * LastModified: Mar 28, 2015 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ namespace Hprose { class RemoteCall { public array<\ReflectionParameter> $params; public bool $byref; public function __construct(public mixed $func, public ResultMode $mode, public ?bool $simple) { if (is_array($func)) { $this->params = (new \ReflectionMethod($func[0], $func[1]))->getParameters(); } else { $this->params = (new \ReflectionFunction($func))->getParameters(); } $this->byref = false; foreach($this->params as $param) { if ($param->isPassedByReference()) { $this->byref = true; break; } } } } abstract class Service { private static array<string> $magic_methods = array( "__construct", "__destruct", "__call", "__callStatic", "__get", "__set", "__isset", "__unset", "__sleep", "__wakeup", "__toString", "__invoke", "__set_state", "__clone" ); private Map<string, RemoteCall> $calls = Map {}; private Vector<string> $names = Vector {}; private Vector<Filter> $filters = Vector {}; private bool $simple = false; protected bool $debug = false; protected int $error_types = E_ALL & ~E_NOTICE; public ?(function(string, array<mixed>, bool, \stdClass): void) $onBeforeInvoke = null; public ?(function(string, array<mixed>, bool, mixed, \stdClass): void) $onAfterInvoke = null; public ?(function(string, \stdClass): void) $onSendError = null; protected function inputFilter(string $data, \stdClass $context): string { $count = count($this->filters); for ($i = $count - 1; $i >= 0; $i--) { $data = $this->filters[$i]->inputFilter($data, $context); } return $data; } protected function outputFilter(string $data, \stdClass $context): string { $count = count($this->filters); for ($i = 0; $i < $count; $i++) { $data = $this->filters[$i]->outputFilter($data, $context); } return $data; } protected function sendError(string $error, \stdClass $context): string { if ($this->onSendError !== null) { $sendError = $this->onSendError; $sendError($error, $context); } $stream = new BytesIO(); $writer = new Writer($stream, true); $stream->write(Tags::TagError); $writer->writeString($error); $stream->write(Tags::TagEnd); $data = $stream->toString(); $stream->close(); return $this->outputFilter($data, $context); } protected function doInvoke(BytesIO $input, \stdClass $context): string { $output = new BytesIO(); $reader = new Reader($input); do { $reader->reset(); $name = (string)$reader->readString(); $alias = strtolower($name); if ($this->calls->contains($alias)) { $call = $this->calls[$alias]; } elseif ($this->calls->contains('*')) { $call = $this->calls['*']; } else { throw new \Exception("Can't find this function " . $name . "()."); } $mode = $call->mode; $simple = $call->simple; if ($simple === null) { $simple = $this->simple; } $args = array(); $byref = false; $tag = $input->getc(); if ($tag == Tags::TagList) { $reader->reset(); $args = $reader->readListWithoutTag()->toArray(); $tag = $input->getc(); if ($tag == Tags::TagTrue) { $byref = true; $tag = $input->getc(); } if ($call->byref) { $_args = array(); foreach($args as $i => &$arg) { if ($call->params[$i]->isPassedByReference()) { $_args[] = &$arg; } else { $_args[] = $arg; } } $args = $_args; } } if (($tag != Tags::TagEnd) && ($tag != Tags::TagCall)) { throw new \Exception('Unknown tag: ' . $tag . "\r\n" . 'with following data: ' . $input->toString()); } if ($this->onBeforeInvoke !== null) { $beforeInvoke = $this->onBeforeInvoke; $beforeInvoke($name, $args, $byref, $context); } if ($this->calls->contains('*') && $call === $this->calls['*']) { $args = array($name, $args); } $result = call_user_func_array($call->func, $args); if ($this->onAfterInvoke !== null) { $afterInvoke = $this->onAfterInvoke; $afterInvoke($name, $args, $byref, $result, $context); } if ($mode == ResultMode::RawWithEndTag) { return $this->outputFilter($result, $context); } elseif ($mode == ResultMode::Raw) { $output->write($result); } else { $writer = new Writer($output, $simple); $output->write(Tags::TagResult); if ($mode == ResultMode::Serialized) { $output->write($result); } else { $writer->reset(); $writer->serialize($result); } if ($byref) { $output->write(Tags::TagArgument); $writer->reset(); $writer->writeArray($args); } } } while ($tag == Tags::TagCall); $output->write(Tags::TagEnd); return $this->outputFilter($output->toString(), $context); } protected function doFunctionList(\stdClass $context): string { $stream = new BytesIO(); $writer = new Writer($stream, true); $stream->write(Tags::TagFunctions); $writer->writeList($this->names); $stream->write(Tags::TagEnd); $data = $stream->toString(); $stream->close(); return $this->outputFilter($data, $context); } private static function getDeclaredOnlyMethods(string $class): array<string> { $result = get_class_methods($class); if ($parent_class = get_parent_class($class)) { $inherit = get_class_methods($parent_class); $result = array_diff($result, $inherit); } $result = array_diff($result, self::$magic_methods); return $result; } public function addMissingFunction(mixed $func, ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $this->addFunction($func, '*', $mode, $simple); } public function addFunction(mixed $func, string $alias = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if (!is_callable($func)) { throw new \Exception('Argument func is not callable.'); } if ($alias == '') { if (is_string($func)) { $alias = $func; } elseif (is_array($func)) { $alias = $func[1]; } else { throw new \Exception('alias must be a string.'); } } $name = strtolower($alias); if (!$this->calls->contains($name)) { $this->names->add($alias); } $this->calls[$name] = new RemoteCall($func, $mode, $simple); } public function addFunctions(array<mixed> $funcs, array<string> $aliases = array(), ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $count = count($aliases); if ($count == 0) { foreach ($funcs as $func) { $this->addFunction($func, '', $mode, $simple); } } elseif ($count == count($funcs)) { foreach ($funcs as $i => $func) { $this->addFunction($func, $aliases[$i], $mode, $simple); } } else { throw new \Exception('The count of functions is not matched with aliases'); } } public function addMethod(string $methodname, mixed $belongto, string $alias = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { $func = array($belongto, $methodname); $this->addFunction($func, $alias, $mode, $simple); } public function addMethods(array<string> $methods, mixed $belongto, mixed $aliases = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($aliases === null || count($aliases) == 0) { $aliases = ''; } $_aliases = array(); if (is_string($aliases)) { $aliasPrefix = $aliases; if ($aliasPrefix !== '') { $aliasPrefix .= '_'; } foreach ($methods as $k => $method) { $_aliases[$k] = $aliasPrefix . $method; } } elseif (is_array($aliases)) { $_aliases = $aliases; } elseif ($aliases instanceof \Indexish) { $_aliases = $aliases; } if (count($methods) != count($_aliases)) { throw new \Exception('The count of methods is not matched with aliases'); } foreach($methods as $k => $method) { $func = array($belongto, $method); $this->addFunction($func, $_aliases[$k], $mode, $simple); } } public function addInstanceMethods(mixed $object, string $class = '', string $aliasPrefix = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($class == '') { $class = get_class($object); } $this->addMethods(self::getDeclaredOnlyMethods($class), $object, $aliasPrefix, $mode, $simple); } public function addClassMethods(string $class, string $execclass = '', string $aliasPrefix = '', ResultMode $mode = ResultMode::Normal, ?bool $simple = null): void { if ($execclass == '') { $execclass = $class; } $this->addMethods(self::getDeclaredOnlyMethods($class), $execclass, $aliasPrefix, $mode, $simple); } public function add(...): void { $args_num = func_num_args(); $args = func_get_args(); switch ($args_num) { case 1: { if (is_callable($args[0])) { $this->addFunction($args[0]); return; } elseif (is_array($args[0])) { $this->addFunctions($args[0]); return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0]); return; } elseif (is_string($args[0])) { $this->addClassMethods($args[0]); return; } break; } case 2: { if (is_callable($args[0]) && is_string($args[1])) { $this->addFunction($args[0], $args[1]); return; } elseif (is_string($args[0])) { if (is_string($args[1]) && !is_callable(array($args[1], $args[0]))) { if (class_exists($args[1])) { $this->addClassMethods($args[0], $args[1]); } else { $this->addClassMethods($args[0], '', $args[1]); } } else { $this->addMethod($args[0], $args[1]); } return; } elseif (is_array($args[0])) { if (is_array($args[1])) { $this->addFunctions($args[0], $args[1]); } else { $this->addMethods($args[0], $args[1]); } return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0], $args[1]); return; } break; } case 3: { if (is_callable($args[0]) && $args[1] == '' && is_string($args[2])) { $this->addFunction($args[0], $args[2]); return; } elseif (is_string($args[0]) && is_string($args[2])) { if (is_string($args[1]) && !is_callable(array($args[0], $args[1]))) { $this->addClassMethods($args[0], $args[1], $args[2]); } else { $this->addMethod($args[0], $args[1], $args[2]); } return; } elseif (is_array($args[0])) { if ($args[1] == '' && is_array($args[2])) { $this->addFunctions($args[0], $args[2]); } else { $this->addMethods($args[0], $args[1], $args[2]); } return; } elseif (is_object($args[0])) { $this->addInstanceMethods($args[0], $args[1], $args[2]); return; } break; } throw new \Exception('Wrong arguments'); } } public function isDebugEnabled(): bool { return $this->debug; } public function setDebugEnabled(bool $enable = true): void { $this->debug = $enable; } public function getFilter(): ?Filter { if (count($this->filters) === 0) { return null; } return $this->filters[0]; } public function setFilter(Filter $filter): void { $this->filters->clear(); if ($filter !== null) { $this->filters->add($filter); } } public function addFilter(Filter $filter): void { $this->filters->add($filter); } public function removeFilter(Filter $filter): bool { $i = $this->filters->linearSearch($filter); if ($i === -1) { return false; } $this->filters->removeKey($i); return true; } public function getSimpleMode(): bool { return $this->simple; } public function setSimpleMode(bool $simple = true): void { $this->simple = $simple; } public function getErrorTypes(): int { return $this->error_types; } public function setErrorTypes(int $error_types): void { $this->error_types = $error_types; } public function defaultHandle(string $request, \stdClass $context): string { $input = new BytesIO($this->inputFilter($request, $context)); try { switch ($input->getc()) { case Tags::TagCall: return $this->doInvoke($input, $context); case Tags::TagEnd: return $this->doFunctionList($context); default: throw new \Exception("Wrong Request: \r\n" . $request); } } catch (\Exception $e) { $error = $e->getMessage(); if ($this->debug) { $error .= "\nfile: " . $e->getFile() . "\nline: " . $e->getLine() . "\ntrace: " . $e->getTraceAsString(); } return $this->sendError($error, $context); } } } } <|endoftext|>
<commit_before>// -*- mode: c++ , encoding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée (maandree@kth.se) * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BasicSenario.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <maandree@kth.se> */ namespace tbrpg { /** * Constructor */ BasicSenario::BasicSenario() : Senario() { this->rules->party_size = 3; this->rules->party_start_size = 3; this->rules->inventory_prototype->personal[0] = new Gold(); this->rules->inventory_prototype->personal[0]->quantity = 400; cleaner::getInstance().enqueueDelete(this->rules->inventory_prototype->personal[0]); MapMajor* map_town = new MapMajor(); MapMajor* map_wilds = new MapMajor(); MapMinor* area_inn = new House(); MapMinor* area_town = new Town(); MapMinor* area_wilds = new Wilderness(); MapMinor* area_goal = new Wilderness(); map_town->name = "The town"; map_town->visible = true; map_town->visited = true; map_town->visitable = true; map_wilds->name = "Outside the town"; map_wilds->visible = false; map_wilds->visited = false; map_wilds->visitable = true; map_wilds->detectable = true; area_inn->description = "You are standing in an inn."; area_inn->area = 40; (area_inn->is_in = map_town)->minors->push_back(area_inn); area_town->description = "You are standing in the marketplace."; area_town->area = 80; area_town->is_in = map_town; (area_town->is_in = map_town)->minors->push_back(area_town); area_wilds->description = "You are out on the open roads."; area_wilds->area = 80; area_wilds->is_in = map_wilds; (area_wilds->is_in = map_wilds)->minors->push_back(area_goal); area_goal->description = "You are in the wilderness."; area_goal->area = 80; area_goal->is_in = map_wilds; (area_goal->is_in = map_wilds)->minors->push_back(area_wilds); Road* road_out = new Road(); Road* road_in = new Road(); road_out->first_distance = road_in->last_distance = 1000; road_out->last_distance = road_in->first_distance = 1000; road_out->waylay_die = road_out->waylay_dice = 1; road_out->waylay_risk = 0; road_in->waylay_die = road_in->waylay_dice = 1; road_in->waylay_risk = 0; road_out->direction = "south"; road_in->direction = "north"; road_out->leads_to = area_wilds; road_in->leads_to = area_town; area_town->roads.push_back(road_out); area_wilds->roads.push_back(road_in); Door* door_in = new Door(); Door* door_out = new Door(); door_in->usable = true; door_out->usable = true; door_in->locked = false; door_out->locked = false; door_in->direction = "inn"; door_out->direction = "town"; door_in->description = "inn, you can rest safely here and get equipment"; door_out->description = "the town"; door_in->leads_to = area_inn; door_out->leads_to = area_town; area_town->connections.push_back(door_in); area_inn->connections.push_back(door_out); Entrance* next = new Entrance(); Entrance* prev = new Entrance(); next->usable = true; prev->usable = true; next->direction = "south"; prev->direction = "north"; next->description = "the wilderness"; prev->description = "the open roads"; next->leads_to = area_goal; prev->leads_to = area_wilds; area_goal->connections.push_back(prev); area_wilds->connections.push_back(next); Store* store = new Store(); area_inn->creatures.push_back(store); this->map->start = area_town; this->map->majors->push_back(map_town); this->map->majors->push_back(map_wilds); store->room_costs.push_back(1); store->room_quality.push_back(2); store->room_costs.push_back(2); store->room_quality.push_back(4); store->room_costs.push_back(4); store->room_quality.push_back(8); store->room_costs.push_back(8); store->room_quality.push_back(16); store->record.race = &PROTOTYPE(Human); store->record.prestige.push_back(&PROTOTYPE(Fighter)); store->inventory.push_back(&PROTOTYPE(ShortSword)); store->inventory.push_back(&PROTOTYPE(LongSword)); store->inventory.push_back(&PROTOTYPE(Bullet)); store->inventory.push_back(&PROTOTYPE(Sling)); store->inventory.push_back(&PROTOTYPE(ChainMail)); store->inventory.push_back(&PROTOTYPE(Helmet)); for (Item* item : store->inventory) item->quantity = -1; Key* questkey = new Key(); questkey->id = 0; cleaner::getInstance().enqueueDelete(questkey); Creature* gibberling = new Creature(); area_wilds->creatures.push_back(gibberling); gibberling->x = 50; gibberling->y = 50; gibberling->alive = true; gibberling->resurrect = false; gibberling->experience = 10; gibberling->record.name = "gibberling"; gibberling->record.colour = 2; gibberling->record.alignment = 4; gibberling->record.inventory.personal.push_back(questkey); gibberling->record.race = &PROTOTYPE(Human); gibberling->record.prestige.push_back(&PROTOTYPE(Fighter)); } /** * Copy constructor * * @param original The object to clone */ BasicSenario::BasicSenario(const BasicSenario& original) : Senario(original) { (void) original; } /** * Copy constructor * * @param original The object to clone */ BasicSenario::BasicSenario(BasicSenario& original) : Senario(original) { (void) original; } /** * Move constructor * * @param original The object to clone */ BasicSenario::BasicSenario(BasicSenario&& original) : Senario(original) { (void) original; } /** * Fork the object * * @return A fork of the object */ Object* BasicSenario::fork() const { return (Object*)(new BasicSenario(*this)); } /** * Destructor */ BasicSenario::~BasicSenario() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ BasicSenario& BasicSenario::operator =(const BasicSenario& original) { Object::__copy__((Senario&)*this, (Senario&)original); return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ BasicSenario& BasicSenario::operator =(BasicSenario& original) { Object::__copy__((Senario&)*this, (Senario&)original); return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ BasicSenario& BasicSenario::operator =(BasicSenario&& original) { std::swap((Senario&)*this, (Senario&)original); return *this; } /** * This is invoked when the senario starts. * The prologue, and perhaps a short tutorial, * should be displayed. */ void BasicSenario::start() { page("This is a simple demo senario.\n" "\n" "You stand outside an inn, where you purchase items such as" "\n" "armour and weapons that your need in your quest. You mission" "\n" "is to the legendary sword known as Sword of Legends."); promptDialogue(2, "Tutor", "examine map :: Examine you world map" "\n" "examine area :: Examine the area" "\n" "examine party :: Examine your character's abilities and spellbooks" "\n" "examine inventory :: Open your inventorty, and pick up items" "\n" "turn undead [off] :: Turn on or off Turn Undead (special ability)" "\n" "find traps [off] :: Turn on or off Find Traps (special ability)" "\n" "stealth [off] :: Turn on or off Stealth Mode (special ability)" "\n" "pick pocket :: Pick pocket a NPC (special ability)" "\n" "disarm :: Disarm a found trap (special ability)" "\n" "unlock :: Unlock a door or chest (special ability)" "\n" "bash :: Bash a door or chest" "\n" "specials :: List other special ability commands you can use" "\n" "talk :: Talk to a NPC" "\n" "travel :: Go in some direction" "\n" "cast *** :: Cast a *** spell" "\n" "cast :: Cast a non-quick spell" "\n" "attack :: Attack with you current weapon" "\n" "weapon :: Change your current weapon" "\n" "quiver :: Change the ammunition to use from you quiver" "\n" "rest :: Rest, you party must be gathered" "\n" "! :: Redo the last action that was not a wait action" "\n" ". :: Wait a turn" "\n" "quit :: Stop playing", {}); } /** * Gets the name of the game senario * * @return The name of the game senario */ std::string BasicSenario::getTitle() { return "Basic game senario demo"; } } <commit_msg>m command intro<commit_after>// -*- mode: c++ , encoding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée (maandree@kth.se) * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BasicSenario.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <maandree@kth.se> */ namespace tbrpg { /** * Constructor */ BasicSenario::BasicSenario() : Senario() { this->rules->party_size = 3; this->rules->party_start_size = 3; this->rules->inventory_prototype->personal[0] = new Gold(); this->rules->inventory_prototype->personal[0]->quantity = 400; cleaner::getInstance().enqueueDelete(this->rules->inventory_prototype->personal[0]); MapMajor* map_town = new MapMajor(); MapMajor* map_wilds = new MapMajor(); MapMinor* area_inn = new House(); MapMinor* area_town = new Town(); MapMinor* area_wilds = new Wilderness(); MapMinor* area_goal = new Wilderness(); map_town->name = "The town"; map_town->visible = true; map_town->visited = true; map_town->visitable = true; map_wilds->name = "Outside the town"; map_wilds->visible = false; map_wilds->visited = false; map_wilds->visitable = true; map_wilds->detectable = true; area_inn->description = "You are standing in an inn."; area_inn->area = 40; (area_inn->is_in = map_town)->minors->push_back(area_inn); area_town->description = "You are standing in the marketplace."; area_town->area = 80; area_town->is_in = map_town; (area_town->is_in = map_town)->minors->push_back(area_town); area_wilds->description = "You are out on the open roads."; area_wilds->area = 80; area_wilds->is_in = map_wilds; (area_wilds->is_in = map_wilds)->minors->push_back(area_goal); area_goal->description = "You are in the wilderness."; area_goal->area = 80; area_goal->is_in = map_wilds; (area_goal->is_in = map_wilds)->minors->push_back(area_wilds); Road* road_out = new Road(); Road* road_in = new Road(); road_out->first_distance = road_in->last_distance = 1000; road_out->last_distance = road_in->first_distance = 1000; road_out->waylay_die = road_out->waylay_dice = 1; road_out->waylay_risk = 0; road_in->waylay_die = road_in->waylay_dice = 1; road_in->waylay_risk = 0; road_out->direction = "south"; road_in->direction = "north"; road_out->leads_to = area_wilds; road_in->leads_to = area_town; area_town->roads.push_back(road_out); area_wilds->roads.push_back(road_in); Door* door_in = new Door(); Door* door_out = new Door(); door_in->usable = true; door_out->usable = true; door_in->locked = false; door_out->locked = false; door_in->direction = "inn"; door_out->direction = "town"; door_in->description = "inn, you can rest safely here and get equipment"; door_out->description = "the town"; door_in->leads_to = area_inn; door_out->leads_to = area_town; area_town->connections.push_back(door_in); area_inn->connections.push_back(door_out); Entrance* next = new Entrance(); Entrance* prev = new Entrance(); next->usable = true; prev->usable = true; next->direction = "south"; prev->direction = "north"; next->description = "the wilderness"; prev->description = "the open roads"; next->leads_to = area_goal; prev->leads_to = area_wilds; area_goal->connections.push_back(prev); area_wilds->connections.push_back(next); Store* store = new Store(); area_inn->creatures.push_back(store); this->map->start = area_town; this->map->majors->push_back(map_town); this->map->majors->push_back(map_wilds); store->room_costs.push_back(1); store->room_quality.push_back(2); store->room_costs.push_back(2); store->room_quality.push_back(4); store->room_costs.push_back(4); store->room_quality.push_back(8); store->room_costs.push_back(8); store->room_quality.push_back(16); store->record.race = &PROTOTYPE(Human); store->record.prestige.push_back(&PROTOTYPE(Fighter)); store->inventory.push_back(&PROTOTYPE(ShortSword)); store->inventory.push_back(&PROTOTYPE(LongSword)); store->inventory.push_back(&PROTOTYPE(Bullet)); store->inventory.push_back(&PROTOTYPE(Sling)); store->inventory.push_back(&PROTOTYPE(ChainMail)); store->inventory.push_back(&PROTOTYPE(Helmet)); for (Item* item : store->inventory) item->quantity = -1; Key* questkey = new Key(); questkey->id = 0; cleaner::getInstance().enqueueDelete(questkey); Creature* gibberling = new Creature(); area_wilds->creatures.push_back(gibberling); gibberling->x = 50; gibberling->y = 50; gibberling->alive = true; gibberling->resurrect = false; gibberling->experience = 10; gibberling->record.name = "gibberling"; gibberling->record.colour = 2; gibberling->record.alignment = 4; gibberling->record.inventory.personal.push_back(questkey); gibberling->record.race = &PROTOTYPE(Human); gibberling->record.prestige.push_back(&PROTOTYPE(Fighter)); } /** * Copy constructor * * @param original The object to clone */ BasicSenario::BasicSenario(const BasicSenario& original) : Senario(original) { (void) original; } /** * Copy constructor * * @param original The object to clone */ BasicSenario::BasicSenario(BasicSenario& original) : Senario(original) { (void) original; } /** * Move constructor * * @param original The object to clone */ BasicSenario::BasicSenario(BasicSenario&& original) : Senario(original) { (void) original; } /** * Fork the object * * @return A fork of the object */ Object* BasicSenario::fork() const { return (Object*)(new BasicSenario(*this)); } /** * Destructor */ BasicSenario::~BasicSenario() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ BasicSenario& BasicSenario::operator =(const BasicSenario& original) { Object::__copy__((Senario&)*this, (Senario&)original); return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ BasicSenario& BasicSenario::operator =(BasicSenario& original) { Object::__copy__((Senario&)*this, (Senario&)original); return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ BasicSenario& BasicSenario::operator =(BasicSenario&& original) { std::swap((Senario&)*this, (Senario&)original); return *this; } /** * This is invoked when the senario starts. * The prologue, and perhaps a short tutorial, * should be displayed. */ void BasicSenario::start() { page("This is a simple demo senario.\n" "\n" "You stand outside an inn, where you purchase items such as" "\n" "armour and weapons that your need in your quest. You mission" "\n" "is to the legendary sword known as Sword of Legends."); promptDialogue(2, "Tutor", "examine map :: Examine you world map" "\n" "examine area :: Examine the area" "\n" "examine party :: Examine your character's abilities and spellbooks" "\n" "examine inventory :: Open your inventorty, and pick up items" "\n" "turn undead [off] :: Turn on or off Turn Undead (special ability)" "\n" "find traps [off] :: Turn on or off Find Traps (special ability)" "\n" "stealth [off] :: Turn on or off Stealth Mode (special ability)" "\n" "bard song [off] :: Turn on or off Bard Song (special ability)" "\n" "pick pocket :: Pick pocket a NPC (special ability)" "\n" "disarm :: Disarm a found trap (special ability)" "\n" "unlock :: Unlock a door or chest (special ability)" "\n" "bash :: Bash a door or chest" "\n" "specials :: List other special ability commands you can use" "\n" "talk :: Talk to a NPC" "\n" "travel :: Go in some direction" "\n" "cast :: Cast a spell" "\n" "attack :: Attack with you current weapon" "\n" "weapon :: Change your current weapon" "\n" "quiver :: Change the ammunition to use from you quiver" "\n" "rest :: Rest, you party must be gathered" "\n" "! :: Redo the last action that was not a wait action" "\n" ". :: Wait a turn" "\n" "quit :: Stop playing", {}); } /** * Gets the name of the game senario * * @return The name of the game senario */ std::string BasicSenario::getTitle() { return "Basic game senario demo"; } } <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <cstdint> #include <cstdlib> #include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <string> using std::atof; using std::count; using std::cout; using std::cerr; using std::endl; using std::getline; using std::string; using std::stringstream; using std::ifstream; using cv::filter2D; using cv::imread; using cv::Mat; using cv::namedWindow; using cv::Rect; using cv::waitKey; namespace { /* \brief カーネルへオペレータをセット。 \param row カーネルの行 \param line ファイルから読み込まれた文字列 \param size カーネルのサイズ */ void SetOperator(Mat row, const string& line, uint64_t size) { stringstream line_stream(line); for (uint64_t i = 0; i < size; ++i) { if (line_stream.good() && !line_stream.eof()) { string op; getline(line_stream, op, ','); // オペレータをセット row.at<double>(i) = static_cast<double>(atof(op.c_str())); } else { break; } } }; /*! \brief ファイルを読み込み、カーネルを取得する。 \param filename カーネルを表したCSVのファイル名 \return カーネル。エラーが起きた場合は空の画像 */ Mat GetKernel(const string& filename) { ifstream stream; stream.open(filename); if (stream.good()) { string line; getline(stream, line); // 最初の行からフィルタサイズを取得。 uint64_t size = count(line.begin(), line.end(), ',') + 1; // カーネルの領域を確保 Mat kernel = Mat::zeros(size, size, cv::DataType<double>::type); if (kernel.data == NULL) { return Mat(); } else { SetOperator(kernel.row(0), line, size); for (uint64_t i = 1; i < size; ++i) { if (stream.good() && !stream.eof()) { getline(stream, line); SetOperator(kernel.row(i), line, size); } else { break; } } return kernel; } } else { return Mat(); } } /*! \brief 画像をカーネルに基づいた線形フィルタをかける。 \param src 元画像 \param kernel カーネル \return フィルタされた画像。元画像かカーネルにエラーがある場合、空の画像 */ Mat Filter(const Mat& src, const Mat& kernel) { if (src.data != NULL && kernel.data != NULL) { Mat filtered; src.copyTo(filtered); filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0)); return filtered; } else { return Mat(); } } /*! \brief エラーメッセージをウィンドウ名として表示。 ウィンドウが閉じられた時、標準エラー出力にもエラーメッセージを出力する。 \TODO もっといいエラーの表示方法はないものか... \param error_message エラーメッセージ \return 常ににEXIT_FAILURE */ int ShowErrorWindow(const std::string& error_message) { namedWindow(error_message, CV_WINDOW_AUTOSIZE); waitKey(0); cerr << error_message << endl; return EXIT_FAILURE; } /*! \brief 元画像をフィルタされた画像を表示。 \param original 元画像 \param filtered フィルタされた画像 \return 常にEXIT_SUCCESS */ int ShowImageWindow(const Mat& original, const Mat& filtered) { Mat output = Mat::zeros( original.size().height, original.size().width * 2, original.type()); // 元画像とフィルタされた画像を結合 original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows))); filtered.copyTo( Mat(output, Rect(original.cols, 0, original.cols, original.rows))); string window_name("linear_filter"); namedWindow(window_name, CV_WINDOW_AUTOSIZE); imshow(window_name, output); waitKey(0); return EXIT_SUCCESS; } /*! \brief ウィンドウを表示し、結果を出力。  'original'か'filtered'にエラーがある場合、エラーウィンドウを表示する。それ以 外の場合はフィルタされた画像を表示する。 \param original 元画像 \param filtered フィルタされた画像 \param エラーコード */ int ShowWindow(const cv::Mat& original, const cv::Mat& filtered) { if (original.data == NULL) { return ShowErrorWindow(string("failed to open the image.")); } else if (filtered.data == NULL) { return ShowErrorWindow(string("failed to filter the image.")); } else { return ShowImageWindow(original, filtered); } } /*! \brief 画像のファイル名を取得。 プログラム引数が2つの時はデフォルトの値'input.jpg'を、それ以上の場合は第二引 数をファイル名として返す。 \param agrc argc \param argv argv \return 画像のファイル名 */ std::string GetImageFilename(int argc, char** argv) { return (argc == 2)? string("input.jpg"): string(argv[1]); } /*! \brief カーネルを記述したファイル名を取得。 プログラム引数が2つの場合は第二引数を、それ以上の場合は第三引数をファイル名と して返す。 \param argc argc \param argv argv \return カーネルを記述したファイル名 */ std::string GetKernelFilename(int argc, char** argv) { return (argc == 2)? string(argv[1]): string(argv[2]); } } // namespace int main(int argc, char** argv) { if (argc == 2 || argc == 3) { Mat original = imread(::GetImageFilename(argc, argv), CV_LOAD_IMAGE_GRAYSCALE); exit( ::ShowWindow( original, ::Filter(original, ::GetKernel(::GetKernelFilename(argc, argv))))); } else { exit( ::ShowErrorWindow( string("Usage: linear_filter image_file filter_csv"))); } return 0; } <commit_msg>::Rewind関数と::GetKernelSize関数を追加。<commit_after>#include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <cstdint> #include <cstdlib> #include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <string> using std::atof; using std::count; using std::cout; using std::cerr; using std::endl; using std::getline; using std::ifstream; using std::ios; using std::string; using std::stringstream; using cv::filter2D; using cv::imread; using cv::Mat; using cv::namedWindow; using cv::Rect; using cv::waitKey; namespace { /*! \brief ファイルストリームの走査位置を先頭へ戻す。 \param stream ファイルストリーム \return ファイルストリーム */ ifstream& Rewind(ifstream& stream) { stream.clear(); stream.seekg(0, ios::beg); return stream; } /* \brief カーネルへオペレータをセット。 \param row カーネルの行 \param line ファイルから読み込まれた文字列 \param size カーネルのサイズ */ void SetOperator(Mat row, const string& line, uint64_t size) { stringstream line_stream(line); for (uint64_t i = 0; i < size; ++i) { if (line_stream.good() && !line_stream.eof()) { string op; getline(line_stream, op, ','); // オペレータをセット row.at<double>(i) = static_cast<double>(atof(op.c_str())); } else { break; } } } /*! \brief カーネルのサイズを取得。 \param stream カーネルのファイルストリーム \return カーネルのサイズ */ int GetKernelSize(ifstream& stream) { string line; getline(stream, line); // 最初の行からフィルタサイズを取得。 uint64_t size = count(line.begin(), line.end(), ',') + 1; return size; } /*! \brief ファイルを読み込み、カーネルを取得する。 \param filename カーネルを表したCSVのファイル名 \return カーネル。エラーが起きた場合は空の画像 */ Mat GetKernel(const string& filename) { ifstream stream(filename); if (stream.good()) { int size = ::GetKernelSize(stream); // カーネルの領域を確保 Mat kernel = Mat::zeros(size, size, cv::DataType<double>::type); if (kernel.data == NULL) { return Mat(); } else { ::Rewind(stream); for (int i = 0; i < size; ++i) { string line; if (stream.good() && !stream.eof()) { getline(stream, line); SetOperator(kernel.row(i), line, size); } else { break; } } return kernel; } } else { return Mat(); } } /*! \brief 画像をカーネルに基づいた線形フィルタをかける。 \param src 元画像 \param kernel カーネル \return フィルタされた画像。元画像かカーネルにエラーがある場合、空の画像 */ Mat Filter(const Mat& src, const Mat& kernel) { if (src.data != NULL && kernel.data != NULL) { Mat filtered; src.copyTo(filtered); filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0)); return filtered; } else { return Mat(); } } /*! \brief エラーメッセージをウィンドウ名として表示。 ウィンドウが閉じられた時、標準エラー出力にもエラーメッセージを出力する。 \TODO もっといいエラーの表示方法はないものか... \param error_message エラーメッセージ \return 常ににEXIT_FAILURE */ int ShowErrorWindow(const std::string& error_message) { namedWindow(error_message, CV_WINDOW_AUTOSIZE); waitKey(0); cerr << error_message << endl; return EXIT_FAILURE; } /*! \brief 元画像をフィルタされた画像を表示。 \param original 元画像 \param filtered フィルタされた画像 \return 常にEXIT_SUCCESS */ int ShowImageWindow(const Mat& original, const Mat& filtered) { Mat output = Mat::zeros( original.size().height, original.size().width * 2, original.type()); // 元画像とフィルタされた画像を結合 original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows))); filtered.copyTo( Mat(output, Rect(original.cols, 0, original.cols, original.rows))); string window_name("linear_filter"); namedWindow(window_name, CV_WINDOW_AUTOSIZE); imshow(window_name, output); waitKey(0); return EXIT_SUCCESS; } /*! \brief ウィンドウを表示し、結果を出力。  'original'か'filtered'にエラーがある場合、エラーウィンドウを表示する。それ以 外の場合はフィルタされた画像を表示する。 \param original 元画像 \param filtered フィルタされた画像 \param エラーコード */ int ShowWindow(const cv::Mat& original, const cv::Mat& filtered) { if (original.data == NULL) { return ShowErrorWindow(string("failed to open the image.")); } else if (filtered.data == NULL) { return ShowErrorWindow(string("failed to filter the image.")); } else { return ShowImageWindow(original, filtered); } } /*! \brief 画像のファイル名を取得。 プログラム引数が2つの時はデフォルトの値'input.jpg'を、それ以上の場合は第二引 数をファイル名として返す。 \param agrc argc \param argv argv \return 画像のファイル名 */ std::string GetImageFilename(int argc, char** argv) { return (argc == 2)? string("input.jpg"): string(argv[1]); } /*! \brief カーネルを記述したファイル名を取得。 プログラム引数が2つの場合は第二引数を、それ以上の場合は第三引数をファイル名と して返す。 \param argc argc \param argv argv \return カーネルを記述したファイル名 */ std::string GetKernelFilename(int argc, char** argv) { return (argc == 2)? string(argv[1]): string(argv[2]); } } // namespace int main(int argc, char** argv) { if (argc == 2 || argc == 3) { Mat original = imread(::GetImageFilename(argc, argv), CV_LOAD_IMAGE_GRAYSCALE); exit( ::ShowWindow( original, ::Filter(original, ::GetKernel(::GetKernelFilename(argc, argv))))); } else { exit( ::ShowErrorWindow( string("Usage: linear_filter image_file filter_csv"))); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2009 Google 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 Google Inc. 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 "config.h" #include "V8InspectorFrontendHost.h" #include "V8MouseEvent.h" #include "bindings/v8/V8Binding.h" #include "core/inspector/InspectorController.h" #include "core/inspector/InspectorFrontendClient.h" #include "core/inspector/InspectorFrontendHost.h" #include "core/platform/HistogramSupport.h" #include "wtf/text/WTFString.h" namespace WebCore { void V8InspectorFrontendHost::platformMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { #if OS(MACOSX) v8SetReturnValue(args, v8::String::NewSymbol("mac")); #elif OS(LINUX) v8SetReturnValue(args, v8::String::NewSymbol("linux")); #elif OS(FREEBSD) v8SetReturnValue(args, v8::String::NewSymbol("freebsd")); #elif OS(OPENBSD) v8SetReturnValue(args, v8::String::NewSymbol("openbsd")); #elif OS(WIN) v8SetReturnValue(args, v8::String::NewSymbol("windows")); #else v8SetReturnValue(args, v8::String::NewSymbol("unknown")); #endif } void V8InspectorFrontendHost::portMethodCustom(const v8::FunctionCallbackInfo<v8::Value>&) { } static void populateContextMenuItems(v8::Local<v8::Array>& itemArray, ContextMenu& menu) { for (size_t i = 0; i < itemArray->Length(); ++i) { v8::Local<v8::Object> item = v8::Local<v8::Object>::Cast(itemArray->Get(i)); v8::Local<v8::Value> type = item->Get(v8::String::NewSymbol("type")); v8::Local<v8::Value> id = item->Get(v8::String::NewSymbol("id")); v8::Local<v8::Value> label = item->Get(v8::String::NewSymbol("label")); v8::Local<v8::Value> enabled = item->Get(v8::String::NewSymbol("enabled")); v8::Local<v8::Value> checked = item->Get(v8::String::NewSymbol("checked")); v8::Local<v8::Value> subItems = item->Get(v8::String::NewSymbol("subItems")); if (!type->IsString()) continue; String typeString = toWebCoreStringWithNullCheck(type.As<v8::String>()); if (typeString == "separator") { ContextMenuItem item(ContextMenuItem(SeparatorType, ContextMenuItemCustomTagNoAction, String())); menu.appendItem(item); } else if (typeString == "subMenu" && subItems->IsArray()) { ContextMenu subMenu; v8::Local<v8::Array> subItemsArray = v8::Local<v8::Array>::Cast(subItems); populateContextMenuItems(subItemsArray, subMenu); ContextMenuItem item(SubmenuType, ContextMenuItemCustomTagNoAction, toWebCoreStringWithNullCheck(label), &subMenu); menu.appendItem(item); } else { ContextMenuAction typedId = static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + id->ToInt32()->Value()); ContextMenuItem menuItem((typeString == "checkbox" ? CheckableActionType : ActionType), typedId, toWebCoreStringWithNullCheck(label)); if (checked->IsBoolean()) menuItem.setChecked(checked->ToBoolean()->Value()); if (enabled->IsBoolean()) menuItem.setEnabled(enabled->ToBoolean()->Value()); menu.appendItem(menuItem); } } } void V8InspectorFrontendHost::showContextMenuMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() < 2) return; v8::Local<v8::Object> eventWrapper = v8::Local<v8::Object>::Cast(args[0]); if (!V8MouseEvent::info.equals(toWrapperTypeInfo(eventWrapper))) return; Event* event = V8Event::toNative(eventWrapper); if (!args[1]->IsArray()) return; v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); ContextMenu menu; populateContextMenuItems(array, menu); InspectorFrontendHost* frontendHost = V8InspectorFrontendHost::toNative(args.Holder()); Vector<ContextMenuItem> items = menu.items(); frontendHost->showContextMenu(event, items); } static void histogramEnumeration(const char* name, const v8::FunctionCallbackInfo<v8::Value>& args, int boundaryValue) { if (args.Length() < 1 || !args[0]->IsInt32()) return; int sample = args[0]->ToInt32()->Value(); if (sample < boundaryValue) HistogramSupport::histogramEnumeration(name, sample, boundaryValue); } void V8InspectorFrontendHost::recordActionTakenMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.ActionTaken", args, 100); } void V8InspectorFrontendHost::recordPanelShownMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.PanelShown", args, 20); } void V8InspectorFrontendHost::recordSettingChangedMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.SettingChanged", args, 100); } } // namespace WebCore <commit_msg>Use the platform=linux code path for other Unix-like platforms (FreeBSD and OpenBSD) as well, not just OS(LINUX) - with the exception of MacOS.<commit_after>/* * Copyright (C) 2007-2009 Google 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 Google Inc. 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 "config.h" #include "V8InspectorFrontendHost.h" #include "V8MouseEvent.h" #include "bindings/v8/V8Binding.h" #include "core/inspector/InspectorController.h" #include "core/inspector/InspectorFrontendClient.h" #include "core/inspector/InspectorFrontendHost.h" #include "core/platform/HistogramSupport.h" #include "wtf/text/WTFString.h" namespace WebCore { void V8InspectorFrontendHost::platformMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { #if OS(MACOSX) v8SetReturnValue(args, v8::String::NewSymbol("mac")); #elif OS(WIN) v8SetReturnValue(args, v8::String::NewSymbol("windows")); #else // Unix-like systems v8SetReturnValue(args, v8::String::NewSymbol("linux")); #endif } void V8InspectorFrontendHost::portMethodCustom(const v8::FunctionCallbackInfo<v8::Value>&) { } static void populateContextMenuItems(v8::Local<v8::Array>& itemArray, ContextMenu& menu) { for (size_t i = 0; i < itemArray->Length(); ++i) { v8::Local<v8::Object> item = v8::Local<v8::Object>::Cast(itemArray->Get(i)); v8::Local<v8::Value> type = item->Get(v8::String::NewSymbol("type")); v8::Local<v8::Value> id = item->Get(v8::String::NewSymbol("id")); v8::Local<v8::Value> label = item->Get(v8::String::NewSymbol("label")); v8::Local<v8::Value> enabled = item->Get(v8::String::NewSymbol("enabled")); v8::Local<v8::Value> checked = item->Get(v8::String::NewSymbol("checked")); v8::Local<v8::Value> subItems = item->Get(v8::String::NewSymbol("subItems")); if (!type->IsString()) continue; String typeString = toWebCoreStringWithNullCheck(type.As<v8::String>()); if (typeString == "separator") { ContextMenuItem item(ContextMenuItem(SeparatorType, ContextMenuItemCustomTagNoAction, String())); menu.appendItem(item); } else if (typeString == "subMenu" && subItems->IsArray()) { ContextMenu subMenu; v8::Local<v8::Array> subItemsArray = v8::Local<v8::Array>::Cast(subItems); populateContextMenuItems(subItemsArray, subMenu); ContextMenuItem item(SubmenuType, ContextMenuItemCustomTagNoAction, toWebCoreStringWithNullCheck(label), &subMenu); menu.appendItem(item); } else { ContextMenuAction typedId = static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + id->ToInt32()->Value()); ContextMenuItem menuItem((typeString == "checkbox" ? CheckableActionType : ActionType), typedId, toWebCoreStringWithNullCheck(label)); if (checked->IsBoolean()) menuItem.setChecked(checked->ToBoolean()->Value()); if (enabled->IsBoolean()) menuItem.setEnabled(enabled->ToBoolean()->Value()); menu.appendItem(menuItem); } } } void V8InspectorFrontendHost::showContextMenuMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() < 2) return; v8::Local<v8::Object> eventWrapper = v8::Local<v8::Object>::Cast(args[0]); if (!V8MouseEvent::info.equals(toWrapperTypeInfo(eventWrapper))) return; Event* event = V8Event::toNative(eventWrapper); if (!args[1]->IsArray()) return; v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); ContextMenu menu; populateContextMenuItems(array, menu); InspectorFrontendHost* frontendHost = V8InspectorFrontendHost::toNative(args.Holder()); Vector<ContextMenuItem> items = menu.items(); frontendHost->showContextMenu(event, items); } static void histogramEnumeration(const char* name, const v8::FunctionCallbackInfo<v8::Value>& args, int boundaryValue) { if (args.Length() < 1 || !args[0]->IsInt32()) return; int sample = args[0]->ToInt32()->Value(); if (sample < boundaryValue) HistogramSupport::histogramEnumeration(name, sample, boundaryValue); } void V8InspectorFrontendHost::recordActionTakenMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.ActionTaken", args, 100); } void V8InspectorFrontendHost::recordPanelShownMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.PanelShown", args, 20); } void V8InspectorFrontendHost::recordSettingChangedMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args) { histogramEnumeration("DevTools.SettingChanged", args, 100); } } // namespace WebCore <|endoftext|>
<commit_before>#include <GraphFilter.h> #include <Graph.h> #include <iostream> using namespace std; bool GraphFilter::processTemporalData(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats) { auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { target_graph.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) { assert(it != end); ++it; } } auto & nodes = target_graph.getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { assert(it->face >= 0 && it->face < source_graph.getFaceCount()); auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (!seen_nodes.count(np.second)) { seen_nodes.insert(np.second); UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); int type_node_id = -1; if (ut == MALE) type_node_id = nodes.createMaleNode(); else if (ut == FEMALE) type_node_id = nodes.createFemaleNode(); if (type_node_id != -1) { target_graph.addEdge(np.first, type_node_id, -1, 0.125f); } } float weight = 1.0f; if (target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } else if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; weight = 0.25f; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; weight = 0.125f; } if ((keep_hashtags || target_type != NODE_HASHTAG) && (keep_links || target_type != NODE_URL)) { unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif } else { seen_edges[np.first][np.second] = target_graph.addEdge(np.first, np.second, -1, weight, 0); } } } } // cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << target_graph.getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); return is_changed; } <commit_msg>adjust weights<commit_after>#include <GraphFilter.h> #include <Graph.h> #include <iostream> using namespace std; bool GraphFilter::processTemporalData(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats) { auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { target_graph.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) { assert(it != end); ++it; } } auto & nodes = target_graph.getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { assert(it->face >= 0 && it->face < source_graph.getFaceCount()); auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (!seen_nodes.count(np.second)) { seen_nodes.insert(np.second); UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); int type_node_id = -1; if (ut == MALE) type_node_id = nodes.createMaleNode(); else if (ut == FEMALE) type_node_id = nodes.createFemaleNode(); if (type_node_id != -1) { target_graph.addEdge(np.first, type_node_id, -1, 0.15f); } } float weight = 1.0f; if (target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } else if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; weight = 0.25f; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; weight = 0.15f; } if ((keep_hashtags || target_type != NODE_HASHTAG) && (keep_links || target_type != NODE_URL)) { unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif } else { seen_edges[np.first][np.second] = target_graph.addEdge(np.first, np.second, -1, weight, 0); } } } } // cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << target_graph.getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); return is_changed; } <|endoftext|>
<commit_before>#include <assert.h> #include <string.h> #include <gcrypt.h> #include <unistd.h> GCRY_THREAD_OPTION_PTHREAD_IMPL; #include "Logger.h" #include "CEncrypt.h" //https://gnupg.org/documentation/manuals/gcrypt/Working-with-cipher-handles.html#Working-with-cipher-handles //https://gnupg.org/documentation/manuals/gcrypt/Key-Derivation.html#Key-Derivation typedef struct { int32_t crc; char magic[8]; uint16_t majorversion; uint16_t minorversion; uint8_t salt[32]; struct { char username[128]; uint8_t key[64]; uint8_t enccheckbytes[64]; uint8_t checkbytes[64]; int32_t hashreps; } user[4]; } TEncHeader; void GCryptCheckError(const char *function, gpg_error_t ret) { if (ret) { LOG(ERROR) << function << ": Failure: " << gcry_strsource(ret) << "/" << gcry_strerror (ret); throw std::exception(); } } void CEncrypt::PassToHash(char *pass, uint8_t salt[32], uint8_t passkey[64], int hashreps) { gpg_error_t ret = gcry_kdf_derive( pass, strlen(pass), GCRY_KDF_SCRYPT, GCRY_MD_SHA256, salt, 32, hashreps, 64, passkey); GCryptCheckError("getpass", ret); } void CEncrypt::CreateEnc(int8_t *block, char *pass) { LOG(INFO) << "Create Encryption block"; uint8_t key[64]; gcry_randomize (key, 64, GCRY_STRONG_RANDOM); TEncHeader *h = (TEncHeader*)block; memset(h, 0, sizeof(blocksize)); h->majorversion = 1; h->minorversion = 0; strcpy(h->magic, "coverfs"); gcry_create_nonce (h->salt, 32); h->user[0].hashreps = 500; strcpy(h->user[0].username, "poke"); gcry_create_nonce (h->user[0].enccheckbytes, 64); uint8_t passkey[64]; PassToHash(pass, h->salt, passkey, h->user[0].hashreps); gpg_error_t ret; gcry_cipher_hd_t hd; ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hd, passkey, 32); GCryptCheckError("gcry_cipher_setkey", ret); ret = gcry_cipher_encrypt (hd, h->user[0].checkbytes, 64, h->user[0].enccheckbytes, 64); GCryptCheckError("gcry_cipher_encrypt", ret); ret = gcry_cipher_encrypt (hd, h->user[0].key, 64, key, 64); GCryptCheckError("gcry_cipher_encrypt", ret); for(int i=0; i<64; i++) key[i] = 0x0; gcry_cipher_close(hd); gcry_md_hash_buffer(GCRY_MD_CRC32, &h->crc, (int8_t*)h+4, blocksize-4); } CEncrypt::CEncrypt(CAbstractBlockIO &bio, char *pass) { assert(sizeof(TEncHeader) == 4+8+4+32+(128+64+64+64+4)*4); assert(bio.blocksize >= 1024); blocksize = bio.blocksize; gpg_error_t ret; const char* gcryptversion = gcry_check_version (GCRYPT_VERSION); LOG(INFO) << "gcrypt version " << gcryptversion; if (gcryptversion == NULL) { LOG(ERROR) << "gcrypt version too old"; throw std::exception(); } ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); GCryptCheckError("gcry_control", ret); gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); assert(gcry_md_get_algo_dlen (GCRY_MD_CRC32) == 4); int8_t block[blocksize]; bio.Read(0, 1, block); TEncHeader *h = (TEncHeader*)block; if (strncmp(h->magic, "coverfs", 8) != 0) { CreateEnc(block, pass); bio.Write(0, 1, block); } int32_t crc; gcry_md_hash_buffer(GCRY_MD_CRC32, &crc, (int8_t*)h+4, blocksize-4); assert(h->crc == crc); assert(h->majorversion == 1); assert(h->minorversion == 0); uint8_t passkey[64]; PassToHash(pass, h->salt, passkey, h->user[0].hashreps); gcry_cipher_hd_t hd; ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hd, passkey, 32); GCryptCheckError("gcry_cipher_setkey", ret); uint8_t check[64]; ret = gcry_cipher_encrypt(hd, check, 64, h->user[0].enccheckbytes, 64); GCryptCheckError("gcry_cipher_encrypt", ret); if (memcmp(check, h->user[0].checkbytes, 64) != 0) { LOG(ERROR) << "Cannot decrypt filesystem. Did you type the right password?"; throw std::exception(); } uint8_t key[64]; ret = gcry_cipher_decrypt(hd, key, 64, h->user[0].key, 64); GCryptCheckError("gcry_cipher_decrypt", ret); gcry_cipher_close(hd); for(int i=0; i<4; i++) { ret = gcry_cipher_open(&hdblock[i], GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hdblock[i], key, 32); GCryptCheckError("gcry_cipher_setkey", ret); } memset(key, 0, 64); memset(block, 0, blocksize); } void CEncrypt::Decrypt(const int blockidx, int8_t *d) { //printf("Decrypt blockidx %i\n", blockidx); int32_t iv[4]; iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know this is bad if (blockidx == 0) return; for(int i=0; i<4; i++) { if (!mutex[i].try_lock()) continue; gcry_cipher_setiv (hdblock[i], iv, 16); gpg_error_t ret = gcry_cipher_decrypt(hdblock[i], d, blocksize, NULL, 0); GCryptCheckError("gcry_cipher_decrypt", ret); mutex[i].unlock(); return; } // all cipher handles are locked. Wait ... mutex[0].lock(); gcry_cipher_setiv (hdblock[0], iv, 16); gpg_error_t ret = gcry_cipher_decrypt(hdblock[0], d, blocksize, NULL, 0); GCryptCheckError("gcry_cipher_decrypt", ret); mutex[0].unlock(); } void CEncrypt::Encrypt(const int blockidx, int8_t* d) { //printf("Encrypt blockidx %i\n", blockidx); int32_t iv[4]; iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know, this is bad if (blockidx == 0) return; for(int i=0; i<4; i++) { if (!mutex[i].try_lock()) continue; gcry_cipher_setiv (hdblock[i], iv, 16); gpg_error_t ret = gcry_cipher_encrypt(hdblock[i], d, blocksize, 0, 0); GCryptCheckError("gcry_cipher_encrypt", ret); mutex[i].unlock(); return; } // all cipher handles are locked. Wait ... mutex[1].lock(); gcry_cipher_setiv (hdblock[1], iv, 16); gpg_error_t ret = gcry_cipher_encrypt(hdblock[1], d, blocksize, 0, 0); GCryptCheckError("gcry_cipher_encrypt", ret); mutex[1].unlock(); } <commit_msg>For Travis CI: Add pthread include for gcrypt<commit_after>#include <assert.h> #include <string.h> #include <gcrypt.h> #include <unistd.h> #include <pthread.h> GCRY_THREAD_OPTION_PTHREAD_IMPL; #include "Logger.h" #include "CEncrypt.h" //https://gnupg.org/documentation/manuals/gcrypt/Working-with-cipher-handles.html#Working-with-cipher-handles //https://gnupg.org/documentation/manuals/gcrypt/Key-Derivation.html#Key-Derivation typedef struct { int32_t crc; char magic[8]; uint16_t majorversion; uint16_t minorversion; uint8_t salt[32]; struct { char username[128]; uint8_t key[64]; uint8_t enccheckbytes[64]; uint8_t checkbytes[64]; int32_t hashreps; } user[4]; } TEncHeader; void GCryptCheckError(const char *function, gpg_error_t ret) { if (ret) { LOG(ERROR) << function << ": Failure: " << gcry_strsource(ret) << "/" << gcry_strerror (ret); throw std::exception(); } } void CEncrypt::PassToHash(char *pass, uint8_t salt[32], uint8_t passkey[64], int hashreps) { gpg_error_t ret = gcry_kdf_derive( pass, strlen(pass), GCRY_KDF_SCRYPT, GCRY_MD_SHA256, salt, 32, hashreps, 64, passkey); GCryptCheckError("getpass", ret); } void CEncrypt::CreateEnc(int8_t *block, char *pass) { LOG(INFO) << "Create Encryption block"; uint8_t key[64]; gcry_randomize (key, 64, GCRY_STRONG_RANDOM); TEncHeader *h = (TEncHeader*)block; memset(h, 0, sizeof(blocksize)); h->majorversion = 1; h->minorversion = 0; strcpy(h->magic, "coverfs"); gcry_create_nonce (h->salt, 32); h->user[0].hashreps = 500; strcpy(h->user[0].username, "poke"); gcry_create_nonce (h->user[0].enccheckbytes, 64); uint8_t passkey[64]; PassToHash(pass, h->salt, passkey, h->user[0].hashreps); gpg_error_t ret; gcry_cipher_hd_t hd; ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hd, passkey, 32); GCryptCheckError("gcry_cipher_setkey", ret); ret = gcry_cipher_encrypt (hd, h->user[0].checkbytes, 64, h->user[0].enccheckbytes, 64); GCryptCheckError("gcry_cipher_encrypt", ret); ret = gcry_cipher_encrypt (hd, h->user[0].key, 64, key, 64); GCryptCheckError("gcry_cipher_encrypt", ret); for(int i=0; i<64; i++) key[i] = 0x0; gcry_cipher_close(hd); gcry_md_hash_buffer(GCRY_MD_CRC32, &h->crc, (int8_t*)h+4, blocksize-4); } CEncrypt::CEncrypt(CAbstractBlockIO &bio, char *pass) { assert(sizeof(TEncHeader) == 4+8+4+32+(128+64+64+64+4)*4); assert(bio.blocksize >= 1024); blocksize = bio.blocksize; gpg_error_t ret; const char* gcryptversion = gcry_check_version (GCRYPT_VERSION); LOG(INFO) << "gcrypt version " << gcryptversion; if (gcryptversion == NULL) { LOG(ERROR) << "gcrypt version too old"; throw std::exception(); } ret = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); GCryptCheckError("gcry_control", ret); gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); assert(gcry_md_get_algo_dlen (GCRY_MD_CRC32) == 4); int8_t block[blocksize]; bio.Read(0, 1, block); TEncHeader *h = (TEncHeader*)block; if (strncmp(h->magic, "coverfs", 8) != 0) { CreateEnc(block, pass); bio.Write(0, 1, block); } int32_t crc; gcry_md_hash_buffer(GCRY_MD_CRC32, &crc, (int8_t*)h+4, blocksize-4); assert(h->crc == crc); assert(h->majorversion == 1); assert(h->minorversion == 0); uint8_t passkey[64]; PassToHash(pass, h->salt, passkey, h->user[0].hashreps); gcry_cipher_hd_t hd; ret = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hd, passkey, 32); GCryptCheckError("gcry_cipher_setkey", ret); uint8_t check[64]; ret = gcry_cipher_encrypt(hd, check, 64, h->user[0].enccheckbytes, 64); GCryptCheckError("gcry_cipher_encrypt", ret); if (memcmp(check, h->user[0].checkbytes, 64) != 0) { LOG(ERROR) << "Cannot decrypt filesystem. Did you type the right password?"; throw std::exception(); } uint8_t key[64]; ret = gcry_cipher_decrypt(hd, key, 64, h->user[0].key, 64); GCryptCheckError("gcry_cipher_decrypt", ret); gcry_cipher_close(hd); for(int i=0; i<4; i++) { ret = gcry_cipher_open(&hdblock[i], GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0); GCryptCheckError("gcry_cipher_open", ret); ret = gcry_cipher_setkey(hdblock[i], key, 32); GCryptCheckError("gcry_cipher_setkey", ret); } memset(key, 0, 64); memset(block, 0, blocksize); } void CEncrypt::Decrypt(const int blockidx, int8_t *d) { //printf("Decrypt blockidx %i\n", blockidx); int32_t iv[4]; iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know this is bad if (blockidx == 0) return; for(int i=0; i<4; i++) { if (!mutex[i].try_lock()) continue; gcry_cipher_setiv (hdblock[i], iv, 16); gpg_error_t ret = gcry_cipher_decrypt(hdblock[i], d, blocksize, NULL, 0); GCryptCheckError("gcry_cipher_decrypt", ret); mutex[i].unlock(); return; } // all cipher handles are locked. Wait ... mutex[0].lock(); gcry_cipher_setiv (hdblock[0], iv, 16); gpg_error_t ret = gcry_cipher_decrypt(hdblock[0], d, blocksize, NULL, 0); GCryptCheckError("gcry_cipher_decrypt", ret); mutex[0].unlock(); } void CEncrypt::Encrypt(const int blockidx, int8_t* d) { //printf("Encrypt blockidx %i\n", blockidx); int32_t iv[4]; iv[0] = blockidx; iv[1] = 0; iv[2] = 0; iv[3] = 0; // I know, this is bad if (blockidx == 0) return; for(int i=0; i<4; i++) { if (!mutex[i].try_lock()) continue; gcry_cipher_setiv (hdblock[i], iv, 16); gpg_error_t ret = gcry_cipher_encrypt(hdblock[i], d, blocksize, 0, 0); GCryptCheckError("gcry_cipher_encrypt", ret); mutex[i].unlock(); return; } // all cipher handles are locked. Wait ... mutex[1].lock(); gcry_cipher_setiv (hdblock[1], iv, 16); gpg_error_t ret = gcry_cipher_encrypt(hdblock[1], d, blocksize, 0, 0); GCryptCheckError("gcry_cipher_encrypt", ret); mutex[1].unlock(); } <|endoftext|>
<commit_before><commit_msg>split in progress<commit_after><|endoftext|>
<commit_before>/* Copyright [2016] [Ganger Games] 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 <GangerEngine/ImageLoader.h> #include <GangerEngine/picoPNG.h> #include <GangerEngine/IOManager.h> #include <GangerEngine/GangerErrors.h> #include <string> #include <vector> namespace GangerEngine { GLTexture ImageLoader::LoadPNG(std::string filePath) { // Create a GLTexture and initialize all its fields to 0 GLTexture texture = {}; // This is the input data to decodePNG, which we load from a file std::vector<unsigned char> in; // This is the output data from decodePNG, which is the pixel data for // our texture std::vector<unsigned char> out; unsigned long width, height; // Read in the image file contents into a buffer if (IOManager::ReadFileToBuffer(filePath, in) == false) { FatalError("Failed to load PNG file to buffer!"); } // Decode the .png format into an array of pixels int errorCode = DecodePNG(out, width, height, &(in[0]), in.size()); if (errorCode != 0) { FatalError("decodePNG failed with error: " + std::to_string(errorCode)); } // Generate the openGL texture object glGenTextures(1, &(texture.id)); // Bind the texture object glBindTexture(GL_TEXTURE_2D, texture.id); // Upload the pixels to the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(out[0])); // Set some texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Generate the mipmaps glGenerateMipmap(GL_TEXTURE_2D); // Unbind the texture glBindTexture(GL_TEXTURE_2D, 0); texture.width = width; texture.height = height; texture.filePath = filePath; // Return a copy of the texture data return texture; } } // namespace GangerEngine <commit_msg>Fix an incorrect name of a header.<commit_after>/* Copyright [2016] [Ganger Games] 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 <GangerEngine/ImageLoader.h> #include <GangerEngine/PicoPNG.h> #include <GangerEngine/IOManager.h> #include <GangerEngine/GangerErrors.h> #include <string> #include <vector> namespace GangerEngine { GLTexture ImageLoader::LoadPNG(std::string filePath) { // Create a GLTexture and initialize all its fields to 0 GLTexture texture = {}; // This is the input data to decodePNG, which we load from a file std::vector<unsigned char> in; // This is the output data from decodePNG, which is the pixel data for // our texture std::vector<unsigned char> out; unsigned long width, height; // Read in the image file contents into a buffer if (IOManager::ReadFileToBuffer(filePath, in) == false) { FatalError("Failed to load PNG file to buffer!"); } // Decode the .png format into an array of pixels int errorCode = DecodePNG(out, width, height, &(in[0]), in.size()); if (errorCode != 0) { FatalError("decodePNG failed with error: " + std::to_string(errorCode)); } // Generate the openGL texture object glGenTextures(1, &(texture.id)); // Bind the texture object glBindTexture(GL_TEXTURE_2D, texture.id); // Upload the pixels to the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(out[0])); // Set some texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Generate the mipmaps glGenerateMipmap(GL_TEXTURE_2D); // Unbind the texture glBindTexture(GL_TEXTURE_2D, 0); texture.width = width; texture.height = height; texture.filePath = filePath; // Return a copy of the texture data return texture; } } // namespace GangerEngine <|endoftext|>
<commit_before> #pragma once #include <string> // for size_t #include "Field_Dimensions.hpp" /// all distances in meters /// all times in seconds /// all weights in kilograms // Number of identifiable robots on one team const size_t Num_Shells = 16; // Number of playing robots on one team const size_t Robots_Per_Team = 6; const size_t Max_Dribble = 128; const size_t Max_Kick = 255; const float Ball_Diameter = 0.043f; const float Ball_Radius = Ball_Diameter / 2.0f; const float Ball_Mass = 0.048f; const float Robot_Diameter = 0.180f; const float Robot_Radius = Robot_Diameter / 2.0f; const float Robot_Height = 0.150f; const float Robot_MouthWidth = 0.10f; const float Robot_MouthRadius = 0.007f; /** constants for dot patterns */ const float Dots_Small_Offset = 0.035; const float Dots_Large_Offset = 0.054772; const float Dots_Radius = 0.02; const std::string Team_Name_Lower = "robojackets"; const std::string Team_Name = "RoboJackets"; <commit_msg>Fixed constants to reflect reality<commit_after> #pragma once #include <string> // for size_t #include "Field_Dimensions.hpp" /// all distances in meters /// all times in seconds /// all weights in kilograms // Number of identifiable robots on one team const size_t Num_Shells = 16; // Number of playing robots on one team const size_t Robots_Per_Team = 6; const size_t Max_Dribble = 128; const size_t Max_Kick = 255; const float Ball_Diameter = 0.043f; const float Ball_Radius = Ball_Diameter / 2.0f; const float Ball_Mass = 0.048f; const float Robot_Diameter = 0.180f; const float Robot_Radius = Robot_Diameter / 2.0f; const float Robot_Height = 0.150f; const float Robot_MouthWidth = 0.0635f; const float Robot_MouthRadius = 0.0815f; /** constants for dot patterns */ const float Dots_Small_Offset = 0.035; const float Dots_Large_Offset = 0.054772; const float Dots_Radius = 0.02; const std::string Team_Name_Lower = "robojackets"; const std::string Team_Name = "RoboJackets"; <|endoftext|>
<commit_before>#include "GameState.h" #include "Batcher.h" #include "DDSLoader.h" #include "File.h" #include "Math.h" #include "OpenGL.h" #include "Profile.h" #include "StateMachine.h" #include "World.h" static vec2 windowToView(StateMachine* stateMachine, const vec2& p) { const float ww = stateMachine->getWindowWidth(); const float wh = stateMachine->getWindowHeight(); const float ws = (ww > wh) ? wh : ww; return { (2.f * p.x - ww) / ws, (wh - 2.f * p.y) / ws }; } static vec2 viewToWindow(StateMachine* stateMachine, const vec2& p) { const float ww = stateMachine->getWindowWidth(); const float wh = stateMachine->getWindowHeight(); const float ws = (ww > wh) ? wh : ww; return { 0.5f * (p.x * ws + ww), 0.5f * (wh - p.y * ws) }; } struct GameState::PrivateData { GLuint shaderProgram; GLuint whiteTexture; Batcher batcher; float joystickAreaRadius; float joystickStickRadius; float joystickMaxOffset; bool joystickActive; vec2 joystickCenter; vec2 joystickPosition; World* world; double exitTime; }; GameState::GameState() : m(new PrivateData) { File vsFile("assets/shaders/game.vs"); GLuint vs = createShader(GL_VERTEX_SHADER, vsFile.getData(), vsFile.getSize()); File fsFile("assets/shaders/game.fs"); GLuint fs = createShader(GL_FRAGMENT_SHADER, fsFile.getData(), fsFile.getSize()); m->shaderProgram = createProgram(vs, fs); glUseProgram(m->shaderProgram); glUniform1i(glGetUniformLocation(m->shaderProgram, "u_sampler"), 0); size_t width, height, depth; GLenum bindTarget; File whiteTextureFile("assets/images/white.dds"); m->whiteTexture = loadDDS(whiteTextureFile.getData(), whiteTextureFile.getSize(), true, width, height, depth, bindTarget); m->joystickAreaRadius = 0.2f; m->joystickStickRadius = 0.1f; m->joystickMaxOffset = 0.1f; m->world = nullptr; } GameState::~GameState() { delete m; } void GameState::enter(StateMachine* stateMachine) { m->joystickActive = false; File levelFile(Profile::getLevelName(Profile::getCurrentLevel()).c_str()); m->world = new World; m->world->init(levelFile.getData(), levelFile.getSize()); m->exitTime = 0.0; } void GameState::leave(StateMachine* stateMachine) { delete m->world; m->world = nullptr; } void GameState::update(StateMachine* stateMachine) { if(!m->exitTime) { if(m->joystickActive) { vec2 d = windowToView(stateMachine, m->joystickPosition) - windowToView(stateMachine, m->joystickCenter); m->world->setControl(d / m->joystickMaxOffset); } else { m->world->setControl(vec2::zero); } m->world->update((float)stateMachine->getDeltaTime()); if(m->world->getState() == World::Lost) { m->exitTime = stateMachine->getTime() + 1.0; } else if(m->world->getState() == World::Won) { if(!Profile::getLevelName(Profile::getCurrentLevel() + 1).empty()) { Profile::setCurrentLevel(Profile::getCurrentLevel() + 1); } else { Profile::setCurrentLevel(0); } m->exitTime = stateMachine->getTime() + 1.0; } } else if(m->exitTime <= stateMachine->getTime()) { stateMachine->requestState("menu"); } } void GameState::render(StateMachine* stateMachine) { glViewport(0, 0, stateMachine->getFramebufferWidth(), stateMachine->getFramebufferHeight()); switch(m->world->getState()) { case World::Playing: glClearColor(1.f, 0.9406f, 0.7969f, 1.f); break; case World::Lost: glClearColor(1.f, 0.5f, 0.5f, 1.f); break; case World::Won: glClearColor(0.5f, 1.f, 0.5f, 1.f); break; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(m->shaderProgram); float sx, sy; if(stateMachine->getFramebufferWidth() > stateMachine->getFramebufferHeight()) { sx = float(stateMachine->getFramebufferHeight()) / float(stateMachine->getFramebufferWidth()); sy = 1.f; } else { sx = 1.f; sy = float(stateMachine->getFramebufferWidth()) / float(stateMachine->getFramebufferHeight()); } float mvp[] = { sx, 0.f, 0.f, 0.f, 0.f, sy, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; glUniformMatrix4fv(glGetUniformLocation(m->shaderProgram, "u_modelViewProjection"), 1, GL_FALSE, mvp); glBindTexture(GL_TEXTURE_2D, m->whiteTexture); m->world->render(m->batcher); if(m->joystickActive) { vec2 c = windowToView(stateMachine, m->joystickCenter); vec2 p = windowToView(stateMachine, m->joystickPosition); m->batcher.addCircle(c, m->joystickAreaRadius, { 0.5f, 0.5f, 0.5f, 0.333f } ); m->batcher.addCircle(p, m->joystickStickRadius, { 0.5f, 0.5f, 0.5f, 0.333f } ); } m->batcher.flush(); } void GameState::mouseDown(StateMachine* stateMachine, float x, float y) { m->joystickActive = true; m->joystickCenter = m->joystickPosition = { x, y }; } void GameState::mouseUp(StateMachine* stateMachine, float x, float y) { m->joystickActive = false; } void GameState::mouseMove(StateMachine* stateMachine, float x, float y) { m->joystickPosition = { x, y }; if(m->joystickActive) { vec2 c = windowToView(stateMachine, m->joystickCenter); vec2 p = windowToView(stateMachine, m->joystickPosition); if(length(p - c) > m->joystickMaxOffset) { m->joystickCenter = viewToWindow(stateMachine, p + normalize(c - p) * m->joystickMaxOffset); } } } <commit_msg>Require click before moving to menustate between lvls<commit_after>#include "GameState.h" #include "Batcher.h" #include "DDSLoader.h" #include "File.h" #include "Math.h" #include "OpenGL.h" #include "Profile.h" #include "StateMachine.h" #include "World.h" static vec2 windowToView(StateMachine* stateMachine, const vec2& p) { const float ww = stateMachine->getWindowWidth(); const float wh = stateMachine->getWindowHeight(); const float ws = (ww > wh) ? wh : ww; return { (2.f * p.x - ww) / ws, (wh - 2.f * p.y) / ws }; } static vec2 viewToWindow(StateMachine* stateMachine, const vec2& p) { const float ww = stateMachine->getWindowWidth(); const float wh = stateMachine->getWindowHeight(); const float ws = (ww > wh) ? wh : ww; return { 0.5f * (p.x * ws + ww), 0.5f * (wh - p.y * ws) }; } struct GameState::PrivateData { GLuint shaderProgram; GLuint whiteTexture; Batcher batcher; float joystickAreaRadius; float joystickStickRadius; float joystickMaxOffset; bool joystickActive; vec2 joystickCenter; vec2 joystickPosition; World* world; double exitTime; }; GameState::GameState() : m(new PrivateData) { File vsFile("assets/shaders/game.vs"); GLuint vs = createShader(GL_VERTEX_SHADER, vsFile.getData(), vsFile.getSize()); File fsFile("assets/shaders/game.fs"); GLuint fs = createShader(GL_FRAGMENT_SHADER, fsFile.getData(), fsFile.getSize()); m->shaderProgram = createProgram(vs, fs); glUseProgram(m->shaderProgram); glUniform1i(glGetUniformLocation(m->shaderProgram, "u_sampler"), 0); size_t width, height, depth; GLenum bindTarget; File whiteTextureFile("assets/images/white.dds"); m->whiteTexture = loadDDS(whiteTextureFile.getData(), whiteTextureFile.getSize(), true, width, height, depth, bindTarget); m->joystickAreaRadius = 0.2f; m->joystickStickRadius = 0.1f; m->joystickMaxOffset = 0.1f; m->world = nullptr; } GameState::~GameState() { delete m; } void GameState::enter(StateMachine* stateMachine) { m->joystickActive = false; File levelFile(Profile::getLevelName(Profile::getCurrentLevel()).c_str()); m->world = new World; m->world->init(levelFile.getData(), levelFile.getSize()); m->exitTime = 0.0; } void GameState::leave(StateMachine* stateMachine) { delete m->world; m->world = nullptr; } void GameState::update(StateMachine* stateMachine) { if(!m->exitTime) { if(m->joystickActive) { vec2 d = windowToView(stateMachine, m->joystickPosition) - windowToView(stateMachine, m->joystickCenter); m->world->setControl(d / m->joystickMaxOffset); } else { m->world->setControl(vec2::zero); } m->world->update((float)stateMachine->getDeltaTime()); if(m->world->getState() == World::Lost) { m->exitTime = stateMachine->getTime() + 0.5; } else if(m->world->getState() == World::Won) { if(!Profile::getLevelName(Profile::getCurrentLevel() + 1).empty()) { Profile::setCurrentLevel(Profile::getCurrentLevel() + 1); } else { Profile::setCurrentLevel(0); } m->exitTime = stateMachine->getTime() + 0.5; } } else if(m->exitTime <= stateMachine->getTime()) { if(m->joystickActive) { stateMachine->requestState("menu"); } } } void GameState::render(StateMachine* stateMachine) { glViewport(0, 0, stateMachine->getFramebufferWidth(), stateMachine->getFramebufferHeight()); switch(m->world->getState()) { case World::Playing: glClearColor(1.f, 0.9406f, 0.7969f, 1.f); break; case World::Lost: glClearColor(1.f, 0.5f, 0.5f, 1.f); break; case World::Won: glClearColor(0.5f, 1.f, 0.5f, 1.f); break; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(m->shaderProgram); float sx, sy; if(stateMachine->getFramebufferWidth() > stateMachine->getFramebufferHeight()) { sx = float(stateMachine->getFramebufferHeight()) / float(stateMachine->getFramebufferWidth()); sy = 1.f; } else { sx = 1.f; sy = float(stateMachine->getFramebufferWidth()) / float(stateMachine->getFramebufferHeight()); } float mvp[] = { sx, 0.f, 0.f, 0.f, 0.f, sy, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; glUniformMatrix4fv(glGetUniformLocation(m->shaderProgram, "u_modelViewProjection"), 1, GL_FALSE, mvp); glBindTexture(GL_TEXTURE_2D, m->whiteTexture); m->world->render(m->batcher); if(m->joystickActive) { vec2 c = windowToView(stateMachine, m->joystickCenter); vec2 p = windowToView(stateMachine, m->joystickPosition); m->batcher.addCircle(c, m->joystickAreaRadius, { 0.5f, 0.5f, 0.5f, 0.333f } ); m->batcher.addCircle(p, m->joystickStickRadius, { 0.5f, 0.5f, 0.5f, 0.333f } ); } m->batcher.flush(); } void GameState::mouseDown(StateMachine* stateMachine, float x, float y) { m->joystickActive = true; m->joystickCenter = m->joystickPosition = { x, y }; } void GameState::mouseUp(StateMachine* stateMachine, float x, float y) { m->joystickActive = false; } void GameState::mouseMove(StateMachine* stateMachine, float x, float y) { m->joystickPosition = { x, y }; if(m->joystickActive) { vec2 c = windowToView(stateMachine, m->joystickCenter); vec2 p = windowToView(stateMachine, m->joystickPosition); if(length(p - c) > m->joystickMaxOffset) { m->joystickCenter = viewToWindow(stateMachine, p + normalize(c - p) * m->joystickMaxOffset); } } } <|endoftext|>
<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <Integration.hpp> namespace PulsarSearch { integrationSamplesDMsConf::integrationSamplesDMsConf() {} integrationSampleDMsConf::~integrationSamplesDMsConf() {} std::string integrationSamplesDMsConf::print() const { return isa::utils::toString(nrSamplesPerBlock) + " " + isa::utils::toString(nrSamplesPerThread); } void readTunedIntegrationSamplesDMsConf(tunedIntegrationSamplesDMsConf & tunedConf, const std::string & confFilename) { std::string temp; std::ifstream confFile(confFilename); while ( ! confFile.eof() ) { unsigned int splitPoint = 0; std::getline(confFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrSamples = 0; unsigned int integration = 0; PulsarSearch::integrationSamplesDMsConf parameters; splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); integration = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint))); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint))); if ( tunedConf.count(deviceName) == 0 ) { std::map< unsigned int, std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > > externalContainer; std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > internalContainer; internalContainer.insert(std::make_pair(integration, parameters)); externalContainer.insert(std::make_pair(nrSamples, internalContainer)); tunedConf.insert(std::make_pair(deviceName, externalContainer)); } else if ( tunedConf[deviceName].count(nrSamples) == 0 ) { std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > internalContainer; internalContainer.insert(std::make_pair(integration, parameters)); tunedConf[deviceName].insert(std::make_pair(nrSamples, internalContainer)); } else { tunedConf[deviceName][nrSamples].insert(std::make_pair(integration, parameters)); } } } } // PulsarSearch <commit_msg>Typo.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <Integration.hpp> namespace PulsarSearch { integrationSamplesDMsConf::integrationSamplesDMsConf() {} integrationSamplesDMsConf::~integrationSamplesDMsConf() {} std::string integrationSamplesDMsConf::print() const { return isa::utils::toString(nrSamplesPerBlock) + " " + isa::utils::toString(nrSamplesPerThread); } void readTunedIntegrationSamplesDMsConf(tunedIntegrationSamplesDMsConf & tunedConf, const std::string & confFilename) { std::string temp; std::ifstream confFile(confFilename); while ( ! confFile.eof() ) { unsigned int splitPoint = 0; std::getline(confFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrSamples = 0; unsigned int integration = 0; PulsarSearch::integrationSamplesDMsConf parameters; splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); integration = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint))); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint))); if ( tunedConf.count(deviceName) == 0 ) { std::map< unsigned int, std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > > externalContainer; std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > internalContainer; internalContainer.insert(std::make_pair(integration, parameters)); externalContainer.insert(std::make_pair(nrSamples, internalContainer)); tunedConf.insert(std::make_pair(deviceName, externalContainer)); } else if ( tunedConf[deviceName].count(nrSamples) == 0 ) { std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > internalContainer; internalContainer.insert(std::make_pair(integration, parameters)); tunedConf[deviceName].insert(std::make_pair(nrSamples, internalContainer)); } else { tunedConf[deviceName][nrSamples].insert(std::make_pair(integration, parameters)); } } } } // PulsarSearch <|endoftext|>
<commit_before> uint8_t USBPutChar(uint8_t c); // press() adds the specified key (printing, non-printing, or modifier) // to the persistent key report and sends the report. Because of the way // USB HID works, the host acts like the key remains pressed until we // call release(), releaseAll(), or otherwise clear the report and resend. size_t Keyboard_::press(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers |= (1<<(k-128)); k = 0; } else { // it's a printing key k = pgm_read_byte(_asciimap + k); if (!k) { setWriteError(); return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers |= 0x02; // the left shift modifier k &= 0x7F; } if (k & 0x40) { // it's an altgr key _keyReport.modifiers |= 0x40; // the altGr key k &= 0x3F; } } // Add k to the key report only if it's not already present // and if there is an empty slot. if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && _keyReport.keys[2] != k && _keyReport.keys[3] != k && _keyReport.keys[4] != k && _keyReport.keys[5] != k) { for (i=0; i<6; i++) { if (_keyReport.keys[i] == 0x00) { _keyReport.keys[i] = k; break; } } if (i == 6) { setWriteError(); return 0; } } sendReport(&_keyReport); return 1; } // release() takes the specified key out of the persistent key report and // sends the report. This tells the OS the key is no longer pressed and that // it shouldn't be repeated any more. size_t Keyboard_::release(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers &= ~(1<<(k-128)); k = 0; } else { // it's a printing key k = pgm_read_byte(_asciimap + k); if (!k) { return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers &= ~(0x02); // the left shift modifier k &= 0x7F; } if (k & 0x40) { // it's an altgr key _keyReport.modifiers &= ~(0x40); // the altGr key k &= 0x3F; } } // Test the key report to see if k is present. Clear it if it exists. // Check all positions in case the key is present more than once (which it shouldn't be) for (i=0; i<6; i++) { if (0 != k && _keyReport.keys[i] == k) { _keyReport.keys[i] = 0x00; } } sendReport(&_keyReport); return 1; } void Keyboard_::releaseAll(void) { _keyReport.keys[0] = 0; _keyReport.keys[1] = 0; _keyReport.keys[2] = 0; _keyReport.keys[3] = 0; _keyReport.keys[4] = 0; _keyReport.keys[5] = 0; _keyReport.modifiers = 0; sendReport(&_keyReport); } size_t Keyboard_::write(uint8_t c) { uint8_t p = press(c); // Keydown release(c); // Keyup return p; // just return the result of press() since release() almost always returns 1 } Keyboard_ Keyboard; #endif <commit_msg>Updated to use new AltGr way.<commit_after> uint8_t USBPutChar(uint8_t c); // press() adds the specified key (printing, non-printing, or modifier) // to the persistent key report and sends the report. Because of the way // USB HID works, the host acts like the key remains pressed until we // call release(), releaseAll(), or otherwise clear the report and resend. size_t Keyboard_::press(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers |= (1<<(k-128)); k = 0; } else { // it's a printing key int oldKey = k; k = pgm_read_byte(_asciimap + k); if (!k) { setWriteError(); return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers |= 0x02; // the left shift modifier k &= 0x7F; } if (_altGrMap) if (_altGrMap[oldKey]) _keyReport.modifiers |= 0x40; } // Add k to the key report only if it's not already present // and if there is an empty slot. if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && _keyReport.keys[2] != k && _keyReport.keys[3] != k && _keyReport.keys[4] != k && _keyReport.keys[5] != k) { for (i=0; i<6; i++) { if (_keyReport.keys[i] == 0x00) { _keyReport.keys[i] = k; break; } } if (i == 6) { setWriteError(); return 0; } } sendReport(&_keyReport); return 1; } // release() takes the specified key out of the persistent key report and // sends the report. This tells the OS the key is no longer pressed and that // it shouldn't be repeated any more. size_t Keyboard_::release(uint8_t k) { uint8_t i; if (k >= 136) { // it's a non-printing key (not a modifier) k = k - 136; } else if (k >= 128) { // it's a modifier key _keyReport.modifiers &= ~(1<<(k-128)); k = 0; } else { // it's a printing key int oldKey = k; k = pgm_read_byte(_asciimap + k); if (!k) { return 0; } if (k & 0x80) { // it's a capital letter or other character reached with shift _keyReport.modifiers &= ~(0x02); // the left shift modifier k &= 0x7F; if (_altGrMap) if (_altGrMap[oldKey]) _keyReport.modifiers |= 0x40; } // Test the key report to see if k is present. Clear it if it exists. // Check all positions in case the key is present more than once (which it shouldn't be) for (i=0; i<6; i++) { if (0 != k && _keyReport.keys[i] == k) { _keyReport.keys[i] = 0x00; } } sendReport(&_keyReport); return 1; } void Keyboard_::releaseAll(void) { _keyReport.keys[0] = 0; _keyReport.keys[1] = 0; _keyReport.keys[2] = 0; _keyReport.keys[3] = 0; _keyReport.keys[4] = 0; _keyReport.keys[5] = 0; _keyReport.modifiers = 0; sendReport(&_keyReport); } size_t Keyboard_::write(uint8_t c) { uint8_t p = press(c); // Keydown release(c); // Keyup return p; // just return the result of press() since release() almost always returns 1 } Keyboard_ Keyboard; #endif <|endoftext|>
<commit_before>#include "Heap.h" #include "Managed.h" namespace magpie { Heap::Heap() : memory_(NULL), free_(NULL), end_(NULL) {} Heap::~Heap() { if (memory_ != NULL) operator delete(memory_); } void Heap::initialize(size_t size) { ASSERT(memory_ == NULL, "Already initialized."); memory_ = reinterpret_cast<char*>(::operator new(size)); free_ = memory_; end_ = memory_ + size; // Store a zero for the size of the "first" object so that we can tell if // the heap is empty. *reinterpret_cast<size_t*>(memory_) = 0; } void Heap::shutDown() { ASSERT(memory_ != NULL, "Not initialized."); ::operator delete(memory_); memory_ = NULL; free_ = NULL; end_ = NULL; } bool Heap::canAllocate(size_t size) const { // Find the end of the allocated object. char* next = free_ + size + sizeof(size_t); // See if it's past the end of the heap. return next < end_; } void* Heap::allocate(size_t size) { char* allocated = free_; char* next = free_ + size + sizeof(size_t); // Make sure we don't go past the end of the heap. if (next >= end_) return NULL; free_ = next; // Store the allocated size so we know where the next object starts. *reinterpret_cast<size_t*>(allocated) = size; // The object is right after the size. return allocated + sizeof(size_t); } void Heap::reset() { free_ = memory_; } Managed* Heap::getFirst() { // Bail if there are no objects in the heap. if (*reinterpret_cast<size_t*>(memory_) == 0) return NULL; // Skip past the size. return reinterpret_cast<Managed*>(memory_ + sizeof(size_t)); } Managed* Heap::getNext(Managed* current) { // Get the size of the current object so we know how far to skip. char* pos = reinterpret_cast<char*>(current); size_t size = *reinterpret_cast<size_t*>(pos - sizeof(size_t)); char* next = pos + size; // Don't walk past the end. if (next >= free_) return NULL; // Skip past the size header of the next object. return reinterpret_cast<Managed*>(next + sizeof(size_t)); } }<commit_msg>Clean up a bit.<commit_after>#include "Heap.h" #include "Managed.h" namespace magpie { Heap::Heap() : memory_(NULL), free_(NULL), end_(NULL) {} Heap::~Heap() { if (memory_ != NULL) operator delete(memory_); } void Heap::initialize(size_t size) { ASSERT(memory_ == NULL, "Already initialized."); memory_ = reinterpret_cast<char*>(::operator new(size)); free_ = memory_; end_ = memory_ + size; // Store a zero for the size of the "first" object so that we can tell if // the heap is empty. *reinterpret_cast<size_t*>(memory_) = 0; } void Heap::shutDown() { ASSERT(memory_ != NULL, "Not initialized."); ::operator delete(memory_); memory_ = NULL; free_ = NULL; end_ = NULL; } bool Heap::canAllocate(size_t size) const { // Find the end of the allocated object. char* next = free_ + size + sizeof(size_t); // See if it's past the end of the heap. return next < end_; } void* Heap::allocate(size_t size) { // The allocated object will start just after its size. char* allocated = free_ + sizeof(size_t); char* next = allocated + size; // Make sure we don't go past the end of the heap. if (next >= end_) return NULL; free_ = next; // Store the allocated size so we know where the next object starts. *reinterpret_cast<size_t*>(allocated - sizeof(size_t)) = size; return allocated; } void Heap::reset() { free_ = memory_; } Managed* Heap::getFirst() { // Bail if there are no objects in the heap. if (*reinterpret_cast<size_t*>(memory_) == 0) return NULL; // Skip past the size. return reinterpret_cast<Managed*>(memory_ + sizeof(size_t)); } Managed* Heap::getNext(Managed* current) { // Get the size of the current object so we know how far to skip. char* pos = reinterpret_cast<char*>(current); size_t size = *reinterpret_cast<size_t*>(pos - sizeof(size_t)); char* next = pos + size; // Don't walk past the end. if (next >= free_) return NULL; // Skip past the size header of the next object. return reinterpret_cast<Managed*>(next + sizeof(size_t)); } }<|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; uint8_t ds_; bool exp_; uint8_t pagen_; uint8_t i2c_adr_(bool exta = 0) const { return EEPROM_ADR_ | ds_ | (static_cast<uint8_t>(exta) << 2); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), ds_(0), exp_(false), pagen_(1) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] ds デバイス選択ビット @param[in] exp 「true」の場合、2バイトアドレス @param[in] pagen ページサイズ */ //-----------------------------------------------------------------// void start(uint8_t ds, bool exp, uint8_t pagen) { ds_ = ds & 7; exp_ = exp; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), tmp, 2)) { return false; } if(!i2c_io_.recv(i2c_adr_((adr >> 16) & 1), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(i2c_adr_(), tmp, 1)) { return false; } if(!i2c_io_.recv(i2c_adr_(), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { const uint8_t* end = src + len; while(src < end) { uint16_t l = pagen_ - static_cast<uint16_t>(src) & (pagen_ - 1); if(exp_) { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr >> 8, adr & 255, src, l)) { return false; } } else { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr & 255, src, l)) { return false; } } src += l; adr += l; if(src <= end) { // 書き込み終了を待つポーリング bool ok = false; for(uint16_t i = 0; i < 600; ++i) { // 最大で6ms待つ utils::delay::micro_second(10); uint8_t tmp[1]; if(read(adr, tmp, 1)) { ok = true; break; } } if(!ok) return false; } } return true; } }; } <commit_msg>add write_sync 関数<commit_after>#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; uint8_t ds_; bool exp_; uint8_t pagen_; uint8_t i2c_adr_(bool exta = 0) const { return EEPROM_ADR_ | ds_ | (static_cast<uint8_t>(exta) << 2); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), ds_(0), exp_(false), pagen_(1) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] ds デバイス選択ビット @param[in] exp 「true」の場合、2バイトアドレス @param[in] pagen ページサイズ */ //-----------------------------------------------------------------// void start(uint8_t ds, bool exp, uint8_t pagen) { ds_ = ds & 7; exp_ = exp; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief 書き込み同期 @param[in] adr 読み込みテストアドレス @param[in] delay 待ち時間(10us単位) @return デバイスエラーなら「false」 */ //-----------------------------------------------------------------// bool sync_write(uint32_t adr = 0, uint16_t delay = 600) const { bool ok = false; for(uint16_t i = 0; i < delay; ++i) { utils::delay::micro_second(10); uint8_t tmp[1]; if(read(adr, tmp, 1)) { ok = true; break; } } return ok; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), tmp, 2)) { return false; } if(!i2c_io_.recv(i2c_adr_((adr >> 16) & 1), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(i2c_adr_(), tmp, 1)) { return false; } if(!i2c_io_.recv(i2c_adr_(), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { const uint8_t* end = src + len; while(src < end) { uint16_t l = pagen_ - static_cast<uint16_t>(src) & (pagen_ - 1); if(exp_) { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr >> 8, adr & 255, src, l)) { return false; } } else { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr & 255, src, l)) { return false; } } src += l; adr += l; if(src < end) { // 書き込み終了を待つポーリング if(!sync_write(adr)) { return false; } } } return true; } }; } <|endoftext|>
<commit_before>#include <sirius.h> using namespace sirius; void test1() { int N = 400; matrix<double_complex> A(N, N); matrix<double_complex> B(N, N); matrix<double_complex> C(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) B(j, i) = utils::random<double_complex>(); } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) A(i, j) = B(i, j) + std::conj(B(j, i)); } A >> B; linalg<device_t::CPU>::heinv(N, A); linalg<device_t::CPU>::hemm(0, 0, N, N, double_complex(1, 0), A, B, double_complex(0, 0), C); int err = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double_complex z = C(i, j); if (i == j) z -= 1.0; if (std::abs(z) > 1e-10) err++; } } linalg<device_t::CPU>::hemm(1, 0, N, N, double_complex(1, 0), A, B, double_complex(0, 0), C); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double_complex z = C(i, j); if (i == j) z -= 1.0; if (std::abs(z) > 1e-10) err++; } } if (err) { printf("test1 failed!\n"); exit(1); } else { printf("test1 passed!\n"); } } template <typename T> void test2() { int N = 400; matrix<T> A(N, N); matrix<T> B(N, N); matrix<T> C(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { A(j, i) = utils::random<T>(); } } A >> B; linalg<device_t::CPU>::geinv(N, A); linalg<device_t::CPU>::gemm(0, 0, N, N, N, A, B, C); int err = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { T c = C(i, j); if (i == j) { c -= 1.0; } if (std::abs(c) > 1e-10) { err++; } } } linalg<device_t::CPU>::gemm(0, 0, N, N, N, A, B, C); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { T c = C(i, j); if (i == j) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } if (err) { printf("test2 failed!\n"); exit(1); } else { printf("test2 passed!\n"); } } #ifdef __SCALAPACK template <typename T> void test3() { int bs = 32; int num_ranks = Communicator::world().size(); int nrc = (int)std::sqrt(0.1 + num_ranks); if (nrc * nrc != num_ranks) { printf("wrong mpi grid\n"); exit(-1); } int N = 400; BLACS_grid blacs_grid(Communicator::world(), nrc, nrc); dmatrix<T> A(N, N, blacs_grid, bs, bs); dmatrix<T> B(N, N, blacs_grid, bs, bs); dmatrix<T> C(N, N, blacs_grid, bs, bs); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) A.set(j, i, utils::random<T>()); } A >> B; T alpha = 1.0; T beta = 0.0; linalg<device_t::CPU>::geinv(N, A); linalg<device_t::CPU>::gemm(0, 0, N, N, N, alpha, A, B, beta, C); int err = 0; for (int i = 0; i < C.num_cols_local(); i++) { for (int j = 0; j < C.num_rows_local(); j++) { T c = C(j, i); if (C.icol(i) == C.irow(j)) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } linalg<device_t::CPU>::gemm(0, 0, N, N, N, alpha, B, A, beta, C); for (int i = 0; i < C.num_cols_local(); i++) { for (int j = 0; j < C.num_rows_local(); j++) { T c = C(j, i); if (C.icol(i) == C.irow(j)) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } if (err) { printf("test3 failed!\n"); exit(1); } else { printf("test3 passed!\n"); } } #endif int main(int argn, char** argv) { sirius::initialize(1); test1(); test2<double>(); test2<double_complex>(); #ifdef __SCALAPACK test3<double_complex>(); #endif sirius::finalize(); return 0; } <commit_msg>fix a test<commit_after>#include <sirius.h> using namespace sirius; void test1() { int N = 400; matrix<double_complex> A(N, N); matrix<double_complex> B(N, N); matrix<double_complex> C(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) B(j, i) = utils::random<double_complex>(); } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) A(i, j) = B(i, j) + std::conj(B(j, i)); } A >> B; linalg<device_t::CPU>::heinv(N, A); linalg2(linalg_t::blas).hemm('L', 'U', N, N, &linalg_const<double_complex>::one(), &A(0, 0), A.ld(), &B(0, 0), B.ld(), &linalg_const<double_complex>::zero(), &C(0, 0), C.ld()); int err = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double_complex z = C(i, j); if (i == j) z -= 1.0; if (std::abs(z) > 1e-10) err++; } } linalg2(linalg_t::blas).hemm('L', 'U', N, N, &linalg_const<double_complex>::one(), &A(0, 0), A.ld(), &B(0, 0), B.ld(), &linalg_const<double_complex>::zero(), &C(0, 0), C.ld()); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double_complex z = C(i, j); if (i == j) z -= 1.0; if (std::abs(z) > 1e-10) err++; } } if (err) { printf("test1 failed!\n"); exit(1); } else { printf("test1 passed!\n"); } } template <typename T> void test2() { int N = 400; matrix<T> A(N, N); matrix<T> B(N, N); matrix<T> C(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { A(j, i) = utils::random<T>(); } } A >> B; linalg<device_t::CPU>::geinv(N, A); linalg<device_t::CPU>::gemm(0, 0, N, N, N, A, B, C); int err = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { T c = C(i, j); if (i == j) { c -= 1.0; } if (std::abs(c) > 1e-10) { err++; } } } linalg<device_t::CPU>::gemm(0, 0, N, N, N, A, B, C); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { T c = C(i, j); if (i == j) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } if (err) { printf("test2 failed!\n"); exit(1); } else { printf("test2 passed!\n"); } } #ifdef __SCALAPACK template <typename T> void test3() { int bs = 32; int num_ranks = Communicator::world().size(); int nrc = (int)std::sqrt(0.1 + num_ranks); if (nrc * nrc != num_ranks) { printf("wrong mpi grid\n"); exit(-1); } int N = 400; BLACS_grid blacs_grid(Communicator::world(), nrc, nrc); dmatrix<T> A(N, N, blacs_grid, bs, bs); dmatrix<T> B(N, N, blacs_grid, bs, bs); dmatrix<T> C(N, N, blacs_grid, bs, bs); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) A.set(j, i, utils::random<T>()); } A >> B; T alpha = 1.0; T beta = 0.0; linalg<device_t::CPU>::geinv(N, A); linalg<device_t::CPU>::gemm(0, 0, N, N, N, alpha, A, B, beta, C); int err = 0; for (int i = 0; i < C.num_cols_local(); i++) { for (int j = 0; j < C.num_rows_local(); j++) { T c = C(j, i); if (C.icol(i) == C.irow(j)) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } linalg<device_t::CPU>::gemm(0, 0, N, N, N, alpha, B, A, beta, C); for (int i = 0; i < C.num_cols_local(); i++) { for (int j = 0; j < C.num_rows_local(); j++) { T c = C(j, i); if (C.icol(i) == C.irow(j)) c -= 1.0; if (std::abs(c) > 1e-10) err++; } } if (err) { printf("test3 failed!\n"); exit(1); } else { printf("test3 passed!\n"); } } #endif int main(int argn, char** argv) { sirius::initialize(1); test1(); test2<double>(); test2<double_complex>(); #ifdef __SCALAPACK test3<double_complex>(); #endif sirius::finalize(); return 0; } <|endoftext|>
<commit_before>// Bit buffer used for assembling tracks #include "SAMdisk.h" #include "TrackBuffer.h" TrackBuffer::TrackBuffer (bool mfm) : m_mfm(mfm) { } void TrackBuffer::addByte (int data, int clock) { for (auto i = 0; i < 8; ++i) { addBit((clock & 0x80) != 0); addBit((data & 0x80) != 0); clock <<= 1; data <<= 1; } } void TrackBuffer::addDataBit (bool one) { if (m_mfm) { // MFM has a reversal between consecutive zeros (clock or data) addBit(!m_onelast && !one); addBit(one); } else { // FM has a reversal before every data bit addBit(true); addBit(one); } } void TrackBuffer::addByte (int byte) { for (auto i = 0; i < 8; ++i) { addDataBit((byte & 0x80) != 0); byte <<= 1; } } void TrackBuffer::addBlock (int byte, int count) { for (int i = 0; i < count; ++i) addByte(byte); } void TrackBuffer::addBlock (const void *buf, int len) { auto pb = reinterpret_cast<const uint8_t *>(buf); while (len-- > 0) addByte(*pb++); } void TrackBuffer::addGap (int count, int fill) { addBlock(fill, count); } void TrackBuffer::addSync () { auto sync{0x00}; addBlock(sync, m_mfm ? 12 : 6); } void TrackBuffer::addAM (int type) { if (m_mfm) { addByte(0xa1, 0x0a); // A1 with missing clock bit addByte(0xa1, 0x0a); // clock: 0 0 0 0 1 X 1 0 addByte(0xa1, 0x0a); // data: 1 0 1 0 0 0 0 1 addByte(type); m_crc.init(0xcdb4); // A1A1A1 m_crc.add(type); } else { // FM address marks use clock of C7 addByte(type, 0xc7); m_crc.init(); m_crc.add(type); } } void TrackBuffer::addIAM () { if (m_mfm) { addByte(0xc2, 0x14); // C2 with missing clock bit addByte(0xc2, 0x14); // clock: 0 0 0 1 X 1 0 0 addByte(0xc2, 0x14); // data: 1 1 0 0 0 0 1 0 addByte(0xfc); } else { // FM IAM uses a clock of D7 addByte(0xfc, 0xd7); } } void TrackBuffer::addIDAM () { addAM(0xfe); } void TrackBuffer::addDAM () { addAM(0xfb); } void TrackBuffer::addDDAM () { addAM(0xf8); } void TrackBuffer::addAltDAM () { addAM(0xfa); } void TrackBuffer::addAltDDAM () // RX02 { addAM(0xfd); } void TrackBuffer::addCRC () { addByte(m_crc >> 8); addByte(m_crc & 0xff); } void TrackBuffer::addTrackStart () { // System/34 double density addGap(80); // gap 4a addSync(); addIAM(); addGap(50); // gap 1 } /* void TrackBuffer::addTrackEnd () { while (m_total_ticks < m_trackend_ticks) addByte(GAP_FILL_BYTE); // gap 4b } */ void TrackBuffer::addSectorHeader (int cyl, int head, int sector, int size) { addIDAM(); addByte(cyl); addByte(head); addByte(sector); addByte(size); m_crc.add(cyl); m_crc.add(head); m_crc.add(sector); m_crc.add(size); addCRC(); } void TrackBuffer::addSectorHeader(const Header &header) { addSectorHeader(header.cyl, header.head, header.sector, header.size); } void TrackBuffer::addSectorData (const void *buf, int len, bool deleted) { auto am{deleted ? 0xf8 : 0xfb}; addAM(am); addBlock(buf, len); m_crc.add(buf, len); addCRC(); } void TrackBuffer::addSectorData(const Data &data, bool deleted) { addSectorData(data.data(), data.size(), deleted); } void TrackBuffer::addSector (int cyl, int head, int sector, int size, const void *buf, int len, int gap3, bool deleted) { addSync(); addSectorHeader(cyl, head, sector, size); addGap(m_mfm ? 22 : 11); // gap 2 addSync(); addSectorData(buf, len, deleted); addGap(gap3); // gap 3 } void TrackBuffer::addSector (const Header &header, const Data &data, int gap3, bool deleted) { addSector(header.cyl, header.head, header.sector, header.size, data.data(), data.size(), gap3, deleted); } void TrackBuffer::addAmigaTrackStart () { m_mfm = true; auto fill{0x00}; addBlock(fill, 60); // Shift the first sector away from the index } /* void TrackBuffer::addAmigaTrackEnd () { while (m_total_ticks < m_B_ticks) addByte(0x00); } */ void TrackBuffer::addAmigaDword (uint32_t dword, uint32_t &checksum) { dword = util::htobe(dword); std::vector<uint32_t> bits = splitAmigaBits(&dword, sizeof(uint32_t), checksum); addAmigaBits(bits); } void TrackBuffer::addAmigaBits (std::vector<uint32_t> &bits) { for (auto it = bits.begin(); it != bits.end(); ++it) { uint32_t data = *it; for (auto i = 0; i < 16; ++i) { addDataBit((data & 0x40000000) != 0); data <<= 2; } } } std::vector<uint32_t> TrackBuffer::splitAmigaBits (const void *buf, int len, uint32_t &checksum) { auto dwords = len / static_cast<int>(sizeof(uint32_t)); const uint32_t *pdw = reinterpret_cast<const uint32_t*>(buf); std::vector<uint32_t> odddata; odddata.reserve(dwords * 2); // Even then odd passes over the data for (auto i = 0; i < 2; ++i) { // All DWORDs in the block for (int j = 0; j < dwords; ++j) { uint32_t bits = 0; uint32_t data = frombe32(pdw[j]) << i; // 16 bits (odd or even) from each DWORD pass for (auto k = 0; k < 16; ++k) { bits |= ((data & 0x80000000) >> (1 + k * 2)); data <<= 2; } odddata.insert(odddata.end(), bits); checksum ^= bits; } } return odddata; } void TrackBuffer::addAmigaSector (int cyl, int head, int sector, int remain, const void *buf) { addByte(0x00); addByte(0x00); addByte(0xa1, 0x0a); // A1 with missing clock bit addByte(0xa1, 0x0a); uint32_t checksum = 0; uint32_t info = (0xff << 24) | (((cyl << 1) | head) << 16) | (sector << 8) | remain; addAmigaDword(info, checksum); uint32_t sector_label[4] = {}; auto bits = splitAmigaBits(sector_label, sizeof(sector_label), checksum); addAmigaBits(bits); addAmigaDword(checksum, checksum); checksum = 0; bits = splitAmigaBits(buf, 512, checksum); addAmigaDword(checksum, checksum); addAmigaBits(bits); } <commit_msg>Fixed clock bug in bitstream generation<commit_after>// Bit buffer used for assembling tracks #include "SAMdisk.h" #include "TrackBuffer.h" TrackBuffer::TrackBuffer (bool mfm) : m_mfm(mfm) { } void TrackBuffer::addByte (int data, int clock) { for (auto i = 0; i < 8; ++i) { addBit((clock & 0x80) != 0); addBit((data & 0x80) != 0); clock <<= 1; data <<= 1; } m_onelast = (data & 0x100) != 0; } void TrackBuffer::addDataBit (bool one) { if (m_mfm) { // MFM has a reversal between consecutive zeros (clock or data) addBit(!m_onelast && !one); addBit(one); } else { // FM has a reversal before every data bit addBit(true); addBit(one); } m_onelast = one; } void TrackBuffer::addByte (int byte) { for (auto i = 0; i < 8; ++i) { addDataBit((byte & 0x80) != 0); byte <<= 1; } } void TrackBuffer::addBlock (int byte, int count) { for (int i = 0; i < count; ++i) addByte(byte); } void TrackBuffer::addBlock (const void *buf, int len) { auto pb = reinterpret_cast<const uint8_t *>(buf); while (len-- > 0) addByte(*pb++); } void TrackBuffer::addGap (int count, int fill) { addBlock(fill, count); } void TrackBuffer::addSync () { auto sync{0x00}; addBlock(sync, m_mfm ? 12 : 6); } void TrackBuffer::addAM (int type) { if (m_mfm) { addByte(0xa1, 0x0a); // A1 with missing clock bit addByte(0xa1, 0x0a); // clock: 0 0 0 0 1 X 1 0 addByte(0xa1, 0x0a); // data: 1 0 1 0 0 0 0 1 addByte(type); m_crc.init(0xcdb4); // A1A1A1 m_crc.add(type); } else { // FM address marks use clock of C7 addByte(type, 0xc7); m_crc.init(); m_crc.add(type); } } void TrackBuffer::addIAM () { if (m_mfm) { addByte(0xc2, 0x14); // C2 with missing clock bit addByte(0xc2, 0x14); // clock: 0 0 0 1 X 1 0 0 addByte(0xc2, 0x14); // data: 1 1 0 0 0 0 1 0 addByte(0xfc); } else { // FM IAM uses a clock of D7 addByte(0xfc, 0xd7); } } void TrackBuffer::addIDAM () { addAM(0xfe); } void TrackBuffer::addDAM () { addAM(0xfb); } void TrackBuffer::addDDAM () { addAM(0xf8); } void TrackBuffer::addAltDAM () { addAM(0xfa); } void TrackBuffer::addAltDDAM () // RX02 { addAM(0xfd); } void TrackBuffer::addCRC () { addByte(m_crc >> 8); addByte(m_crc & 0xff); } void TrackBuffer::addTrackStart () { // System/34 double density addGap(80); // gap 4a addSync(); addIAM(); addGap(50); // gap 1 } /* void TrackBuffer::addTrackEnd () { while (m_total_ticks < m_trackend_ticks) addByte(GAP_FILL_BYTE); // gap 4b } */ void TrackBuffer::addSectorHeader (int cyl, int head, int sector, int size) { addIDAM(); addByte(cyl); addByte(head); addByte(sector); addByte(size); m_crc.add(cyl); m_crc.add(head); m_crc.add(sector); m_crc.add(size); addCRC(); } void TrackBuffer::addSectorHeader(const Header &header) { addSectorHeader(header.cyl, header.head, header.sector, header.size); } void TrackBuffer::addSectorData (const void *buf, int len, bool deleted) { auto am{deleted ? 0xf8 : 0xfb}; addAM(am); addBlock(buf, len); m_crc.add(buf, len); addCRC(); } void TrackBuffer::addSectorData(const Data &data, bool deleted) { addSectorData(data.data(), data.size(), deleted); } void TrackBuffer::addSector (int cyl, int head, int sector, int size, const void *buf, int len, int gap3, bool deleted) { addSync(); addSectorHeader(cyl, head, sector, size); addGap(m_mfm ? 22 : 11); // gap 2 addSync(); addSectorData(buf, len, deleted); addGap(gap3); // gap 3 } void TrackBuffer::addSector (const Header &header, const Data &data, int gap3, bool deleted) { addSector(header.cyl, header.head, header.sector, header.size, data.data(), data.size(), gap3, deleted); } void TrackBuffer::addAmigaTrackStart () { m_mfm = true; auto fill{0x00}; addBlock(fill, 60); // Shift the first sector away from the index } /* void TrackBuffer::addAmigaTrackEnd () { while (m_total_ticks < m_B_ticks) addByte(0x00); } */ void TrackBuffer::addAmigaDword (uint32_t dword, uint32_t &checksum) { dword = util::htobe(dword); std::vector<uint32_t> bits = splitAmigaBits(&dword, sizeof(uint32_t), checksum); addAmigaBits(bits); } void TrackBuffer::addAmigaBits (std::vector<uint32_t> &bits) { for (auto it = bits.begin(); it != bits.end(); ++it) { uint32_t data = *it; for (auto i = 0; i < 16; ++i) { addDataBit((data & 0x40000000) != 0); data <<= 2; } } } std::vector<uint32_t> TrackBuffer::splitAmigaBits (const void *buf, int len, uint32_t &checksum) { auto dwords = len / static_cast<int>(sizeof(uint32_t)); const uint32_t *pdw = reinterpret_cast<const uint32_t*>(buf); std::vector<uint32_t> odddata; odddata.reserve(dwords * 2); // Even then odd passes over the data for (auto i = 0; i < 2; ++i) { // All DWORDs in the block for (int j = 0; j < dwords; ++j) { uint32_t bits = 0; uint32_t data = frombe32(pdw[j]) << i; // 16 bits (odd or even) from each DWORD pass for (auto k = 0; k < 16; ++k) { bits |= ((data & 0x80000000) >> (1 + k * 2)); data <<= 2; } odddata.insert(odddata.end(), bits); checksum ^= bits; } } return odddata; } void TrackBuffer::addAmigaSector (int cyl, int head, int sector, int remain, const void *buf) { addByte(0x00); addByte(0x00); addByte(0xa1, 0x0a); // A1 with missing clock bit addByte(0xa1, 0x0a); uint32_t checksum = 0; uint32_t info = (0xff << 24) | (((cyl << 1) | head) << 16) | (sector << 8) | remain; addAmigaDword(info, checksum); uint32_t sector_label[4] = {}; auto bits = splitAmigaBits(sector_label, sizeof(sector_label), checksum); addAmigaBits(bits); addAmigaDword(checksum, checksum); checksum = 0; bits = splitAmigaBits(buf, 512, checksum); addAmigaDword(checksum, checksum); addAmigaBits(bits); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include <boost/variant/variant.hpp> #include "TypeChecker.hpp" #include "Compiler.hpp" #include "GetTypeVisitor.hpp" #include "SemanticalException.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "Types.hpp" #include "Variable.hpp" #include "Options.hpp" #include "TypeTransformer.hpp" #include "VisitorUtils.hpp" #include "ASTVisitor.hpp" #include "ast/SourceFile.hpp" using namespace eddic; struct CheckerVisitor : public boost::static_visitor<> { AUTO_RECURSE_PROGRAM() AUTO_RECURSE_FUNCTION_CALLS() AUTO_RECURSE_SIMPLE_LOOPS() AUTO_RECURSE_BRANCHES() AUTO_RECURSE_BINARY_CONDITION() AUTO_RECURSE_MINUS_PLUS_VALUES() void operator()(ast::FunctionDeclaration& declaration){ visit_each(*this, declaration.Content->instructions); } void operator()(ast::GlobalVariableDeclaration& declaration){ Type type = stringToType(declaration.Content->variableType); Type valueType = visit(GetTypeVisitor(), *declaration.Content->value); if (valueType != type) { throw SemanticalException("Incompatible type for global variable " + declaration.Content->variableName); } } void operator()(ast::Import&){ //Nothing to check here } void operator()(ast::StandardImport&){ //Nothing to check here } void operator()(ast::GlobalArrayDeclaration&){ //Nothing to check here } void operator()(ast::Foreach& foreach){ visit_each(*this, foreach.Content->instructions); } void operator()(ast::ForeachIn& foreach){ //TODO Check types of array //TODO Check type of varaible = base of array visit_each(*this, foreach.Content->instructions); } template<typename T> void checkAssignment(T& assignment){ visit(*this, assignment.Content->value); auto var = assignment.Content->context->getVariable(assignment.Content->variableName); Type valueType = visit(GetTypeVisitor(), assignment.Content->value); if (valueType != var->type()) { throw SemanticalException("Incompatible type in assignment of variable " + assignment.Content->variableName); } if(var->type().isConst()){ throw SemanticalException("The variable " + assignment.Content->variableName + " is const, cannot edit it"); } if(var->position().isParameter()){ throw SemanticalException("Cannot change the value of the parameter " + assignment.Content->variableName); } } void operator()(ast::Assignment& assignment){ checkAssignment(assignment); } void operator()(ast::CompoundAssignment& assignment){ checkAssignment(assignment); } void operator()(ast::SuffixOperation& operation){ auto var = operation.Content->variable; if(var->type().isArray() || var->type().base() != BaseType::INT){ throw SemanticalException("The variable " + var->name() + " is not of type int, cannot increment or decrement it"); } if(var->type().isConst()){ throw SemanticalException("The variable " + var->name() + " is const, cannot edit it"); } } void operator()(ast::PrefixOperation& operation){ auto var = operation.Content->variable; if(var->type().isArray() || var->type().base() != BaseType::INT){ throw SemanticalException("The variable " + var->name() + " is not of type int, cannot increment or decrement it"); } if(var->type().isConst()){ throw SemanticalException("The variable " + var->name() + " is const, cannot edit it"); } } void operator()(ast::Return& return_){ visit(*this, return_.Content->value); Type returnValueType = visit(GetTypeVisitor(), return_.Content->value); if(returnValueType != return_.Content->function->returnType){ throw SemanticalException("The return value is not of the good type in the function " + return_.Content->function->name); } } void operator()(ast::ArrayAssignment& assignment){ visit(*this, assignment.Content->indexValue); visit(*this, assignment.Content->value); auto var = assignment.Content->context->getVariable(assignment.Content->variableName); Type valueType = visit(GetTypeVisitor(), assignment.Content->value); if (valueType.base() != var->type().base()) { throw SemanticalException("Incompatible type in assignment of array " + assignment.Content->variableName); } Type indexType = visit(GetTypeVisitor(), assignment.Content->indexValue); if (indexType.base() != BaseType::INT) { throw SemanticalException("Invalid index value type in assignment of array " + assignment.Content->variableName); } } void operator()(ast::VariableDeclaration& declaration){ visit(*this, *declaration.Content->value); Type variableType = stringToType(declaration.Content->variableType); Type valueType = visit(GetTypeVisitor(), *declaration.Content->value); if (valueType != variableType) { throw SemanticalException("Incompatible type in declaration of variable " + declaration.Content->variableName); } } void operator()(ast::ArrayDeclaration&){ //No need for type checking here } void operator()(ast::Swap& swap){ if (swap.Content->lhs_var->type() != swap.Content->rhs_var->type()) { throw SemanticalException("Swap of variables of incompatible type"); } } void operator()(ast::ArrayValue& array){ visit(*this, array.Content->indexValue); Type valueType = visit(GetTypeVisitor(), array.Content->indexValue); if (valueType.base() != BaseType::INT || valueType.isArray()) { throw SemanticalException("Invalid index for the array " + array.Content->arrayName); } } void operator()(ast::ComposedValue& value){ visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); GetTypeVisitor visitor; Type type = visit(visitor, value.Content->first); for(auto& operation : value.Content->operations){ Type operationType = visit(visitor, operation.get<1>()); if(type != operationType){ throw SemanticalException("Incompatible type"); } } } void operator()(ast::BuiltinOperator& builtin){ //TODO } void operator()(ast::VariableValue&){ //Nothing to check here } void operator()(ast::TerminalNode&){ //Terminal nodes have no need for type checking } }; void TypeChecker::check(ast::SourceFile& program) const { CheckerVisitor visitor; visit_non_variant(visitor, program); } <commit_msg>Implement type checking for built in operators<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include <boost/variant/variant.hpp> #include "TypeChecker.hpp" #include "Compiler.hpp" #include "GetTypeVisitor.hpp" #include "SemanticalException.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "Types.hpp" #include "Variable.hpp" #include "Options.hpp" #include "TypeTransformer.hpp" #include "VisitorUtils.hpp" #include "ASTVisitor.hpp" #include "ast/SourceFile.hpp" using namespace eddic; struct CheckerVisitor : public boost::static_visitor<> { AUTO_RECURSE_PROGRAM() AUTO_RECURSE_FUNCTION_CALLS() AUTO_RECURSE_SIMPLE_LOOPS() AUTO_RECURSE_BRANCHES() AUTO_RECURSE_BINARY_CONDITION() AUTO_RECURSE_MINUS_PLUS_VALUES() void operator()(ast::FunctionDeclaration& declaration){ visit_each(*this, declaration.Content->instructions); } void operator()(ast::GlobalVariableDeclaration& declaration){ Type type = stringToType(declaration.Content->variableType); Type valueType = visit(GetTypeVisitor(), *declaration.Content->value); if (valueType != type) { throw SemanticalException("Incompatible type for global variable " + declaration.Content->variableName); } } void operator()(ast::Import&){ //Nothing to check here } void operator()(ast::StandardImport&){ //Nothing to check here } void operator()(ast::GlobalArrayDeclaration&){ //Nothing to check here } void operator()(ast::Foreach& foreach){ visit_each(*this, foreach.Content->instructions); } void operator()(ast::ForeachIn& foreach){ //TODO Check types of array //TODO Check type of varaible = base of array visit_each(*this, foreach.Content->instructions); } template<typename T> void checkAssignment(T& assignment){ visit(*this, assignment.Content->value); auto var = assignment.Content->context->getVariable(assignment.Content->variableName); Type valueType = visit(GetTypeVisitor(), assignment.Content->value); if (valueType != var->type()) { throw SemanticalException("Incompatible type in assignment of variable " + assignment.Content->variableName); } if(var->type().isConst()){ throw SemanticalException("The variable " + assignment.Content->variableName + " is const, cannot edit it"); } if(var->position().isParameter()){ throw SemanticalException("Cannot change the value of the parameter " + assignment.Content->variableName); } } void operator()(ast::Assignment& assignment){ checkAssignment(assignment); } void operator()(ast::CompoundAssignment& assignment){ checkAssignment(assignment); } void operator()(ast::SuffixOperation& operation){ auto var = operation.Content->variable; if(var->type().isArray() || var->type().base() != BaseType::INT){ throw SemanticalException("The variable " + var->name() + " is not of type int, cannot increment or decrement it"); } if(var->type().isConst()){ throw SemanticalException("The variable " + var->name() + " is const, cannot edit it"); } } void operator()(ast::PrefixOperation& operation){ auto var = operation.Content->variable; if(var->type().isArray() || var->type().base() != BaseType::INT){ throw SemanticalException("The variable " + var->name() + " is not of type int, cannot increment or decrement it"); } if(var->type().isConst()){ throw SemanticalException("The variable " + var->name() + " is const, cannot edit it"); } } void operator()(ast::Return& return_){ visit(*this, return_.Content->value); Type returnValueType = visit(GetTypeVisitor(), return_.Content->value); if(returnValueType != return_.Content->function->returnType){ throw SemanticalException("The return value is not of the good type in the function " + return_.Content->function->name); } } void operator()(ast::ArrayAssignment& assignment){ visit(*this, assignment.Content->indexValue); visit(*this, assignment.Content->value); auto var = assignment.Content->context->getVariable(assignment.Content->variableName); Type valueType = visit(GetTypeVisitor(), assignment.Content->value); if (valueType.base() != var->type().base()) { throw SemanticalException("Incompatible type in assignment of array " + assignment.Content->variableName); } Type indexType = visit(GetTypeVisitor(), assignment.Content->indexValue); if (indexType.base() != BaseType::INT) { throw SemanticalException("Invalid index value type in assignment of array " + assignment.Content->variableName); } } void operator()(ast::VariableDeclaration& declaration){ visit(*this, *declaration.Content->value); Type variableType = stringToType(declaration.Content->variableType); Type valueType = visit(GetTypeVisitor(), *declaration.Content->value); if (valueType != variableType) { throw SemanticalException("Incompatible type in declaration of variable " + declaration.Content->variableName); } } void operator()(ast::ArrayDeclaration&){ //No need for type checking here } void operator()(ast::Swap& swap){ if (swap.Content->lhs_var->type() != swap.Content->rhs_var->type()) { throw SemanticalException("Swap of variables of incompatible type"); } } void operator()(ast::ArrayValue& array){ visit(*this, array.Content->indexValue); Type valueType = visit(GetTypeVisitor(), array.Content->indexValue); if (valueType.base() != BaseType::INT || valueType.isArray()) { throw SemanticalException("Invalid index for the array " + array.Content->arrayName); } } void operator()(ast::ComposedValue& value){ visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); GetTypeVisitor visitor; Type type = visit(visitor, value.Content->first); for(auto& operation : value.Content->operations){ Type operationType = visit(visitor, operation.get<1>()); if(type != operationType){ throw SemanticalException("Incompatible type"); } } } void operator()(ast::BuiltinOperator& builtin){ for_each(builtin.Content->values.begin(), builtin.Content->values.end(), [&](ast::Value& value){ visit(*this, value); }); if(builtin.Content->values.size() < 1){ throw SemanticalException("Too few arguments to the builtin operator"); } if(builtin.Content->values.size() > 1){ throw SemanticalException("Too many arguments to the builtin operator"); } GetTypeVisitor visitor; Type type = visit(visitor, builtin.Content->values[0]); if(builtin.Content->type == ast::BuiltinType::SIZE){ if(!type.isArray()){ throw SemanticalException("The builtin size() operator takes only array as arguments"); } } else if(builtin.Content->type == ast::BuiltinType::LENGTH){ if(type.isArray() || type.base() != BaseType::STRING){ throw SemanticalException("The builtin length() operator takes only string as arguments"); } } } void operator()(ast::VariableValue&){ //Nothing to check here } void operator()(ast::TerminalNode&){ //Terminal nodes have no need for type checking } }; void TypeChecker::check(ast::SourceFile& program) const { CheckerVisitor visitor; visit_non_variant(visitor, program); } <|endoftext|>
<commit_before>#include "native/UriTemplate.hpp" #include "native/UriTemplateFormat.hpp" #include "native/UriTemplateValue.hpp" #include "native/helper/trace.hpp" #if NNATIVE_USE_RE2 == 1 #include <re2/re2.h> #elif NNATIVE_USE_STDREGEX == 1 #include <regex> #else #endif // elif NNATIVE_USE_STDREGEX == 1 #include <set> using namespace native; namespace { #if NNATIVE_USE_RE2 == 1 bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) { // regex is compiled only at the first call static const re2::RE2 reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName} re2::StringPiece text(&(*iBegin), std::distance(iBegin, iEnd)); re2::StringPiece results[3]; if(!reParam.Match(text, 0, text.size(), re2::RE2::UNANCHORED, results, 3)) { return false; } iText.assign(text.data(), results[0].begin() - text.begin()); Name.assign(results[1].data(), results[1].size()); iFormat.assign(results[2].data(), results[2].size()); iBegin += results[0].end() - text.begin(); return true; } /** * Recursive save extracted data by regex into values * @param ioParsedValues parsed values container to be populated * @param ioPosition current smatch position * @iParams parameters name vector to be added as key values * @iFormatNames format name vector to parse child values, if exists */ void saveValues( UriTemplateValue &ioParsedValues, int &ioPosition, const re2::StringPiece* iMatchResults, const int iMatchResultsSize, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames) { NNATIVE_ASSERT(iParams.size() == iFormatNames.size()); NNATIVE_ASSERT(iMatchResultsSize - ioPosition >= static_cast<int>(iParams.size())); for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i) { const std::string value = iMatchResults[ioPosition++].as_string(); const std::string &name = iParams[i]; const std::string &formatName = iFormatNames[i]; UriTemplateValue &childValue = ioParsedValues.addChild(name, value); const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName); if(format.isRegExOnly()) { continue; } // Parse subvalues of format name const UriTemplate &uriTemplate = format.getTemplate(); NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\""); saveValues(childValue, ioPosition, iMatchResults, iMatchResultsSize, uriTemplate.getParams(), uriTemplate.getFormatNames()); } } bool extractAndSaveValues(UriTemplateValue &oValues, const std::string &iUri, const std::string &iExtractPattern, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames, const bool iAnchorEnd = true) { const re2::RE2 rePattern(iExtractPattern); const int matchResultsSize = 1+rePattern.NumberOfCapturingGroups(); re2::StringPiece matchResults[matchResultsSize]; re2::StringPiece uriPiece(iUri); if(!rePattern.Match(uriPiece, 0, uriPiece.size(), (iAnchorEnd ? re2::RE2::ANCHOR_BOTH : re2::RE2::ANCHOR_START), matchResults, matchResultsSize)) { NNATIVE_DEBUG("No match found"); return false; } int position = 0; // No name to the first parsed value oValues.clear(); oValues.getString() = matchResults[position++].as_string(); // save child values saveValues(oValues, position, matchResults, matchResultsSize, iParams, iFormatNames); return true; } bool containCapturingGroup(const std::string &iPattern) { // regex is compiled only at the first call static const re2::RE2 reCapturingGroup("\\([^?\\)]+\\)"); // true for "(test|other)", but false for non capturing groups (?:test|other) re2::StringPiece strPiece(iPattern); return reCapturingGroup.Match(strPiece, 0, strPiece.size(), re2::RE2::UNANCHORED, nullptr, 0); } #elif NNATIVE_USE_STDREGEX == 1 #include <regex> bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) { // regex is compiled only at the first call static const std::regex reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName} std::smatch results; if(!std::regex_search(iBegin, iEnd, results, reParam)) { return false; } iText.assign(iBegin, iBegin + results.position()); Name = results.str(1); iFormat = results.str(2); iBegin += results.position() + results.length(); return true; } /** * Recursive save extracted data by regex into values * @param ioParsedValues parsed values container to be populated * @param ioPosition current smatch position * @iParams parameters name vector to be added as key values * @iFormatNames format name vector to parse child values, if exists */ void saveValues( UriTemplateValue &ioParsedValues, int &ioPosition, const std::smatch &iMatchResults, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames) { NNATIVE_ASSERT(iParams.size() == iFormatNames.size()); NNATIVE_ASSERT(iMatchResults.size() - ioPosition >= iParams.size()); for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i) { const std::string value = iMatchResults.str(ioPosition++); const std::string &name = iParams[i]; const std::string &formatName = iFormatNames[i]; UriTemplateValue &childValue = ioParsedValues.addChild(name, value); const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName); if(format.isRegExOnly()) { continue; } // Parse subvalues of format name const UriTemplate &uriTemplate = format.getTemplate(); NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\""); saveValues(childValue, ioPosition, iMatchResults, uriTemplate.getParams(), uriTemplate.getFormatNames()); } } bool extractAndSaveValues(UriTemplateValue &oValues, const std::string &iUri, const std::string &iExtractPattern, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames, const bool iAnchorEnd = true) { std::smatch matchResults; const std::regex rePattern(iExtractPattern); if(iAnchorEnd) { if(!std::regex_match(iUri, matchResults, rePattern)) { NNATIVE_DEBUG("No match found"); return false; } } else { if(!std::regex_search(iUri, matchResults, rePattern, std::regex_constants::match_continuous)) { NNATIVE_DEBUG("No match found"); return false; } } int position = 0; // No name to the first parsed value oValues.clear(); oValues.getString() = matchResults.str(position++); // save child values saveValues(oValues, position, matchResults, iParams, iFormatNames); return true; } bool containCapturingGroup(const std::string &iPattern) { // regex is compiled only at the first call static const std::regex reCapturingGroup("\\([^?\\)]+\\)"); // true for "(test|other)", but false for non capturing groups (?:test|other) std::smatch dummyResults; return std::regex_search(iPattern, dummyResults, reCapturingGroup); } #endif // elif NNATIVE_USE_STDREGEX == 1 } /* namespace */ UriTemplate::UriTemplate(const std::string &iTemplate) : _template(iTemplate) { parse(); } UriTemplate::UriTemplate(const UriTemplate &iBaseUriTemplate, const std::string &iTemplateSuffix) : _template(iBaseUriTemplate.getTemplate() + iTemplateSuffix) { parse(); } UriTemplate::UriTemplate(const UriTemplate &iOther) : _template(iOther._template), _matchPattern(iOther._matchPattern), _extractPattern(iOther._extractPattern), _params(iOther._params), _formatNames(iOther._formatNames) { // Avoid parsing because template string is already parsed } void UriTemplate::parse() { NNATIVE_DEBUG("New URI Template \"" << _template << "\""); // should not contain capturing groups. e.g. "/path/(caputeText)/{param1:format1}" NNATIVE_ASSERT_MSG(!ContainCapturingGroup(_template), "URI template \"" << _template << "\" contain capturing groups"); _matchPattern = ""; _extractPattern = ""; std::set<std::string> uniqParams; _params.clear(); _formatNames.clear(); // extract format names std::string::const_iterator begin = _template.begin(); std::string::const_iterator end = _template.end(); std::string textStr; std::string paramName; std::string formatName; while (getNextParameter(begin, end, textStr, paramName, formatName)) { NNATIVE_DEBUG("paramName:"<<paramName<<", formatName:"<<formatName); const UriTemplateFormat& globalFormat = UriTemplateFormat::GetGlobalFormat(formatName); // Check if parameter name duplicate. e.g: "/path{sameParamName:anyFormatName}/other/{sameParamName:anyFormatName}" if(!uniqParams.insert(paramName).second) { NNATIVE_DEBUG("Duplicate parameter name found " << paramName); NNATIVE_ASSERT(0); } _params.push_back(paramName); _formatNames.push_back(formatName); _matchPattern += textStr + globalFormat.getPattern(); _extractPattern += textStr + globalFormat.getPattern(true); } // add the remaing string std::string textRemained(begin, end); _matchPattern += textRemained; // extract pattern may be part of a format name, do net add end of string ("$") _extractPattern += textRemained; NNATIVE_DEBUG("Pattern for match: \"" << _matchPattern << "\""); NNATIVE_DEBUG("Pattern for extraction: \"" << _extractPattern << "\""); } bool UriTemplate::extract(UriTemplateValue &oValues, const std::string &iUri, const bool iAnchorEnd) const { NNATIVE_DEBUG("Extract values from \"" << iUri << "\" by using URI template \"" << _template << "\", pattern: \"" << _extractPattern << "\")"); return extractAndSaveValues(oValues, iUri, _extractPattern, getParams(), getFormatNames(), iAnchorEnd); } bool UriTemplate::ContainCapturingGroup(const std::string &iPattern) { return ::containCapturingGroup(iPattern); } <commit_msg>uriTemplate: re2 resolve non-POD element type issue<commit_after>#include "native/UriTemplate.hpp" #include "native/UriTemplateFormat.hpp" #include "native/UriTemplateValue.hpp" #include "native/helper/trace.hpp" #if NNATIVE_USE_RE2 == 1 #include <re2/re2.h> #elif NNATIVE_USE_STDREGEX == 1 #include <regex> #else #endif // elif NNATIVE_USE_STDREGEX == 1 #include <set> #include <memory> using namespace native; namespace { #if NNATIVE_USE_RE2 == 1 bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) { // regex is compiled only at the first call static const re2::RE2 reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName} re2::StringPiece text(&(*iBegin), std::distance(iBegin, iEnd)); re2::StringPiece results[3]; if(!reParam.Match(text, 0, text.size(), re2::RE2::UNANCHORED, results, 3)) { return false; } iText.assign(text.data(), results[0].begin() - text.begin()); Name.assign(results[1].data(), results[1].size()); iFormat.assign(results[2].data(), results[2].size()); iBegin += results[0].end() - text.begin(); return true; } /** * Recursive save extracted data by regex into values * @param ioParsedValues parsed values container to be populated * @param ioPosition current smatch position * @iParams parameters name vector to be added as key values * @iFormatNames format name vector to parse child values, if exists */ void saveValues( UriTemplateValue &ioParsedValues, int &ioPosition, const re2::StringPiece* iMatchResults, const int iMatchResultsSize, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames) { NNATIVE_ASSERT(iParams.size() == iFormatNames.size()); NNATIVE_ASSERT(iMatchResultsSize - ioPosition >= static_cast<int>(iParams.size())); for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i) { const std::string value = iMatchResults[ioPosition++].as_string(); const std::string &name = iParams[i]; const std::string &formatName = iFormatNames[i]; UriTemplateValue &childValue = ioParsedValues.addChild(name, value); const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName); if(format.isRegExOnly()) { continue; } // Parse subvalues of format name const UriTemplate &uriTemplate = format.getTemplate(); NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\""); saveValues(childValue, ioPosition, iMatchResults, iMatchResultsSize, uriTemplate.getParams(), uriTemplate.getFormatNames()); } } bool extractAndSaveValues(UriTemplateValue &oValues, const std::string &iUri, const std::string &iExtractPattern, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames, const bool iAnchorEnd = true) { const re2::RE2 rePattern(iExtractPattern); const int matchResultsSize = 1+rePattern.NumberOfCapturingGroups(); std::unique_ptr<re2::StringPiece[]> matchResults(new re2::StringPiece[matchResultsSize]); re2::StringPiece uriPiece(iUri); if(!rePattern.Match(uriPiece, 0, uriPiece.size(), (iAnchorEnd ? re2::RE2::ANCHOR_BOTH : re2::RE2::ANCHOR_START), matchResults.get(), matchResultsSize)) { NNATIVE_DEBUG("No match found"); return false; } int position = 0; // No name to the first parsed value oValues.clear(); oValues.getString() = matchResults[position++].as_string(); // save child values saveValues(oValues, position, matchResults.get(), matchResultsSize, iParams, iFormatNames); return true; } bool containCapturingGroup(const std::string &iPattern) { // regex is compiled only at the first call static const re2::RE2 reCapturingGroup("\\([^?\\)]+\\)"); // true for "(test|other)", but false for non capturing groups (?:test|other) re2::StringPiece strPiece(iPattern); return reCapturingGroup.Match(strPiece, 0, strPiece.size(), re2::RE2::UNANCHORED, nullptr, 0); } #elif NNATIVE_USE_STDREGEX == 1 #include <regex> bool getNextParameter(std::string::const_iterator& iBegin, std::string::const_iterator iEnd, std::string& iText, std::string& Name, std::string& iFormat) { // regex is compiled only at the first call static const std::regex reParam("\\{([a-zA-Z][a-zA-Z0-9]*):([a-zA-Z][a-zA-Z0-9]*)\\}"); //e.g.: {param:formatName} std::smatch results; if(!std::regex_search(iBegin, iEnd, results, reParam)) { return false; } iText.assign(iBegin, iBegin + results.position()); Name = results.str(1); iFormat = results.str(2); iBegin += results.position() + results.length(); return true; } /** * Recursive save extracted data by regex into values * @param ioParsedValues parsed values container to be populated * @param ioPosition current smatch position * @iParams parameters name vector to be added as key values * @iFormatNames format name vector to parse child values, if exists */ void saveValues( UriTemplateValue &ioParsedValues, int &ioPosition, const std::smatch &iMatchResults, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames) { NNATIVE_ASSERT(iParams.size() == iFormatNames.size()); NNATIVE_ASSERT(iMatchResults.size() - ioPosition >= iParams.size()); for(std::vector<std::string>::size_type i = 0; i < iParams.size(); ++i) { const std::string value = iMatchResults.str(ioPosition++); const std::string &name = iParams[i]; const std::string &formatName = iFormatNames[i]; UriTemplateValue &childValue = ioParsedValues.addChild(name, value); const UriTemplateFormat &format = UriTemplateFormat::GetGlobalFormat(formatName); if(format.isRegExOnly()) { continue; } // Parse subvalues of format name const UriTemplate &uriTemplate = format.getTemplate(); NNATIVE_DEBUG("Extract child values from \"" << value << "\" with key \"" << name << "\" by using format name \"" << formatName << "\" with pattern \"" << uriTemplate.getPattern(true) << "\""); saveValues(childValue, ioPosition, iMatchResults, uriTemplate.getParams(), uriTemplate.getFormatNames()); } } bool extractAndSaveValues(UriTemplateValue &oValues, const std::string &iUri, const std::string &iExtractPattern, const std::vector<std::string> &iParams, const std::vector<std::string> &iFormatNames, const bool iAnchorEnd = true) { std::smatch matchResults; const std::regex rePattern(iExtractPattern); if(iAnchorEnd) { if(!std::regex_match(iUri, matchResults, rePattern)) { NNATIVE_DEBUG("No match found"); return false; } } else { if(!std::regex_search(iUri, matchResults, rePattern, std::regex_constants::match_continuous)) { NNATIVE_DEBUG("No match found"); return false; } } int position = 0; // No name to the first parsed value oValues.clear(); oValues.getString() = matchResults.str(position++); // save child values saveValues(oValues, position, matchResults, iParams, iFormatNames); return true; } bool containCapturingGroup(const std::string &iPattern) { // regex is compiled only at the first call static const std::regex reCapturingGroup("\\([^?\\)]+\\)"); // true for "(test|other)", but false for non capturing groups (?:test|other) std::smatch dummyResults; return std::regex_search(iPattern, dummyResults, reCapturingGroup); } #endif // elif NNATIVE_USE_STDREGEX == 1 } /* namespace */ UriTemplate::UriTemplate(const std::string &iTemplate) : _template(iTemplate) { parse(); } UriTemplate::UriTemplate(const UriTemplate &iBaseUriTemplate, const std::string &iTemplateSuffix) : _template(iBaseUriTemplate.getTemplate() + iTemplateSuffix) { parse(); } UriTemplate::UriTemplate(const UriTemplate &iOther) : _template(iOther._template), _matchPattern(iOther._matchPattern), _extractPattern(iOther._extractPattern), _params(iOther._params), _formatNames(iOther._formatNames) { // Avoid parsing because template string is already parsed } void UriTemplate::parse() { NNATIVE_DEBUG("New URI Template \"" << _template << "\""); // should not contain capturing groups. e.g. "/path/(caputeText)/{param1:format1}" NNATIVE_ASSERT_MSG(!ContainCapturingGroup(_template), "URI template \"" << _template << "\" contain capturing groups"); _matchPattern = ""; _extractPattern = ""; std::set<std::string> uniqParams; _params.clear(); _formatNames.clear(); // extract format names std::string::const_iterator begin = _template.begin(); std::string::const_iterator end = _template.end(); std::string textStr; std::string paramName; std::string formatName; while (getNextParameter(begin, end, textStr, paramName, formatName)) { NNATIVE_DEBUG("paramName:"<<paramName<<", formatName:"<<formatName); const UriTemplateFormat& globalFormat = UriTemplateFormat::GetGlobalFormat(formatName); // Check if parameter name duplicate. e.g: "/path{sameParamName:anyFormatName}/other/{sameParamName:anyFormatName}" if(!uniqParams.insert(paramName).second) { NNATIVE_DEBUG("Duplicate parameter name found " << paramName); NNATIVE_ASSERT(0); } _params.push_back(paramName); _formatNames.push_back(formatName); _matchPattern += textStr + globalFormat.getPattern(); _extractPattern += textStr + globalFormat.getPattern(true); } // add the remaing string std::string textRemained(begin, end); _matchPattern += textRemained; // extract pattern may be part of a format name, do net add end of string ("$") _extractPattern += textRemained; NNATIVE_DEBUG("Pattern for match: \"" << _matchPattern << "\""); NNATIVE_DEBUG("Pattern for extraction: \"" << _extractPattern << "\""); } bool UriTemplate::extract(UriTemplateValue &oValues, const std::string &iUri, const bool iAnchorEnd) const { NNATIVE_DEBUG("Extract values from \"" << iUri << "\" by using URI template \"" << _template << "\", pattern: \"" << _extractPattern << "\")"); return extractAndSaveValues(oValues, iUri, _extractPattern, getParams(), getFormatNames(), iAnchorEnd); } bool UriTemplate::ContainCapturingGroup(const std::string &iPattern) { return ::containCapturingGroup(iPattern); } <|endoftext|>