hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9b2f117d28bcd33f3d11a51e57db4bac970dd701
165
cpp
C++
src/logging/Console_logger.cpp
Swassie/dcmed
eb0225d991715b10bace2b96103c3fd98fe83c29
[ "BSD-3-Clause" ]
null
null
null
src/logging/Console_logger.cpp
Swassie/dcmed
eb0225d991715b10bace2b96103c3fd98fe83c29
[ "BSD-3-Clause" ]
null
null
null
src/logging/Console_logger.cpp
Swassie/dcmed
eb0225d991715b10bace2b96103c3fd98fe83c29
[ "BSD-3-Clause" ]
1
2021-05-10T08:54:39.000Z
2021-05-10T08:54:39.000Z
#include "logging/Console_logger.h" #include <iostream> void Console_logger::log(const std::string& message, Log_level) { std::cout << message << std::endl; }
20.625
65
0.70303
Swassie
9b374ba0a6c686002f0eca1a0c1dd5cb114772d1
7,415
hpp
C++
inc/UI/Flyout.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
inc/UI/Flyout.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
inc/UI/Flyout.hpp
barne856/3DSWMM
60dd2702c82857dcf4358b8d42a1fb430a568e90
[ "MIT" ]
null
null
null
#ifndef FLYOUT #define FLYOUT #include "Application/Application.hpp" #include "Meshes/Rectangle.hpp" #include "Meshes/Circle.hpp" #include "Materials/Flat.hpp" #include "Materials/VertexColor.hpp" #include "Application/Renderer.hpp" #include "Application/Tool.hpp" #include <iostream> class Flyout : public UIElement { public: Flyout() { flyout_base = new Rectangle(); flyout_shadow = new Rectangle({-0.5f, -0.5f}, {0.5f, 0.5f}, {0.0f, 0.0f, 0.0f, 1.0}, flyout_color_light); resize_bar = new Rectangle(); flat_material = new Flat(); vertex_color_material = new VertexColor(); } ~Flyout() { delete flyout_base; delete flyout_shadow; delete resize_bar; delete flat_material; delete vertex_color_material; } virtual void on_key(int key, int action) { } virtual void on_mouse_button(int button, int action) { if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { input.mouse_button[0] = true; } if (action == GLFW_RELEASE) { input.mouse_button[0] = false; } } if (selected_widget) { selected_widget->on_mouse_button(button, action); } } virtual void on_mouse_move(int x, int y) { // transfer focus to widget for (auto widget : (*widgets_ptr).widgets) { if (widget->is_focused(x, y)) { if (widget != selected_widget) { if (selected_widget) { selected_widget->reset_state(); } selected_widget = widget; } return widget->on_mouse_move(x, y); } else { widget->reset_state(); } selected_widget = nullptr; } } virtual void on_mouse_wheel(int pos) { // scroll widgets widgets_ptr->widget_scroll_pos += float(pos); // no scrolling past the top and no scrolling if window can fit everything if (widgets_ptr->widget_scroll_pos > 0.0f || 64 * UI_scale() * widgets_ptr->row_count < UI_height()) { widgets_ptr->widget_scroll_pos = 0.0f; } // no scrolling past the bottom else if (64 * UI_scale() * (widgets_ptr->row_count + widgets_ptr->widget_scroll_pos) < UI_height()) { widgets_ptr->widget_scroll_pos = floor(UI_height() / (UI_scale() * 64.0f)) - widgets_ptr->row_count; } } virtual void on_resize(int width, int height) { // Adjust widget_scroll_pos on window resize // if visible widgets height is less than ui height, set scroll pos so bottom widget is on last row if (64 * UI_scale() * (widgets_ptr->row_count + widgets_ptr->widget_scroll_pos) < UI_height()) { widgets_ptr->widget_scroll_pos = floor(UI_height() / (UI_scale() * 64.0f)) - widgets_ptr->row_count; } if(widgets_ptr->widget_scroll_pos > 0.0f)// set scroll pos so top widget is on first row { widgets_ptr->widget_scroll_pos = 0.0f; } } virtual void render() { Renderer::BEGIN(UI_camera()); flat_material->set_color(flyout_color_light); Renderer::submit(flyout_base, flat_material); Renderer::submit(flyout_shadow, vertex_color_material); flat_material->set_color(flyout_color_dark); Renderer::submit(resize_bar, flat_material); // Render widgets for (auto &name : (*widgets_ptr).names) { if (name) { Renderer::submit(name, flat_material); } } if (widgets_ptr) { for (auto widget : (*widgets_ptr).widgets) { widget->render(); } } // no END() because this will be called inside END() } void rescale(float x_pos, float flyout_full_width) { if (flyout_full_width != 0.0f) { flyout_width = flyout_full_width; } this->x_pos = x_pos; set_bottom_left(glm::vec2(x_pos, 0.0f)); set_top_right(glm::vec2(x_pos + get_width(), UI_height())); flyout_base->set_position(glm::vec3(x_pos + 0.5f * (get_width() - resize_bar_width * UI_scale()), 0.5f * UI_height(), -1.0f)); flyout_base->set_scale(glm::vec3((get_width() - resize_bar_width * UI_scale()), UI_height(), 0.0f)); flyout_shadow->set_position(glm::vec3(x_pos + 0.5f * UI_scale() * resize_bar_width, 0.5f * UI_height(), 0.0f)); flyout_shadow->set_scale(glm::vec3(resize_bar_width * UI_scale(), UI_height(), 0.0f)); if (get_width() < resize_bar_width * UI_scale()) { flyout_shadow->set_scale(glm::vec3(0.0f, UI_height(), 0.0f)); } resize_bar->set_position(glm::vec3(x_pos + get_width() - 0.5f * UI_scale() * resize_bar_width, 0.5f * UI_height(), 0.0f)); resize_bar->set_scale(glm::vec3(UI_scale() * resize_bar_width, UI_height(), 0.0f)); // rescale widgets if (widgets_ptr) { float widget_height = 64 * UI_scale(); int i = 0; widgets_ptr->update_scroll_pos(widget_scroll_speed); float row = widgets_ptr->current_widget_scroll_pos; for (auto widget : widgets_ptr->widgets) { if (widgets_ptr->names[i]) { (*widgets_ptr).names[i]->set_scale({label_scale, 2.0f * label_scale, 0.0f}); (*widgets_ptr).names[i]->set_center({x_pos + get_width() - resize_bar_width * UI_scale() - flyout_width / 2.0f, UI_height() - widget_height * (row + 0.25f), 0.0f}); row += 0.5f; } widget->set_bottom_left(glm::vec2(x_pos + get_width() - resize_bar_width * UI_scale() - flyout_width, UI_height() - widget_height * (row + (*widgets_ptr).widget_rows[i]))); widget->set_top_right(glm::vec2(x_pos + get_width() - resize_bar_width * UI_scale(), UI_height() - widget_height * row)); row += (*widgets_ptr).widget_rows[i]; i++; } } } void set_widgets(WidgetArray *widgets) { widgets_ptr = widgets; widgets_ptr->reset_state(); } void reset_state() { input.world_pos = glm::vec3(0.0f); input.mouse_button[0] = false; } private: // Flyout Rectangle *flyout_base; Rectangle *flyout_shadow; Rectangle *resize_bar; float flyout_width = 128.0f; int resize_bar_width = 8; // pixels float x_pos = 0.0f; float shadow_size = 50.0f; WidgetArray *widgets_ptr = nullptr; // pointer to vector of UIElement pointers which are implimented in each tool with a flyout UIElement *selected_widget = nullptr; float label_scale = 16.0f * UI_scale(); float widget_scroll_speed = 0.25f; // Colors Flat *flat_material; VertexColor *vertex_color_material; glm::vec4 flyout_color_light = glm::vec4(223 / 255.0, 230 / 255.0, 233 / 255.0, 1.0f); glm::vec4 flyout_color_dark = glm::vec4(45 / 255.0, 52 / 255.0, 54 / 255.0, 1.0f); }; #endif
34.649533
188
0.5706
barne856
9b386d1553801bd7f598e20bdd04f360c7ec083b
571
hh
C++
src/http/http_server_connection.hh
sharixos/libevent-cpp
01b62cdb61a189afc7a31c8c9f8a90e350ab18b7
[ "MIT" ]
35
2019-04-02T01:48:49.000Z
2022-03-21T08:36:22.000Z
src/http/http_server_connection.hh
sharixos/libevent-cpp
01b62cdb61a189afc7a31c8c9f8a90e350ab18b7
[ "MIT" ]
1
2019-04-01T12:13:01.000Z
2019-04-26T07:33:00.000Z
src/http/http_server_connection.hh
sharixos/libevent-cpp
01b62cdb61a189afc7a31c8c9f8a90e350ab18b7
[ "MIT" ]
6
2019-04-01T23:10:20.000Z
2021-03-04T09:13:56.000Z
#pragma once #include <http_connection.hh> namespace eve { class http_server; class http_server_connection : public http_connection { public: http_server *server; std::string clientaddress; unsigned int clientport; public: http_server_connection(std::shared_ptr<event_base> base, int fd, http_server* server); ~http_server_connection() {} void fail(http_connection_error error); void do_read_done(); void do_write_done(); int associate_new_request(); void handle_request(http_request * req); }; } // namespace eve
19.033333
89
0.71979
sharixos
9b45cb6f733041a6d3da26ca330801f5d3b922a6
11,229
cpp
C++
examples/Rasterizer/Rasterizer.cpp
madanwork/pxcore-local
c08e9b7a8b675bab71f6c0771c03f8e416cc9545
[ "Apache-2.0" ]
null
null
null
examples/Rasterizer/Rasterizer.cpp
madanwork/pxcore-local
c08e9b7a8b675bab71f6c0771c03f8e416cc9545
[ "Apache-2.0" ]
null
null
null
examples/Rasterizer/Rasterizer.cpp
madanwork/pxcore-local
c08e9b7a8b675bab71f6c0771c03f8e416cc9545
[ "Apache-2.0" ]
null
null
null
#include "pxCore.h" #include "pxEventLoop.h" #include "pxWindow.h" #include "pxKeycodes.h" #include "pxOffscreen.h" #include "pxTimer.h" #include "rtData.h" #include "xs_StringUtil.h" #include "stdio.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifndef PX_PLATFORM_WIN #include <unistd.h> #else #include <io.h> #define open _open #define close _close #define read _read #define fstat _fstat #define stat _stat #endif #define JOHNS #ifdef JOHNS #include "pxCanvas.h" #endif //#endif pxEventLoop eventLoop; void mandel(pxBuffer& b, long double xmin, long double xmax, long double ymin, long double ymax, unsigned maxiter ) { int nx = b.width(); int ny = b.height(); short ix, iy; unsigned iter; long double cx, cy; long double x, y, x2, y2, temp; for( iy = 0; iy < ny; iy ++ ) { cy = ymin + iy * ( ymax - ymin ) / ( ny - 1 ); for( ix = 0; ix < nx; ix ++ ) { cx = xmin + ix * ( xmax - xmin ) / ( nx - 1 ); x = y = x2 = y2 = 0.0; iter = 0; while( iter < maxiter && ( x2 + y2 ) <= 9.0 /* 10000.0 ??? */ ) { temp = x2 - y2 + cx; y = 2 * x * y + cy; x = temp; x2 = x * x; y2 = y * y; iter++; } double v; if (iter >= maxiter) v = 1.0; else v = (double)iter/(double)maxiter; pxPixel* p = b.pixel(ix, iy); if (v >= 1.0) { p->r = p->b = p->g = 0; p->a = 32; } else { p->r = (uint8_t)(255*v); p->b = (uint8_t)(80*(1.0-v)); p->g = (uint8_t)(255*(1.0-v)); p->a = 255; } } } } void drawBackground(pxBuffer& b) { int w = b.width(); int h = b.height(); for (int y = 0; y < h; y++) { pxPixel* p = b.scanline(y); for (int x = 0; x < w; x++) { p->r = pxClamp<int>(x + y, 0, 255); p->g = pxClamp<int>(y, 0, 255); p->b = pxClamp<int>(x, 0, 255); p++; } } } bool rtLoadFileUnix(const char* file, rtData& data) { bool e = false; struct stat st; int f = open(file, O_RDONLY); if (f != -1) { fstat(f, &st); unsigned long sizeToUse = st.st_size; // space for null terminstor data.initWithLength(sizeToUse+1); if (data.bytes()) { unsigned long bytesRead = read(f, data.bytes(), sizeToUse); unsigned char* bytes = (unsigned char*)data.bytes(); bytes[bytesRead] = 0; // NULL terminate it for convenience e = true; } close(f); } return e; } class myWindow: public pxWindow { public: myWindow(): mShapeIndex(6) { gQuality = 1; gTextureRotate = 0; gAnimating = false; gRotateDelta = 1 * 3.1415 / 180; // Init Texture textureOffscreen.init(128,96); mandel(textureOffscreen, -2, 1, -1.5, 1.5, 16); // Init Offscreen offscreen.init(800, 800); #ifdef JOHNS canvasPtr = new pxCanvas; pxCanvas& canvas = *canvasPtr; canvas.initWithBuffer(&offscreen); canvas.setAlpha(1.0); canvas.setAlphaTexture(true); canvas.setTexture(&textureOffscreen); #endif loadShape(); } ~myWindow() { #ifdef JOHNS delete canvasPtr; #endif } void loadShape() { if (mShapeIndex >= 1 && mShapeIndex <= 4) { readFile(mShapeIndex); } else if (mShapeIndex == 5) { testLargeFill(); } #if 0 else { testText(); } #endif } void drawFrame() { // Draw the current shape drawBackground(offscreen); #ifdef JOHNS pxMatrix m; m.identity(); m.rotate(gTextureRotate); canvasPtr->setTextureMatrix(m); if (mShapeIndex != 6) canvasPtr->fill(); else { #if 1 // canvasPtr->setFont(L"Arial"); // canvasPtr->setFontSize(10); // canvasPtr->drawText(L"Hello john", 100, 100); #else pxBuffer* b = canvasPtr->texture(); canvasPtr->setTexture(NULL); //canvasPtr->setYOversample(4); canvasPtr->setFillColor(0, 255, 0); #if 0 canvasPtr->moveTo(1, 1); canvasPtr->lineTo(2, 1); canvasPtr->lineTo(2, 2.68); canvasPtr->lineTo(1, 2.68); canvasPtr->lineTo(1,1); #endif for (int i = 0; i <= 10; i++) { canvasPtr->newPath(); double d = (double)2 + ((double)i * 0.1); canvasPtr->rectangle(2+ (i*1)+ 1, 1, 2 + (i*1) + 2, d); // canvasPtr->rectangle(2+ (i*1)+ 1, 1, 2 + (i*1) + 2, 2.3); // printf("bottom: %f\n", d); canvasPtr->closePath(); canvasPtr->fill(); } for (int i = 0; i <= 10; i++) { canvasPtr->newPath(); double d = (double)6 + ((double)i * 0.1); canvasPtr->rectangle(2+ (i*1)+ 1, d, 2 + (i*1) + 2, 8); // printf("bottom: %f\n", d); canvasPtr->closePath(); canvasPtr->fill(); } canvasPtr->setStrokeColor(255, 0, 0); canvasPtr->setStrokeWidth(1); //canvasPtr->stroke(); canvasPtr->setTexture(b); #endif } #endif invalidateRect(); } void onCreate() { drawFrame(); } void onAnimationTimer() { gTextureRotate += gRotateDelta; drawFrame(); } void onSize(int32_t w, int32_t h) { offscreen.init(w, h); drawFrame(); } void onKeyDown(uint32_t keyCode, uint32_t flags) { // printf("onKeyDown\n"); switch(keyCode) { case PX_KEY_LEFT: { // Rotate Texture #ifdef JOHNS pxMatrix m; m.identity(); m.rotate(gTextureRotate+=gRotateDelta); canvasPtr->setTextureMatrix(m); canvasPtr->clear(); #endif } break; case PX_KEY_RIGHT: { // Rotate Texture #ifdef JOHNS pxMatrix m; m.identity(); m.rotate(gTextureRotate-=gRotateDelta); canvasPtr->setTextureMatrix(m); canvasPtr->clear(); #endif } break; case PX_KEY_UP: // Increase Quality gQuality++; if (gQuality > 4) gQuality = 4; #ifdef JOHNS canvasPtr->setYOversample(1<<gQuality); printf("Oversample => %d\n", 1 << gQuality); #endif break; case PX_KEY_DOWN: // Decrease Quality gQuality--; if (gQuality < 0) gQuality = 0; #ifdef JOHNS canvasPtr->setYOversample(1<<gQuality); printf("Oversample => %d\n", 1 << gQuality); #endif break; case PX_KEY_ONE: case PX_KEY_TWO: { // printf("cycle\n"); // Cycle throught Shapes mShapeIndex = (keyCode == PX_KEY_ONE)?mShapeIndex-1: mShapeIndex+1; if (mShapeIndex < 1) mShapeIndex = 6; if (mShapeIndex > 6) mShapeIndex = 1; loadShape(); drawFrame(); } break; case PX_KEY_A: // Toggle Texture Animation gAnimating = !gAnimating; setAnimationFPS(gAnimating?70:0); break; case PX_KEY_T: { // Toogle Filtering #ifdef JOHNS if (!canvasPtr->texture()) { canvasPtr->setTexture(&textureOffscreen); } else canvasPtr->setTexture(NULL); #endif } break; case PX_KEY_F: { // Time Filling Shape //double start = pxMilliseconds(); // drawFrame #ifdef JOHNS canvasPtr->fill(true); #endif // double end = pxMilliseconds(); // printf("Elapsed Time %gms FPS: %g\n", end-start, 1000/(end-start)); } break; case PX_KEY_C: // Toggle Texture Clamp #ifdef JOHNS canvasPtr->setTextureClamp(!canvasPtr->textureClamp()); #endif break; case PX_KEY_B: // Toggle Bilerp #ifdef JOHNS canvasPtr->setBiLerp(!canvasPtr->biLerp()); #endif break; case PX_KEY_M: // Toggle Alpha Texture #ifdef JOHNS canvasPtr->setAlphaTexture(!canvasPtr->alphaTexture()); #endif break; default: break; } drawFrame(); } void onCloseRequest() { eventLoop.exit(); } void onDraw(pxSurfaceNative s) { offscreen.blit(s); } void testLargeFill() { // Draw a filled 640x480 #ifdef JOHNS pxCanvas& canvas = *canvasPtr; canvas.newPath(); canvas.moveTo(0, 0); canvas.lineTo(640, 0); canvas.lineTo(640, 480); canvas.lineTo(0, 480); canvas.lineTo(0, 0); canvas.fill(); #endif } void testText() { // Draw a filled 640x480 #ifdef JOHNS pxCanvas& canvas = *canvasPtr; // canvas.drawText(L"Hello John", 100, 100); #endif } void readFile(int test) { #ifdef JOHNS pxCanvas& canvas = *canvasPtr; #endif uint32_t len = 0; char *f; int pathNum = 0; rtData d; { { #if defined(PX_PLATFORM_WIN) if (rtLoadFileUnix("c:\\_data\\complex.data", d)) #elif defined(PX_PLATFORM_MAC) if (rtLoadFileUnix("/Users/Shared/complex.data", d)) #elif defined(PX_PLATFORM_X11) if (rtLoadFileUnix("./complex.data", d)) #endif { f = (char*)d.bytes(); len = d.length(); // char *of = f; char *ef = f + len; if (f) { while (f && f<ef && *f) { pathNum++; if (pathNum == test) { #ifdef JOHNS canvas.newPath(); #endif } bool first = true; while (f && *f!=0 && *f!='\r' && *f!='\n') { real64 x, y; char str1[256], str2[256]; f = xs_NextToken(f, str1, 256, ','); if (f&&f[0]==',') f++; f = xs_NextToken(f, str2, 256, ','); if (f&&f[0]==',') f++; xs_atod(str1, &x, 256); xs_atod(str2, &y, 256); if (pathNum == test) { if (first) { #ifdef JOHNS canvas.moveTo(x,y); #endif first = false; } else { #ifdef JOHNS canvas.lineTo(x,y); #endif } } } if (f) while (f && *f && (*f=='\r' || *f=='\n')) f++; } } } } } } private: int mShapeIndex; int gQuality; double gTextureRotate; bool gAnimating; double gRotateDelta; pxOffscreen textureOffscreen; pxOffscreen offscreen; #ifdef JOHNS pxCanvas* canvasPtr; #endif }; void usage() { printf("Keys\n"); printf("----\n"); printf("1 - Previous Shape\n"); printf("2 - Next Shape\n"); printf("T - Toggle Texture Map\n"); printf("M - Toggle Alpha Texture\n"); printf("C - Toggle Texture Clamp\n"); printf("B - Toggle BiLerp\n"); printf("A - Toggle Animation\n"); printf("F - Time Fill\n"); printf("Up - Increase Oversampling\n"); printf("Dn - Decrease Oversampling\n"); printf("\n"); } int pxMain(int, char **) { usage(); myWindow win; win.init(10, 64, 800, 600); win.setTitle("Rasterizer"); win.setVisibility(true); eventLoop.run(); return 0; }
20.159785
76
0.512779
madanwork
9b47b994dff24857a78571043882d5982f1195ae
2,665
cpp
C++
src/engine/graphics/BufferObject.cpp
PepeSegade/LittleEngine
0d8bcc1f783cfb3b8e8a1ad2456e470900ccdd1a
[ "WTFPL" ]
null
null
null
src/engine/graphics/BufferObject.cpp
PepeSegade/LittleEngine
0d8bcc1f783cfb3b8e8a1ad2456e470900ccdd1a
[ "WTFPL" ]
null
null
null
src/engine/graphics/BufferObject.cpp
PepeSegade/LittleEngine
0d8bcc1f783cfb3b8e8a1ad2456e470900ccdd1a
[ "WTFPL" ]
null
null
null
#include "BufferObject.h" unsigned int LittleEngine::BufferObject::calculateDataSize() { switch (dataType) { case GL_FLOAT: case GL_INT: case GL_UNSIGNED_INT: return 4; case GL_SHORT: case GL_UNSIGNED_SHORT: return 2; case GL_BYTE: case GL_UNSIGNED_BYTE: return 1; default: break; } return 0; } LittleEngine::BufferObject::BufferObject(GLenum dataType, GLenum bufferType) : dataType(dataType), bufferType(bufferType), id(0), size(0) { } LittleEngine::BufferObject::~BufferObject() { glDeleteBuffers(1, &id); } LittleEngine::BufferObject* LittleEngine::BufferObject::bind() { glBindBuffer(bufferType, id); return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::bindAsVertexArray() { glBindVertexArray(id); return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::unbind() { glBindBuffer(bufferType, 0); return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::render(RenderMode renderMode) { switch (renderMode) { case RenderMode::TRIANGLES: { glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, (void*)0); break; } case RenderMode::QUADS: { glPatchParameteri(GL_PATCH_VERTICES, 4); glDrawElements(GL_PATCHES, size, GL_UNSIGNED_INT, (void*)0); break; } case RenderMode::TRIANGLES_PATCH: { glPatchParameteri(GL_PATCH_VERTICES, 3); glDrawElements(GL_PATCHES, size, GL_UNSIGNED_INT, (void*)0); break; } case RenderMode::POINTS: { glDrawArrays(GL_POINTS, 0, size); break; } default: // This should never happen break; } return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::addDataToShader(const void* data, int size) { return addDataToShaderSpecifyDataSize(data, size, calculateDataSize()); } LittleEngine::BufferObject* LittleEngine::BufferObject::addDataToShaderSpecifyDataSize(const void* data, int size, int dataSize) { this->size = size; glGenBuffers(1, &id); glBindBuffer(bufferType, id); unsigned int sizeTimesData = size * dataSize; glBufferData(bufferType, sizeTimesData, data, GL_STATIC_DRAW); return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::bindBufferBase(int bufferLocation) { glBindBufferBase(bufferType, bufferLocation, id); return this; } LittleEngine::BufferObject* LittleEngine::BufferObject::compute(int blocksCount) { glDispatchCompute(blocksCount, 1, 1); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); return this; } void* LittleEngine::BufferObject::mapBufferOnObject(int size) { return glMapBufferRange(bufferType, 0, size, GL_MAP_WRITE_BIT); } LittleEngine::BufferObject* LittleEngine::BufferObject::unmapBuffer() { glUnmapBuffer(bufferType); return this; }
21.150794
128
0.762477
PepeSegade
9b49fbaff57cff6ac1206644743e89b0d2aa8236
3,003
cpp
C++
netc/PollPoller.cpp
Sun-CX/reactor
88d90a96ae8c018c902846437ef6068da2715aa2
[ "Apache-2.0" ]
3
2020-08-11T06:47:16.000Z
2021-07-16T09:51:28.000Z
netc/PollPoller.cpp
Sun-CX/reactor
88d90a96ae8c018c902846437ef6068da2715aa2
[ "Apache-2.0" ]
null
null
null
netc/PollPoller.cpp
Sun-CX/reactor
88d90a96ae8c018c902846437ef6068da2715aa2
[ "Apache-2.0" ]
2
2020-08-10T07:38:29.000Z
2021-07-16T09:48:09.000Z
// // Created by suncx on 2020/8/21. // #include "PollPoller.h" #include "Ext.h" #include "Channel.h" #include "ConsoleStream.h" #include <cstring> #include <poll.h> #include <cassert> using std::iter_swap; using reactor::core::Timestamp; using reactor::net::PollPoller; using std::chrono::system_clock; PollPoller::PollPoller(EventLoop *loop) : Poller(loop) {} Timestamp PollPoller::poll(Channels &active_channels, int milliseconds) { int ready_events = ::poll(fds.data(), fds.size(), milliseconds); Timestamp ts = system_clock::now(); if (unlikely(ready_events < 0)) { // error if (ready_events != EINTR) RC_FATAL << "poll wait error: " << ::strerror(errno); } else if (ready_events == 0) { // timeout RC_WARN << "poll wait timeout, nothing happened"; } else { fill_active_channels(active_channels, ready_events); } return ts; } void PollPoller::fill_active_channels(Poller::Channels &active_channels, int ready_events) const { for (auto it = fds.cbegin(); it != fds.cend() and ready_events > 0; ++it) { if (it->revents > 0) { auto v = channel_map.find(it->fd); auto channel = v->second; channel->set_revents(it->revents); active_channels.push_back(channel); ready_events--; } } } void PollPoller::update_channel(Channel *channel) { #ifndef NDEBUG Poller::assert_in_loop_thread(); #endif int index = channel->get_index(); if (index < 0) { // a new channel assert(channel_map.find(channel->get_fd()) == channel_map.cend()); pollfd pfd; pfd.fd = channel->get_fd(); pfd.events = channel->get_events(); pfd.revents = 0; fds.push_back(pfd); channel->set_index(static_cast<int>(fds.size() - 1)); channel_map[channel->get_fd()] = channel; } else { // an existed channel assert(channel_map.find(channel->get_fd()) != channel_map.cend()); assert(channel_map[channel->get_fd()] == channel); assert(0 <= index and index < fds.size()); pollfd &pfd = fds[index]; assert(pfd.fd == channel->get_fd()); pfd.events = channel->get_events(); pfd.revents = 0; } } void PollPoller::remove_channel(Channel *channel) { #ifndef NDEBUG Poller::assert_in_loop_thread(); #endif int index = channel->get_index(); assert(channel_map.find(channel->get_fd()) != channel_map.cend()); assert(channel_map[channel->get_fd()] == channel); assert(0 <= index and index < fds.size()); pollfd &pfd = fds[index]; if (index == fds.size() - 1) // last one fds.pop_back(); else { // swap this channel with the last channel. int last_channel_fd = fds.back().fd; iter_swap(fds.begin() + index, fds.end() - 1); fds.pop_back(); channel_map[last_channel_fd]->set_index(index); } auto n = channel_map.erase(channel->get_fd()); assert(n == 1); }
27.550459
98
0.615052
Sun-CX
9b4c0a6cf34a07115250dcdcec2415639afb80b2
555
cpp
C++
arrays/2D arrays/02_searching_an_element_.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
1
2022-02-23T17:27:42.000Z
2022-02-23T17:27:42.000Z
arrays/2D arrays/02_searching_an_element_.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
null
null
null
arrays/2D arrays/02_searching_an_element_.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int n, m, k; cin >> n >> m >> k; int num[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> num[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (num[i][j] == k) { cout << "element found" << endl; cout << "row no." << i << " column no." << j; } } cout << endl; } return 0; }
18.5
62
0.311712
omkarugale7
9b4f56e5127349a2b8fc87334443e313f948393f
2,611
cpp
C++
VNVita/Program.cpp
QuantumBoogaloo/VNVitaPrototype
bf06d08e41da9874dd51cee967bfe2b5c27567d5
[ "Apache-2.0" ]
null
null
null
VNVita/Program.cpp
QuantumBoogaloo/VNVitaPrototype
bf06d08e41da9874dd51cee967bfe2b5c27567d5
[ "Apache-2.0" ]
4
2018-03-22T13:34:22.000Z
2018-03-22T13:55:56.000Z
VNVita/Program.cpp
QuantumBoogaloo/VNVitaPrototype
bf06d08e41da9874dd51cee967bfe2b5c27567d5
[ "Apache-2.0" ]
null
null
null
#include "Program.h" /* Copyright (C) 2018 Quantum Boogaloo, Bakagamedev(@bakagamedev), Pharap (@Pharap) 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 <stdexcept> VNVita::Program::Program(void) { SDL_Window * windowPointer = SDL_CreateWindow("VN Vita", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 544, SDL_WindowFlags(0)); if (windowPointer == nullptr) { throw std::runtime_error(SDL_GetError()); } SDL_Renderer * rendererPointer = SDL_CreateRenderer(windowPointer, -1, SDL_RendererFlags::SDL_RENDERER_ACCELERATED); if (rendererPointer == nullptr) { throw std::runtime_error(SDL_GetError()); } this->window = SharedWindow(windowPointer, SDL_DestroyWindow); this->renderer = SharedRenderer(rendererPointer, SDL_DestroyRenderer); } VNVita::Program::SharedWindow VNVita::Program::getWindow(void) { return this->window; } VNVita::Program::SharedRenderer VNVita::Program::getRenderer(void) { return this->renderer; } VNVita::Program::SharedConstWindow VNVita::Program::getWindow(void) const { return std::static_pointer_cast<SDL_Window const>(this->window); } VNVita::Program::SharedConstRenderer VNVita::Program::getRenderer(void) const { return std::static_pointer_cast<SDL_Renderer const>(this->renderer); } bool VNVita::Program::isRunning(void) const { return this->running; } void VNVita::Program::run(void) { this->running = true; Uint32 frameStart = 0; float deltaTime = 0; while (this->running) { deltaTime = (SDL_GetTicks() - frameStart) / 1000.0f; frameStart = SDL_GetTicks(); this->handleInput(); this->update(); this->render(); } } void VNVita::Program::handleInput(void) { SDL_Event event; if (SDL_PollEvent(&event)) { if (event.type == SDL_EventType::SDL_QUIT) { this->running = false; } } } void VNVita::Program::update(void) { } void VNVita::Program::render(void) { SDL_SetRenderDrawColor(this->renderer.get(), 100, 149, 237, SDL_ALPHA_OPAQUE); SDL_RenderClear(this->renderer.get()); SDL_RenderPresent(this->renderer.get()); }
24.401869
137
0.716201
QuantumBoogaloo
9b53e0c2962bf9585e5583d9a71e0cbe89876c39
805
cpp
C++
SFML_RPG/Tile.cpp
krisgreg/LBEngine
391c6b2a2e543ea725884997c7bf3dc56572772a
[ "MIT" ]
null
null
null
SFML_RPG/Tile.cpp
krisgreg/LBEngine
391c6b2a2e543ea725884997c7bf3dc56572772a
[ "MIT" ]
null
null
null
SFML_RPG/Tile.cpp
krisgreg/LBEngine
391c6b2a2e543ea725884997c7bf3dc56572772a
[ "MIT" ]
null
null
null
#include "Tile.h" #include "Consts.h" lbe::Tile::Tile(sf::Vector2f WorldPos, sf::Texture *Texture, sf::Vector2f TexturePos, int TextureId) : TextureId(TextureId) { BackgroundSprite.setSize(sf::Vector2f(lbe::TILE_SIZE, lbe::TILE_SIZE)); BackgroundSprite.setTexture(Texture); BackgroundSprite.setTextureRect(sf::IntRect(TexturePos.x, TexturePos.y, lbe::TILE_TEXTURE_SIZE, lbe::TILE_TEXTURE_SIZE)); BackgroundSprite.setPosition(WorldPos); } lbe::Tile::~Tile() { } void lbe::Tile::Draw(sf::RenderWindow & window) { window.draw(BackgroundSprite); } sf::Vector2f lbe::Tile::GetWorldPos() { return BackgroundSprite.getPosition(); } int lbe::Tile::GetTextureId() { return TextureId; } bool lbe::Tile::bContainsPoint(sf::Vector2f Point) { return BackgroundSprite.getGlobalBounds().contains(Point); }
23
123
0.754037
krisgreg
9b5951bdfb9b2cfe06e5a321dfec953188bff92a
1,329
cpp
C++
Pathfinding/DijkstraWalker.cpp
Gerard097/Pathfinding
343ff9550dbd3f5d141a9ba3ccb2902002660dff
[ "MIT" ]
25
2019-01-05T14:16:55.000Z
2022-03-08T22:42:21.000Z
Pathfinding/DijkstraWalker.cpp
Gerard097/Pathfinding
343ff9550dbd3f5d141a9ba3ccb2902002660dff
[ "MIT" ]
1
2020-08-11T06:32:46.000Z
2020-08-11T17:09:40.000Z
Pathfinding/DijkstraWalker.cpp
Gerard097/Pathfinding
343ff9550dbd3f5d141a9ba3ccb2902002660dff
[ "MIT" ]
5
2018-04-14T19:01:35.000Z
2021-05-16T10:48:50.000Z
#include "DijkstraWalker.h" #include "Graph.h" CDijkstraWalker::CDijkstraWalker() { } CDijkstraWalker::~CDijkstraWalker() { } bool CDijkstraWalker::Step() { if ( m_pEnd && m_pCurrent && m_iCurrentSteps++ < m_iMaxSteps && !m_nodes.empty() ) { m_pCurrent = *m_nodes.begin(); m_nodes.erase( m_nodes.begin() ); if ( m_pCurrent != m_pEnd ) { m_pCurrent->SetVisited( true ); LoadConnections( m_pCurrent ); } else CreatePath( m_pCurrent ); } else { return true; } return false; } void CDijkstraWalker::LoadConnections( CGraphNode *pNode ) { auto connections = std::move( GetConnections( pNode ) ); for ( auto& node : connections ) { float fTentDist = pNode->GetTentativeDistance() + node->GetWeight(); float fNodeTent = node->GetTentativeDistance(); if ( !node->Visited() && !node->IsBlocked() && fTentDist < fNodeTent ) { auto it = m_nodes.find( node ); if ( it != m_nodes.end() ) { m_nodes.erase( it ); } node->SetTentativeDistance( fTentDist ); m_nodes.insert( node ); node->SetParent( pNode ); } } } void CDijkstraWalker::ClearNodes() { m_nodes.clear(); } /*******Clase Para Comprar pesos******/ bool CLessWeight::operator()( CGraphNode *lhs, CGraphNode *rhs ) const { return lhs->GetTentativeDistance() < rhs->GetTentativeDistance(); }
17.25974
70
0.65237
Gerard097
9b59ccb2e9504f811b740ad3e8602d0d6188a825
17,964
cpp
C++
MTUSpline/MTUSplineData.cpp
GuillaumeVDu/MTUSpline
13ce7b2e52b820312c29464cb5560bdca446b252
[ "BSD-3-Clause" ]
2
2019-07-25T18:09:42.000Z
2019-09-08T16:02:18.000Z
MTUSpline/MTUSplineData.cpp
GuillaumeVDu/MTUSpline
13ce7b2e52b820312c29464cb5560bdca446b252
[ "BSD-3-Clause" ]
null
null
null
MTUSpline/MTUSplineData.cpp
GuillaumeVDu/MTUSpline
13ce7b2e52b820312c29464cb5560bdca446b252
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015, Massimo Sartori, Monica Reggiani and Guillaume Durandau // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <sstream> using std::stringstream; #include <iostream> using std::cout; using std::endl; #define _USE_MATH_DEFINES #include <math.h> #include <stdlib.h> #include <fstream> using std::ifstream; using std::ofstream; #include <iomanip> #include "MTUSplineBase.h" #include "MTUSplineData.h" #define PRECISION 6 using namespace std; /** * Class for dimension exception. */ /*class DimException: public exception { virtual const char* what() const throw() { return "The dimension is bigger than 8 which is the maximum accepted."; } } dimException;*/ /** * Class for use exception. *//* class UseException: public exception { virtual const char* what() const throw() { return "Nothing to do here, something went wrong or does'nt have quality code."; } } useException2;*/ #ifdef LOG_WRITE vector<double> globalcoeff; vector<double> globalcoeffRead; #endif const int DIGIT_NUM = 8; const int NUMBER_DIGIT_OUTPUT = 8; inline double roundIt(double x, double n = DIGIT_NUM) { return floor(x * pow(10.0, n) + 0.5) / pow(10.0, n); } #ifndef MTU_h inline double radians(double d) { return d * M_PI / 180; } inline double degrees(double r) { return r * 180 / M_PI; } #endif MTUSplineData::~MTUSplineData() { // for (vector< MTUSplineBase* >::iterator it1 = splines_.begin(); it1 != splines_.end(); it1++) // delete *it1; } void MTUSplineData::computeSplineCoeff(const string& inputDataFilename) { #ifdef LOG cout << "Reading input data from: " << inputDataFilename << endl; #endif readInputData(inputDataFilename); #ifdef LOG cout << "Read the following interpolation data:\n"; displayInputData(); #endif // create the noMuscles_ splines for (int i = 0; i < noMuscles_; ++i) { std::shared_ptr<MTUSpline<N_DOF> > newSpline(new MTUSpline<N_DOF>(a_, b_, n_)); splines_.push_back(newSpline); } #ifdef LOG cout << "Created " << splines_.size() << " splines.\n"; #endif // now compute coefficients for each muscle for (int i = 0; i < noMuscles_; ++i) { vector<double> currentMuscle(y_[i]); splines_[i]->computeCoefficients(currentMuscle, currentMuscle.begin()); } } void MTUSplineData::computeSplineCoeff( const vector<vector<double> >& lmtVectorMat, const vector<double> a, vector<double> b, vector<int> n, vector<string> DOFNameVect, vector<string> muscleNameVect, int numOfDim) { a_ = a; b_ = b; n_ = n; noMuscles_ = muscleNameVect.size(); muscleNames_ = muscleNameVect; dofName_ = DOFNameVect; y_ = lmtVectorMat; computeSplineCoeff(numOfDim); } vector< std::shared_ptr<MTUSplineBase> > MTUSplineData::computeSplineCoeff(int numOfDim) { splines_.clear(); for (int i = 0; i < noMuscles_; ++i) { switch(numOfDim) { case 1: { std::shared_ptr<MTUSpline<1> > newSpline(new MTUSpline<1>(a_[0], b_[0], n_[0])); vector<double> currentMuscle(y_[i]); newSpline->computeCoefficients(currentMuscle, currentMuscle.begin()); splines_.push_back(newSpline); //splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 2: { std::shared_ptr<MTUSpline<2> > newSpline(new MTUSpline<2>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 3: { std::shared_ptr<MTUSpline<3> > newSpline(new MTUSpline<3>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 4: { std::shared_ptr<MTUSpline<4> > newSpline( new MTUSpline<4>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 5: { std::shared_ptr<MTUSpline<5> > newSpline(new MTUSpline<5>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 6: { std::shared_ptr<MTUSpline<6> > newSpline(new MTUSpline<6>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 7: { std::shared_ptr<MTUSpline<7> > newSpline( new MTUSpline<7>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } case 8: { std::shared_ptr<MTUSpline<8> > newSpline( new MTUSpline<8>(a_, b_, n_)); splines_.push_back(newSpline); vector<double> currentMuscle(y_[i]); splines_[i].get()->computeCoefficients(currentMuscle, currentMuscle.begin()); break; } //default: //throw dimException; } } return splines_; } vector< std::shared_ptr<MTUSplineBase> > MTUSplineData::createSplineDim(int numOfDim) { splines_.clear(); for (int i = 0; i < noMuscles_; ++i) { switch(numOfDim) { case 1: { std::shared_ptr<MTUSpline<1> > newSpline(new MTUSpline<1>(a_[0], b_[0], n_[0])); splines_.push_back(newSpline); break; } case 2: { std::shared_ptr<MTUSpline<2> > newSpline(new MTUSpline<2>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 3: { std::shared_ptr<MTUSpline<3> > newSpline(new MTUSpline<3>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 4: { std::shared_ptr<MTUSpline<4> > newSpline( new MTUSpline<4>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 5: { std::shared_ptr<MTUSpline<5> > newSpline(new MTUSpline<5>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 6: { std::shared_ptr<MTUSpline<6> > newSpline(new MTUSpline<6>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 7: { std::shared_ptr<MTUSpline<7> > newSpline( new MTUSpline<7>(a_, b_, n_)); splines_.push_back(newSpline); break; } case 8: { std::shared_ptr<MTUSpline<8> > newSpline( new MTUSpline<8>(a_, b_, n_)); splines_.push_back(newSpline); break; } //default: //throw dimException; } } return splines_; } void MTUSplineData::readInputData(const string& inputDataFilename) { // --- Read DOFs ifstream inputDataFile(inputDataFilename.c_str()); if (!inputDataFile.is_open()) { cout << "ERROR: " << inputDataFilename << " could not be open\n"; exit(EXIT_FAILURE); } for (int i = 0; i < N_DOF; ++i) { inputDataFile >> dofName_[i]; inputDataFile >> std::fixed >> std::setprecision(PRECISION) >> a_[i]; inputDataFile >> std::fixed >> std::setprecision(PRECISION) >> b_[i]; inputDataFile >> n_[i]; } string line; getline(inputDataFile, line, '\n'); getline(inputDataFile, line, '\n'); stringstream myStream(line); string nextMuscleName; // --- Read Interpolation Data // 1. first their names do { myStream >> nextMuscleName; muscleNames_.push_back(nextMuscleName); } while (!myStream.eof()); noMuscles_ = muscleNames_.size(); // 2. then their values for all the possible combination of DOFs values // 2a. create the matrix to store them noInputData_ = 1; for (int i = 0; i < N_DOF; ++i) noInputData_ *= (n_[i] + 1); for (int i = 0; i < noMuscles_; ++i) y_.push_back(vector<double>(noInputData_)); // 2b. read the data for (int j = 0; j < noInputData_; ++j) for (int i = 0; i < noMuscles_; ++i) { inputDataFile >> y_[i][j]; } inputDataFile.close(); } void MTUSplineData::displayInputData() { cout << "-- DOFs \n"; cout << "DofName\t a \t b \t n \t h \n"; for (int i = N_DOF - 1; i >= 0; --i) { cout << dofName_[i] << "\t"; cout << a_[i] << "\t"; cout << b_[i] << "\t"; cout << n_[i] << "\t"; cout << (b_[i] - a_[i]) / n_[i] << endl; } cout << "-- Data \n"; for (int i = N_DOF - 1; i >= 0; --i) cout << dofName_[i] << "\t"; for (int i = 0; i < noMuscles_; ++i) { cout << muscleNames_[i] << "\t"; } cout << endl; vector<int> index(N_DOF); double tot, mul; for (int soFar = 0; soFar < noInputData_; ++soFar) { tot = 0; mul = noInputData_; for (int i = N_DOF - 1; i > 0; --i) { mul = mul / (n_[i] + 1); index[i] = (soFar - tot) / mul; tot += index[i] * mul; } index[0] = soFar % (n_[0] + 1); for (int i = N_DOF - 1; i >= 0; --i) { cout << a_[i] + index[i] * (b_[i] - a_[i]) / n_[i] << "\t"; } for (int j = 0; j < noMuscles_; ++j) cout << y_[j][soFar] << "\t"; cout << endl; } } void MTUSplineData::readEvalAngles() { string anglesFilename = evalDataDir_ + "/angles.in"; ifstream anglesFile(anglesFilename.c_str()); if (!anglesFile.is_open()) { cout << "ERROR: " << anglesFilename << " could not be open\n"; exit(EXIT_FAILURE); } anglesFile >> noEvalData_; for (int i = 0; i < noEvalData_; ++i) angles_.push_back(vector<double>(N_DOF)); for (int i = 0; i < noEvalData_; ++i) for (int j = N_DOF - 1; j >= 0; --j) { anglesFile >> angles_[i][j]; } anglesFile.close(); } void MTUSplineData::readEvalAngles(const string& Filename, int dim) { ifstream anglesFile(Filename.c_str()); if (!anglesFile.is_open()) { cout << "ERROR: " << Filename << " could not be open\n"; exit(EXIT_FAILURE); } anglesFile >> noEvalData_; for (int i = 0; i < noEvalData_; ++i) angles_.push_back(vector<double>(dim)); for (int i = 0; i < noEvalData_; ++i) for (int j = 0; j < dim; j++) anglesFile >> std::fixed >> std::setprecision(PRECISION) >> angles_[i][j]; anglesFile.close(); } void MTUSplineData::openOutputFile(ofstream& outputDataFile) { if (!outputDataFile.is_open()) { cout << "ERROR: outputDataFile could not be open\n"; exit(EXIT_FAILURE); } for (int i = 0; i < noMuscles_; ++i) outputDataFile << muscleNames_[i] << "\t"; outputDataFile << endl; for (int i = 0; i < noMuscles_; ++i) outputDataFile << "eval\t"; outputDataFile << endl; } void MTUSplineData::openEvalFile(ifstream& evalDataFile) { if (!evalDataFile.is_open()) { cout << "ERROR: evalData File could not be open\n"; exit(EXIT_FAILURE); } // check we have the same amount of data of angles int numRows; evalDataFile >> numRows; if (numRows != noEvalData_) { cout << "ERROR: we have " << noEvalData_ << " angles, but " << numRows << " lines of data in input from the evalDataFile" << endl; exit(EXIT_FAILURE); } // check we have the same muscles string line; vector<string> muscleNames; getline(evalDataFile, line, '\n'); getline(evalDataFile, line, '\n'); stringstream myStream(line); string nextMuscle; do { myStream >> nextMuscle; muscleNames.push_back(nextMuscle); } while (!myStream.eof()); if (muscleNames.size() != static_cast<unsigned int>(noMuscles_)) { cout << "ERROR: we have " << noMuscles_ << " interpolated muscles, but " << muscleNames.size() << " muscles in the evalDataFile" << endl; exit(EXIT_FAILURE); } for (int i = 0; i < noMuscles_; ++i) { if (muscleNames[i] != muscleNames_[i]) { cout << "ERROR: the " << i << "-th muscle is " << muscleNames_[i] << " in the interpolated Data while" << muscleNames[i] << " in file evalData " << endl; exit(EXIT_FAILURE); } } } void MTUSplineData::evalLmt() { // First open the inputDataFile string evalDataFilename = evalDataDir_ + "lmt.in"; ifstream evalDataFile(evalDataFilename.c_str()); openEvalFile(evalDataFile); // Then open the outputDataFile string outputDataFilename = evalDataDir_ + "lmt.out"; ofstream outputDataFile(outputDataFilename.c_str()); openOutputFile(outputDataFile); // now readData double nextValue; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { outputDataFile << std::fixed << std::setprecision(PRECISION) << splines_[i]->getValue(angles_[j]) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } template <class T> void MTUSplineData::evalLmt(const string& outputDataFilename, T& splines) { ofstream outputDataFile(outputDataFilename.c_str()); outputDataFile << noEvalData_ << endl; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { cpt_++; outputDataFile << std::fixed << std::setprecision(PRECISION) << splines[i]->getValue(angles_[j]) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<1> > >& splines) { ofstream outputDataFile(outputDataFilename.c_str()); outputDataFile << noEvalData_ << endl; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { cpt_++; outputDataFile << std::fixed << std::setprecision(PRECISION) << splines[i]->getValue(angles_[j][0]) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } void MTUSplineData::evalMa() { // for all the degree of freedom for (int k = 0; k < N_DOF; ++k) { // First open the inputDataFile string evalDataFilename = evalDataDir_ + "ma" + dofName_[k] + ".in"; ifstream evalDataFile(evalDataFilename.c_str()); openEvalFile(evalDataFile); // Then open the outputDataFile string outputDataFilename = evalDataDir_ + "ma" + dofName_[k] + ".out"; ofstream outputDataFile(outputDataFilename.c_str()); openOutputFile(outputDataFile); double nextValue; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { outputDataFile << std::fixed << std::setprecision(PRECISION) << -splines_[i]->getFirstDerivative(angles_[j], k) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } } template <class T> void MTUSplineData::evalMa(const string& outputDataFilename, T& splines, int dim) { ofstream outputDataFile(outputDataFilename.c_str()); outputDataFile << noEvalData_ << endl; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { cpt_++; outputDataFile << std::fixed << std::setprecision(PRECISION) <<-splines[i]->getFirstDerivative(angles_[j], dim) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<1> > >& splines, int dim) { ofstream outputDataFile(outputDataFilename.c_str()); outputDataFile << noEvalData_ << endl; for (int j = 0; j < noEvalData_; ++j) { for (int i = 0; i < noMuscles_; ++i) { cpt_++; outputDataFile << std::fixed << std::setprecision(PRECISION)<< -splines[i]->getFirstDerivative(angles_[j][0]) << "\t"; } outputDataFile << endl; } outputDataFile.close(); } template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<2> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<3> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<4> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<5> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<6> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<7> > >& splines, int dim); template void MTUSplineData::evalMa(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<8> > >& splines, int dim); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<2> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<3> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<4> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<5> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<6> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<7> > >& splines); template void MTUSplineData::evalLmt(const string& outputDataFilename, vector<std::shared_ptr<MTUSpline<8> > >& splines);
27.135952
129
0.671064
GuillaumeVDu
9b5f9afc0bdd486988c4a933a6947159cf4e2279
5,315
cpp
C++
drivers/AT24Cxx/AT24Cxx.cpp
GXUNiot/mbed
39634be44c4d5c62883b0177c138952029550b0d
[ "MIT" ]
null
null
null
drivers/AT24Cxx/AT24Cxx.cpp
GXUNiot/mbed
39634be44c4d5c62883b0177c138952029550b0d
[ "MIT" ]
null
null
null
drivers/AT24Cxx/AT24Cxx.cpp
GXUNiot/mbed
39634be44c4d5c62883b0177c138952029550b0d
[ "MIT" ]
null
null
null
#include "AT24Cxx.h" AT24CXX::AT24CXX(I2C *i2c, uint16_t size, uint8_t hardaddr, uint32_t feq) { AT24CXX::_i2c = i2c; uint16_t i; for(i=512; i>=0x01; i>>=1) { if( size == i ) { break; } } _storageSize = i; if( _storageSize == 1 ) { _pageSize = 8; } else if( _storageSize <= 16 ) { _pageSize = 16; } else if( _storageSize <= 64 ) { _pageSize = 32; } else if( _storageSize <= 256 ) { _pageSize = 64; } _addrSize = i*128; _feq = feq; _hardAddr = (hardaddr & 0x7)<<1; } AT24CXX::~AT24CXX() { _i2c = NULL; } uint8_t AT24CXX::read(uint16_t addr, uint8_t *data) { //检查地址有效性 if( addr >= _addrSize ) return 5; (*_i2c).frequency(_feq); (*_i2c).start(); //伪写 if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { wait_ms(10); (*_i2c).start(); if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { (*_i2c).stop(); return 4; } } //如果是长地址 if( _addrSize > 0xFF ) //发送高位地址 if( (*_i2c).write(addr >> 8) != 1 ) {(*_i2c).stop();return 3;} //发送低位地址 if( (*_i2c).write(addr & 0xFF) != 1 ) {(*_i2c).stop();return 2;} //读命令 (*_i2c).start(); if( (*_i2c).write(0xA1 | _hardAddr ) != 1 ) {(*_i2c).stop();return 1;} *data = (*_i2c).read(0); //操作完成 (*_i2c).stop(); return 0; } uint8_t AT24CXX::readNow(uint8_t *data) { (*_i2c).frequency(_feq); (*_i2c).start(); //读命令 if( (*_i2c).write(0xA1|_hardAddr) != 1 ) { wait_ms(10); (*_i2c).start(); if( (*_i2c).write(0xA1|_hardAddr) != 1 ) { (*_i2c).stop(); return 1; } } *data = (*_i2c).read(0); //操作完成 (*_i2c).stop(); return 0; } uint8_t AT24CXX::read(uint16_t addr, uint8_t *dataArray, uint16_t len) { //检查地址有效性 if( addr >= _addrSize || (addr + len) > _addrSize ) return 5; (*_i2c).frequency(_feq); (*_i2c).start(); //伪写 if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { wait_ms(10); (*_i2c).start(); if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { (*_i2c).stop(); return 4; } } //如果是长地址 if( _addrSize > 0xFF ) //发送高位地址 if( (*_i2c).write(addr >> 8) != 1 ) {(*_i2c).stop();return 3;} //发送低位地址 if( (*_i2c).write(addr & 0xFF) != 1 ) {(*_i2c).stop();return 2;} //读命令 (*_i2c).start(); if( (*_i2c).write(0xA1 | _hardAddr ) != 1 ) {(*_i2c).stop();return 1;} //连续读取 for(; len >0; len--,dataArray++) if(len!=1) *dataArray = (*_i2c).read(1); else *dataArray = (*_i2c).read(0); //操作完成 (*_i2c).stop(); return 0; } uint8_t AT24CXX::write(uint16_t addr, uint8_t data) { //检查地址有效性 if( addr >= _addrSize ) return 5; (*_i2c).frequency(_feq); (*_i2c).start(); //写命令 if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { wait_ms(10); (*_i2c).start(); if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { (*_i2c).stop(); return 4; } } //如果是长地址 if( _addrSize > 0xFF ) //发送高位地址 if( (*_i2c).write(addr >> 8) != 1 ) {(*_i2c).stop();return 3;} //发送低位地址 if( (*_i2c).write(addr & 0xFF) != 1 ) {(*_i2c).stop();return 2;} //发送数据 if( (*_i2c).write(data & 0xFF) != 1 ) {(*_i2c).stop();return 1;} //操作完成 (*_i2c).stop(); return 0; } uint8_t AT24CXX::writePage(uint16_t addr, const uint8_t* data, uint8_t len) { //检查地址有效性 if( addr >= _addrSize ) return 7; if( (addr + len) > _addrSize ) return 6; if( len > _pageSize ) return 5; //不是整页地址 if( (addr % _pageSize) != 0 ) { //计算当前页剩余地址 uint8_t shortlen = _pageSize-(addr % _pageSize); //写入长度超剩余地址 if( len > shortlen ) { //拆分写入页 uint8_t result = writePage(addr,data,shortlen); if( result != 0 ) return (10+result); addr += shortlen; data += shortlen; len -= shortlen; wait_ms(10); } } (*_i2c).frequency(_feq); (*_i2c).start(); //写命令 if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { wait_ms(10); (*_i2c).start(); if( (*_i2c).write(0xA0|_hardAddr) != 1 ) { (*_i2c).stop(); return 4; } } //如果是长地址 if( _addrSize > 0xFF ) //发送高位地址 if( (*_i2c).write(addr >> 8) != 1 ) {(*_i2c).stop();return 3;} //发送低位地址 if( (*_i2c).write(addr & 0xFF) != 1 ) {(*_i2c).stop();return 2;} for( ; len>0; len--,data++) if( (*_i2c).write((*data) & 0xFF) != 1 ) {(*_i2c).stop();return 1;} //操作完成 (*_i2c).stop(); return 0; } uint8_t AT24CXX::write(uint16_t addr, const uint8_t* data, uint16_t len) { //检查地址有效性 if( addr >= _addrSize ) return 6; if( (addr + len) > _addrSize ) return 5; uint8_t count = 1; while( len > _pageSize ) { //printf("addr:%d\rlen:%d",addr,len); uint8_t result = writePage(addr,data,_pageSize); if( result != 0 ) return (count*10+result); count++; addr += _pageSize; data += _pageSize; len -= _pageSize; wait_ms(10); }; //printf("addr:%d\rlen:%d",addr,len); return writePage(addr,data,len); } uint16_t AT24CXX::getStorageSize(void) { return AT24CXX::_storageSize; } uint8_t AT24CXX::getPageSize(void) { return AT24CXX::_pageSize; } uint16_t AT24CXX::getMaxAddr(void) { return AT24CXX::_addrSize; }
18.078231
75
0.519473
GXUNiot
9b616ec4b4d118f2ff45fd6fd8909f0fee40fde4
2,117
cpp
C++
Assets/Chunity/Plugins/iOS/chuck_utils.cpp
marek-stoj/Chuckings
fcca01afdc759b8d374c5ab3d31d010c1174af04
[ "Unlicense" ]
21
2016-02-11T17:28:13.000Z
2018-03-27T00:42:28.000Z
lib/chuck/chuck_utils.cpp
PaulBatchelor/tiziku
d603fd8de5dbdfdbbfba350ffc9d5f5d6f03ee99
[ "MIT" ]
2
2016-01-19T21:58:34.000Z
2016-01-20T03:17:13.000Z
lib/chuck/chuck_utils.cpp
PaulBatchelor/tiziku
d603fd8de5dbdfdbbfba350ffc9d5f5d6f03ee99
[ "MIT" ]
5
2016-01-15T04:52:36.000Z
2019-05-07T00:52:23.000Z
/*---------------------------------------------------------------------------- ChucK Concurrent, On-the-fly Audio Programming Language Compiler and Virtual Machine Copyright (c) 2004 Ge Wang and Perry R. Cook. All rights reserved. http://chuck.stanford.edu/ http://chuck.cs.princeton.edu/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 U.S.A. -----------------------------------------------------------------------------*/ //----------------------------------------------------------------------------- // file: chuck_utils.cpp // desc: common utils, adapted from Tiger Compiler Andrew Appel // // author: Ge Wang (ge@ccrma.stanford.edu | gewang@cs.princeton.edu) // adapted from: Andrew Appel (appel@cs.princeton.edu) // date: Summer 2002 //----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include "chuck_utils.h" #include "chuck_errmsg.h" void * checked_malloc( int len ) { if( !len ) return NULL; void *p = calloc( len, 1 ); if( !p ) { EM_error2( 0, "out of memory!\n" ); exit( 1 ); } return p; } c_str cc_str( char * s ) { c_str p = (c_str)checked_malloc( strlen(s)+1 ); strcpy( p, s ); return p; } U_boolList U_BoolList( t_CKBOOL head, U_boolList tail ) { U_boolList list = (U_boolList)checked_malloc( sizeof(*list) ); list->head = head; list->tail = tail; return list; }
27.141026
79
0.585262
marek-stoj
9b6541346a3ffd37f45f0ef5b8b1a1f33977679c
5,492
c++
C++
audio/audio_test.initial.c++
pyrocharles/basilio_chat
5f7a23eb6ab964e6fcc5b6e3334d45a3a769b13c
[ "MIT" ]
null
null
null
audio/audio_test.initial.c++
pyrocharles/basilio_chat
5f7a23eb6ab964e6fcc5b6e3334d45a3a769b13c
[ "MIT" ]
null
null
null
audio/audio_test.initial.c++
pyrocharles/basilio_chat
5f7a23eb6ab964e6fcc5b6e3334d45a3a769b13c
[ "MIT" ]
null
null
null
// #include "core_audio.h++" #include "portaudio/portaudio.h" #include <iostream> #include <exception> #include <string> /** * General PortAudio exception class, thrown when there's an error initializing * or terminating the library. * * @author Charles Van West * @version 0.0 */ class PortAudio_Exception : public std::exception { public: PortAudio_Exception(const PaError err) : error(Pa_GetErrorText(err)) { } PortAudio_Exception(const std::string& err) : error(err) { } std::string get_error() const { return error; } private: std::string error; }; /** * More specific PortAudio exception class, thrown when something goes wrong * while using the library. * * @author Charles Van West * @version 0.0 */ class PortAudio_Use_Exception : public PortAudio_Exception { public: using PortAudio_Exception::PortAudio_Exception; /* inherit constructors */ }; /** * Structure to pass a static data field to the callback function */ struct pa_test_data { float left_phase, right_phase; }; /** * Callback function for testing out PortAudio. Parameters should be pretty * self-explanatory. */ static int pa_test_callback(const void* input_buffer, void* output_buffer, unsigned long int buffer_frames, const PaStreamCallbackTimeInfo* time_info, PaStreamCallbackFlags status_flags, void* user_data) { /* cast data into a reasonable structure */ pa_test_data* data = static_cast<pa_test_data*>(user_data); const float* in = static_cast<const float*>(input_buffer); float* out = static_cast<float*>(output_buffer); for (unsigned long int i = 0; i < buffer_frames; ++i) { /* read left and right phase from input buffer into data, then shift */ data->left_phase = *(in++); data->right_phase = data->left_phase; /* put left and right phase into output buffer, then shift by two */ out[0] = data->left_phase; out[1] = data->right_phase; out += 2; } return 0; } int main() { static constexpr int SAMPLE_RATE = 44100; static pa_test_data data; try { PaError error; /* initialize PortAudio */ error = Pa_Initialize(); if (error != paNoError) { throw PortAudio_Exception(error); } else { std::cout << "Initialized PortAudio successfully." << std::endl; } /* open a stream */ PaStream* stream; error = Pa_OpenDefaultStream(&stream, 1, /* mono input */ 2, /* stereo output */ paFloat32, /* 32 bit floating point samples */ SAMPLE_RATE, paFramesPerBufferUnspecified, /* frames per buffer, i.e. the number of sample frames that PortAudio will request from the callback. Many apps may want to use paFramesPerBufferUnspecified, which tells PortAudio to pick the best, possibly changing, buffer size.*/ pa_test_callback, /* the callback function */ &data); /* pointer that will be passed to the callback as user_data */ if (error != paNoError) { throw PortAudio_Use_Exception(error); } else { std::cout << "Opened a stream." << std::endl; } /* start the stream */ error = Pa_StartStream(stream); if (error != paNoError) { throw PortAudio_Use_Exception(error); } else { std::cout << "Initialized the stream." << std::endl; } /* sleep for some seconds */ Pa_Sleep(10000); /* stop the stream */ error = Pa_StopStream(stream); if (error != paNoError) { throw PortAudio_Use_Exception(error); } else { std::cout << "Stopped the stream." << std::endl; } /* close the stream */ error = Pa_CloseStream(stream); if (error != paNoError) { throw PortAudio_Use_Exception(error); } else { std::cout << "Closed the stream." << std::endl; } /* terminate PortAudio */ error = Pa_Terminate(); if (error != paNoError) { throw PortAudio_Exception(error); } else { std::cout << "Terminated PortAudio successfully." << std::endl; } } catch (PortAudio_Use_Exception exc) { std::cout << "Error using PortAudio: " << exc.get_error() << std::endl; Pa_Terminate(); return 1; } catch (PortAudio_Exception exc) { std::cout << "Error in PortAudio: " << exc.get_error() << std::endl; return 2; } return 0; }
34.759494
80
0.510197
pyrocharles
9b654ca7b697e4cf6a365ea36356a26187875e44
6,682
cpp
C++
Lib/vc4/DMA/DMA.cpp
Freddan-67/V3DLib
dcefc24a9a399ee1f5d1aa5529f44d9fd2486929
[ "MIT" ]
44
2021-01-16T14:17:15.000Z
2022-03-11T19:53:59.000Z
Lib/vc4/DMA/DMA.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
8
2021-01-16T17:52:02.000Z
2021-12-18T22:38:00.000Z
Lib/vc4/DMA/DMA.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
7
2021-01-16T14:25:47.000Z
2022-02-03T16:34:45.000Z
#include "DMA.h" #include "Support/basics.h" #include "Support/Helpers.h" #include "Helpers.h" namespace V3DLib { namespace DMA { using ::operator<<; // C++ weirdness void Stmt::setupVPMRead(int n, Expr::Ptr addr, bool hor, int stride) { m_setupVPMRead.numVecs = n; m_setupVPMRead.stride = stride; m_setupVPMRead.hor = hor; address_internal(addr); } void Stmt::setupVPMWrite(Expr::Ptr addr, bool hor, int stride) { m_setupVPMWrite.stride = stride; m_setupVPMWrite.hor = hor; address_internal(addr); } void Stmt::setupDMARead(bool is_horizontal, int numRows, Expr::Ptr addr, int rowLen, int vpitch) { m_setupDMARead.hor = is_horizontal?1 : 0; m_setupDMARead.numRows = numRows; m_setupDMARead.rowLen = rowLen; m_setupDMARead.vpitch = vpitch; address_internal(addr); } void Stmt::setupDMAWrite(bool is_horizontal, int numRows, Expr::Ptr addr, IntExpr rowLen) { m_setupDMAWrite.hor = is_horizontal? 1 : 0; m_setupDMAWrite.numRows = numRows; m_setupDMAWrite.rowLen = rowLen; address_internal(addr); } Expr::Ptr Stmt::stride_internal() { assert(m_exp.get() != nullptr); return m_exp; } bool Stmt::address(int in_tag, Expr::Ptr e0) { auto tag = to_tag(in_tag); if (is_dma_readwrite_tag(tag) || tag == V3DLib::Stmt::SET_READ_STRIDE || tag == V3DLib::Stmt::SET_WRITE_STRIDE) { address_internal(e0); return true; } return false; } void Stmt::address_internal(Expr::Ptr e0) { assertq(e0 != nullptr, "DMA set address"); m_exp = e0; } Expr::Ptr Stmt::address_internal() { assert(m_exp.get() != nullptr); return m_exp; } std::string Stmt::pretty(int indent, int in_tag) { auto tag = to_tag(in_tag); std::string ret; switch (tag) { case V3DLib::Stmt::SET_READ_STRIDE: ret << indentBy(indent) << "dmaSetReadPitch(" << stride_internal()->pretty() << ");"; break; case V3DLib::Stmt::SET_WRITE_STRIDE: ret << indentBy(indent) << "dmaSetWriteStride(" << stride_internal()->pretty() << ")"; break; case V3DLib::Stmt::SEMA_INC: // Increment semaphore ret << indentBy(indent) << "semaInc(" << m_semaId << ");"; break; case V3DLib::Stmt::SEMA_DEC: // Decrement semaphore ret << indentBy(indent) << "semaDec(" << m_semaId << ");"; break; case V3DLib::Stmt::SEND_IRQ_TO_HOST: ret << indentBy(indent) << "hostIRQ();"; break; case V3DLib::Stmt::SETUP_VPM_READ: ret << indentBy(indent) << "vpmSetupRead(" << "numVecs=" << m_setupVPMRead.numVecs << "," << "dir=" << (m_setupVPMRead.hor ? "HOR" : "VIR") << "," << "stride=" << m_setupVPMRead.stride << "," << address_internal()->pretty() << ");"; break; case V3DLib::Stmt::SETUP_VPM_WRITE: ret << indentBy(indent) << "vpmSetupWrite(" << "dir=" << (m_setupVPMWrite.hor ? "HOR" : "VIR") << "," << "stride=" << m_setupVPMWrite.stride << "," << address_internal()->pretty() << ");"; break; case V3DLib::Stmt::DMA_READ_WAIT: ret << indentBy(indent) << "dmaReadWait();"; break; case V3DLib::Stmt::DMA_WRITE_WAIT: ret << indentBy(indent) << "dmaWriteWait();"; break; case V3DLib::Stmt::DMA_START_READ: ret << indentBy(indent) << "dmaStartRead(" << address_internal()->pretty() << ");"; break; case V3DLib::Stmt::DMA_START_WRITE: ret << indentBy(indent) << "dmaStartWrite(" << address_internal()->pretty() << ");"; break; case V3DLib::Stmt::SETUP_DMA_READ: ret << indentBy(indent) << "dmaSetupRead(" << "numRows=" << m_setupDMARead.numRows << "," << "rowLen=%" << m_setupDMARead.rowLen << "," << "dir=" << (m_setupDMARead.hor ? "HORIZ" : "VERT") << "," << "vpitch=" << m_setupDMARead.vpitch << "," << address_internal()->pretty() << ");"; break; case V3DLib::Stmt::SETUP_DMA_WRITE: { Expr::Ptr rle = m_setupDMAWrite.rowLen.expr(); if (rle->tag() == Expr::INT_LIT) { breakpoint } ret << indentBy(indent) << "dmaSetupWrite(" << "numRows=" << m_setupDMAWrite.numRows << "," << "rowLen=" << rle->dump() << "," << "dir=" << (m_setupDMAWrite.hor ? "HORIZ" : "VERT") << "," << address_internal()->pretty() << ");"; } break; default: break; } return ret; } /** * TODO test */ std::string disp(int in_tag) { auto tag = to_tag(in_tag); std::string ret; switch (tag) { case V3DLib::Stmt::SET_READ_STRIDE: ret << "SET_READ_STRIDE"; break; case V3DLib::Stmt::SET_WRITE_STRIDE: ret << "SET_WRITE_STRIDE"; break; case V3DLib::Stmt::SEND_IRQ_TO_HOST: ret << "SEND_IRQ_TO_HOST"; break; case V3DLib::Stmt::SEMA_INC: ret << "SEMA_INC"; break; case V3DLib::Stmt::SEMA_DEC: ret << "SEMA_DEC"; break; case V3DLib::Stmt::SETUP_VPM_READ: ret << "SETUP_VPM_READ"; break; case V3DLib::Stmt::SETUP_VPM_WRITE: ret << "SETUP_VPM_WRITE"; break; case V3DLib::Stmt::SETUP_DMA_READ: ret << "SETUP_DMA_READ"; break; case V3DLib::Stmt::SETUP_DMA_WRITE: ret << "SETUP_DMA_WRITE"; break; case V3DLib::Stmt::DMA_READ_WAIT: ret << "DMA_READ_WAIT"; break; case V3DLib::Stmt::DMA_WRITE_WAIT: ret << "DMA_WRITE_WAIT"; break; case V3DLib::Stmt::DMA_START_READ: ret << "DMA_START_READ"; break; case V3DLib::Stmt::DMA_START_WRITE: ret << "DMA_START_WRITE"; break; default: break; } return ret; } bool Stmt::is_dma_readwrite_tag(int in_tag) { auto tag = to_tag(in_tag); switch (tag) { case V3DLib::Stmt::SETUP_VPM_READ: case V3DLib::Stmt::SETUP_VPM_WRITE: case V3DLib::Stmt::SETUP_DMA_READ: case V3DLib::Stmt::SETUP_DMA_WRITE: case V3DLib::Stmt::DMA_START_READ: case V3DLib::Stmt::DMA_START_WRITE: return true; default: return false; } } bool Stmt::is_dma_tag(int in_tag) { if (is_dma_readwrite_tag(in_tag)) return true; auto tag = to_tag(in_tag); switch (tag) { case V3DLib::Stmt::SET_READ_STRIDE: case V3DLib::Stmt::SET_WRITE_STRIDE: case V3DLib::Stmt::SEMA_INC: case V3DLib::Stmt::SEMA_DEC: case V3DLib::Stmt::SEND_IRQ_TO_HOST: case V3DLib::Stmt::DMA_READ_WAIT: case V3DLib::Stmt::DMA_WRITE_WAIT: return true; default: return false; } } } // namespace DMA } // namespace V3DLib
27.385246
98
0.59144
Freddan-67
9b67a50c4f87f8329edd5270930a0f8f84f55d9b
5,443
cpp
C++
models/memory/CaffDRAM/Bank.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/memory/CaffDRAM/Bank.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/memory/CaffDRAM/Bank.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* * Bank.cpp * * Created on: Jun 14, 2011 * Author: rishirajbheda */ #include "Bank.h" #include "kernel/manifold.h" using namespace std; namespace manifold { namespace caffdram { Bank::Bank(const Dsettings* dramSetting) { // TODO Auto-generated constructor stub this->dramSetting = dramSetting; this->firstAccess = true; this->lastAccessedRow = 0; this->bankAvailableAtTime = 0; stats = new Bank_stat_engine(); } Bank::~Bank() { // TODO Auto-generated destructor stub delete stats; } //private copy contructor only used by unit test Bank :: Bank(const Bank& b) { *this = b; this->stats = new Bank_stat_engine(); } unsigned long int Bank::processRequest(Dreq* dRequest) { #ifdef DBG_CAFFDRAM cout << "request originTime= " << dRequest->get_originTime() << " Bank available time= " << bankAvailableAtTime << endl; #endif //req_info info; //info.old_avail = bankAvailableAtTime; //info.orig = dRequest->get_originTime(); pair<uint64_t, uint64_t> busy; unsigned long int returnLatency = 0; //bool org_less_than_avail = false; if (dRequest->get_originTime() <= this->bankAvailableAtTime) { //org_less_than_avail = true; busy.first = bankAvailableAtTime; //become busy starting at bankAvailableAtTime } else { busy.first = dRequest->get_originTime(); //become busy starting at origin time this->bankAvailableAtTime = dRequest->get_originTime(); } if (this->dramSetting->memPagePolicy == OPEN_PAGE) { returnLatency = this->processOpenPageRequest(dRequest); } else { returnLatency = this->processClosedPageRequest(dRequest); } //info.new_avail = bankAvailableAtTime; //reqs.push_back(info); busy.second = bankAvailableAtTime; //bankAvailableAtTime has been updated busy.first = bankAvailableAtTime - busy.first; //busy for this number of cycles due to this request if(stats_busy_cycles.size() > 0) busy.first += stats_busy_cycles.back().first; //accumulate assert(busy.first <= busy.second); stats_busy_cycles.push_back(busy); if(stats_busy_cycles.size() > 100) //only keep 100 pairs stats_busy_cycles.pop_front(); stats->num_requests++; stats->latencies.collect(returnLatency - dRequest->get_originTime()); return (returnLatency); } unsigned long int Bank::processOpenPageRequest(Dreq* dRequest) { unsigned long int returnLatency = 0; if (this->firstAccess == false) { if (dRequest->get_rowId() == this->lastAccessedRow) { this->bankAvailableAtTime += this->dramSetting->t_CAS; } else { this->bankAvailableAtTime += this->dramSetting->t_RP; this->bankAvailableAtTime += (this->dramSetting->t_RCD + this->dramSetting->t_CAS); } } else { this->bankAvailableAtTime += (this->dramSetting->t_RCD + this->dramSetting->t_CAS); this->firstAccess = false; } unsigned long endT = this->bankAvailableAtTime + this->dramSetting->t_BURST; dRequest->set_endTime(endT); returnLatency = endT; this->lastAccessedRow = dRequest->get_rowId(); return (returnLatency); } unsigned long int Bank::processClosedPageRequest(Dreq* dRequest) { unsigned long int returnLatency = 0; this->bankAvailableAtTime += (this->dramSetting->t_RCD + this->dramSetting->t_CAS); this->bankAvailableAtTime += this->dramSetting->t_RP; unsigned long endT = this->bankAvailableAtTime + this->dramSetting->t_BURST; dRequest->set_endTime(endT); returnLatency = endT; return (returnLatency); } void Bank::print_stats (ostream & out) { stats->print_stats(out); uint64_t endTick = manifold::kernel::Manifold::NowTicks(); #if 0 for(list<req_info>::iterator it=reqs.begin(); it != reqs.end(); ++it) { out << "(" << it->old_avail << ", " << it->orig << ", " << it->new_avail << ") "; } out<<endl; for(list<pair<uint64_t, uint64_t> >::iterator it=stats_busy_cycles.begin(); it != stats_busy_cycles.end(); ++it) { out << "(" << it->first << ", " << it->second << ") "; } out<<endl; #endif if(stats_busy_cycles.size() > 0) { if(stats_busy_cycles.back().second > endTick) { list<pair<uint64_t, uint64_t> >::iterator it = stats_busy_cycles.begin(); for(; it != stats_busy_cycles.end(); ++it) { if(it->second > endTick) break; } out << "busy cycles= " << it->first << "(" << (it->first) / ((double)endTick) * 100 << "%)"; if(it == stats_busy_cycles.begin()) out << " **"; } else { out << "busy cycles= " << stats_busy_cycles.back().first << "(" << (stats_busy_cycles.back().first)/((double)endTick) * 100 << "%)"; } out << endl; } else { out << "busy cycles= 0\n"; } } Bank_stat_engine::Bank_stat_engine () : Stat_engine(), num_requests("Number of Requests", ""), latencies("Average Memory Latency", "", 1000, 5, 0) { } Bank_stat_engine::~Bank_stat_engine () { } void Bank_stat_engine::global_stat_merge(Stat_engine * e) { Bank_stat_engine * global_engine = (Bank_stat_engine*)e; global_engine->num_requests += num_requests.get_value(); global_engine->latencies.merge(&latencies); } void Bank_stat_engine::print_stats (ostream & out) { num_requests.print(out); latencies.print(out); //out << latencies.get_average() << endl; } void Bank_stat_engine::clear_stats() { num_requests.clear(); latencies.clear(); } void Bank_stat_engine::start_warmup () { } void Bank_stat_engine::end_warmup () { } void Bank_stat_engine::save_samples () { } } //namespace caffdram } //namespace manifold
24.299107
137
0.681058
Basseuph
9b69ce4fa6a4aeaff0e8c0f76919d5bb82ff8ba1
430
cc
C++
google_interview_practice/Angle_Between_Hands_of_a_Clock/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
google_interview_practice/Angle_Between_Hands_of_a_Clock/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
google_interview_practice/Angle_Between_Hands_of_a_Clock/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { public: double angleClock(int hour, int minutes) { double minAngle = (double)minutes * 6.0f; double hourAngle = (double)hour * 30.0f + (double)minutes * 0.5f; double angle; if (hourAngle >= 360.0f) hourAngle -= 360.f; angle = (hourAngle > minAngle) ? (hourAngle - minAngle) : (minAngle - hourAngle); return (angle > 180.f) ? (360.0f - angle) : angle; } };
33.076923
89
0.588372
ldy121
9b7008e29e28bdfe814c711b660c3d8a7f29f92d
1,937
hpp
C++
em_unet/src/PyGreentea/evaluation/src_cython/zi/zunit/registry.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
10
2018-09-13T17:37:22.000Z
2020-05-08T16:20:42.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/zunit/registry.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
1
2018-12-02T14:17:39.000Z
2018-12-02T20:59:26.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/zunit/registry.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
2
2019-03-03T12:06:10.000Z
2020-04-12T13:23:02.000Z
// // Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu> // ---------------------------------------------------------- // // 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/>. // #ifndef ZI_ZUNIT_REGISTRY_HPP #define ZI_ZUNIT_REGISTRY_HPP 1 #include <zi/zunit/config.hpp> #include <zi/zunit/test_case.hpp> #include <zi/zunit/test_suite.hpp> #include <zi/zunit/tags.hpp> #include <zi/time/timer.hpp> #include <zi/utility/enable_singleton_of_this.hpp> #include <zi/utility/non_copyable.hpp> #include <zi/utility/for_each.hpp> #include <zi/bits/ref.hpp> #include <list> #include <cstddef> namespace zi { namespace zunit { class registry: public enable_singleton_of_this< registry > { private: std::list< reference_wrapper< test_suite > > suites_; public: registry(): suites_() {} void add_suite( test_suite& suite ) { suites_.push_front( ref( suite ) ); } void run_all() { std::size_t total_tests_passed = 0; std::size_t total_suites_passed = 0; FOR_EACH( it, suites_ ) { std::size_t tests_passed = it->get().run_all(); if ( tests_passed >= 0 ) { total_tests_passed += tests_passed; ++total_suites_passed; } } } }; } // namespace zunit } // namespace zi #endif
24.518987
72
0.65049
VCG
f927b774e27cde416407c0404a9e3b45c5c5e104
1,221
cpp
C++
src/main.cpp
mliszcz/tango-fs
7f9bf2b88e5a76ad9a418ca8662b0cf458d9e678
[ "MIT" ]
null
null
null
src/main.cpp
mliszcz/tango-fs
7f9bf2b88e5a76ad9a418ca8662b0cf458d9e678
[ "MIT" ]
null
null
null
src/main.cpp
mliszcz/tango-fs
7f9bf2b88e5a76ad9a418ca8662b0cf458d9e678
[ "MIT" ]
null
null
null
#define FUSE_USE_VERSION 30 #include <handlers/getattr.hpp> #include <handlers/readdir.hpp> #include <handlers/open.hpp> #include <handlers/read.hpp> #include <paths.hpp> #include <tango.hpp> #include <fuse.h> #include <utility> namespace { const auto handler = paths::makeFuseHandler(tango::createDatabase, tango::createDeviceProxy); constexpr auto getattr = [](auto&& p) { return handlers::getattr(std::forward<decltype(p)>(p)); }; constexpr auto open_ = [](auto&& p) { return handlers::open(std::forward<decltype(p)>(p)); }; constexpr auto read_ = [](auto&& p) { return handlers::read(std::forward<decltype(p)>(p)); }; constexpr auto readdir = [](auto&& p) { return handlers::readdir(std::forward<decltype(p)>(p)); }; } // namespace int main(int argc, char *argv[]) { struct fuse_operations ops{}; ops.getattr = [](auto... args) { return handler(getattr)(args...); }; ops.open = [](auto... args) { return handler(open_)(args...); }; ops.read = [](auto... args) { return handler(read_)(args...); }; ops.readdir = [](auto... args) { return handler(readdir)(args...); }; return fuse_main(argc, argv, &ops, nullptr); }
25.4375
73
0.622441
mliszcz
f92fd52099ef73adc1d00cbbe3783752db54732c
3,061
hpp
C++
em_unet/src/PyGreentea/evaluation/src_cython/zi/disjoint_sets/disjoint_sets2.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
10
2018-09-13T17:37:22.000Z
2020-05-08T16:20:42.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/disjoint_sets/disjoint_sets2.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
1
2018-12-02T14:17:39.000Z
2018-12-02T20:59:26.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/disjoint_sets/disjoint_sets2.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
2
2019-03-03T12:06:10.000Z
2020-04-12T13:23:02.000Z
// // Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu> // ---------------------------------------------------------- // // 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/>. // #ifndef ZI_DISJOINT_SETS_DISJOINT_SETS2_HPP #define ZI_DISJOINT_SETS_DISJOINT_SETS2_HPP 1 #include <zi/config/config.hpp> #include <zi/bits/type_traits.hpp> #include <zi/utility/enable_if.hpp> #include <zi/utility/assert.hpp> #include <zi/utility/detail/empty_type.hpp> #include <cstddef> #include <cassert> namespace zi { template< class T > class disjoint_sets2: enable_if< is_integral< T >::value, detail::empty_type >::type { private: struct node { T r, p, v; node(): r(0), p(0) { } }; node *x_; T size_ ; T sets_ ; inline T find_set_( T id ) const { ZI_ASSERT( id < size_ ); T n( id ), x; while ( n != x_[ n ].p ) { n = x_[ n ].p; } while ( n != id ) { x = x_[ id ].p; x_[ id ].p = n; id = x; } return n; } public: disjoint_sets2( const T& s ): size_( s ), sets_( s ) { ZI_ASSERT( s >= 0 ); x_ = new node[ s ]; for ( T i = 0; i < s; ++i ) { x_[ i ].p = i; x_[ i ].v = i; x_[ i ].r = 0; } } ~disjoint_sets2() { delete [] x_; } inline T find_set( T id ) const { return x_[ find_set_( id ) ].v; } inline T join( T ox, T oy ) { ZI_ASSERT( ox < size_ && ox >= 0 ); ZI_ASSERT( oy < size_ && oy >= 0 ); T x = find_set_( ox ); T y = find_set_( oy ); if ( x == y ) { return x_[ x ].v; } --sets_; if ( x_[ x ].r >= x_[ y ].r ) { x_[ y ].p = x; if ( x_[ x ].r == x_[ y ].r ) { ++x_[x].r; } x_[ x ].v = oy; return oy; } x_[ x ].p = y; x_[ y ].v = oy; return oy; } inline void clear() { for ( T i = 0; i < size_; ++i ) { x_[ i ].p = i; x_[ i ].v = i; x_[ i ].r = 0; } sets_ = size_; } T size() const { return size_; } T set_count() const { return sets_; } }; } // namespace zi #endif
19.876623
72
0.469128
VCG
f935da8431f92003a01979a6258194fe2551c085
2,262
hpp
C++
src/output/output_manager.hpp
savcardamone/tyche-
ea89edea89a607291e4fe0ba738d75522f54dc1a
[ "MIT" ]
null
null
null
src/output/output_manager.hpp
savcardamone/tyche-
ea89edea89a607291e4fe0ba738d75522f54dc1a
[ "MIT" ]
1
2018-12-28T13:30:16.000Z
2018-12-29T10:30:33.000Z
src/output/output_manager.hpp
savcardamone/tyche
ea89edea89a607291e4fe0ba738d75522f54dc1a
[ "MIT" ]
null
null
null
/** * @file output_manager.hpp * @author Salvatore Cardamone * @brief Multiprocessing-aware output manager class. */ #ifndef __TYCHEPLUSPLUS_OUTPUT_MANAGER_HPP #define __TYCHEPLUSPLUS_OUTPUT_MANAGER_HPP #include <fstream> #include "multiprocess/multiprocess_base.hpp" namespace tycheplusplus { /** * @class OutputManager * @brief Manage output streams. Encapsulates the streams we can output to and * direct output to the appropriate stream. */ class OutputManager : public MultiProcessBase { public: // Stream types we support with the OutputManager enum StreamTypes { Terminal, File, Null }; // Constructors and Destructors OutputManager(boost::mpi::communicator& comm, std::string& name, StreamTypes stream); ~OutputManager(); /** * @brief Return a reference to the active stream. * @retval Reference to the object's active stream. */ inline std::ostream& Stream() { return active_stream_; } void SwitchStream(const StreamTypes Stream); /** * @brief << operator overload for the OutputManager. Streams a value into the * active stream. Note that we serialise over processes in case * processes share an ostream (i.e. the terminal). * @param manager OutputManager reference. * @param val Value to place on the active stream. * @retval The OutputManager reference. */ template<class T> friend OutputManager& operator<<(OutputManager& manager, const T& val) { // Go through processes one by one and print to the ostream one at a time for (int i_proc=0; i_proc<manager.Size(); ++i_proc) { if (i_proc == manager.Rank()) manager.Stream() << val; manager.Comm().barrier(); } return manager ; } private: // Name of the OutputManager. For multiprocessing, we can then get a unique filename // we can write to if output is directed to the file stream std::string name_; // Note that since std::ostream is not copy-constructible, we can only have a reference // to the terminal stream since it's initialised with std::cout std::ostream& term_stream_; std::ostream null_stream_, active_stream_; std::ofstream file_stream_; }; } /* namespace tycheplusplus */ #endif /* #ifndef __TYCHEPLUSPLUS_OUTPUT_MANAGER_HPP */
29.763158
89
0.712202
savcardamone
f93819ccdcf0c436ddab2aebc30c7168e13181b2
19,996
cpp
C++
generic/stack1d.cpp
cschreib/speclib
efbe7b0c9c28dddd82916c7fff4813bfe7a9ff31
[ "MIT" ]
null
null
null
generic/stack1d.cpp
cschreib/speclib
efbe7b0c9c28dddd82916c7fff4813bfe7a9ff31
[ "MIT" ]
null
null
null
generic/stack1d.cpp
cschreib/speclib
efbe7b0c9c28dddd82916c7fff4813bfe7a9ff31
[ "MIT" ]
null
null
null
#include <phypp.hpp> vec1d cure_error(vec1d err, vec1d err_formal) { vec1u idl = where(err > 0); if (!idl.empty()) { err_formal[idl] *= median(err[idl]/err_formal[idl]); } // Keep the bootstrap unless it is too small for some reason idl = where(err < 0.7*err_formal); err[idl] = err_formal[idl]; return err; } void print_help(); int phypp_main(int argc, char* argv[]) { std::string out; vec1s files; // 1D spectra to stack double rescale = 1.0; // rescaling factor to apply to flux and errors vec1u rebin = {1}; // spectral binnings (1: no binning, x: bin 'x' pixels into one) bool verbose = false; // print progress in the standard output vec1s filters; // filters to use to build broadband fluxes std::string filter_db = data_dir+"fits/filter-db/db.dat"; // Weighting scheme for stacking spectra and spectral binning // "optimal": inverse variance weighting, "uniform": no weighting std::string stack_weight = "optimal"; std::string stack_op = "mean"; bool do_sigma_clip = true; // enable/disable sigma clipping of outliers double sigma_clip_threshold = 5.0; // significance threshold for rejecting outliers uint_t sigma_clip_width = 1; // width (in pixels) of the wavelength bin in which to define outliers bool save_cubes = false; // save the "cube" of 1D spectra prior to stacking them bool help = false; read_args(argc, argv, arg_list( out, files, stack_weight, stack_op, filters, do_sigma_clip, sigma_clip_threshold, sigma_clip_width, save_cubes, rebin, rescale, verbose, filter_db, help )); if (help) { print_help(); return 0; } file::mkdir(file::get_directory(out)); if (stack_weight != "optimal" && stack_weight != "uniform") { error("unknown weighting scheme '", stack_weight, "' for stacking"); return 1; } if (files.empty()) { error("no spectrum to stack (files=...)"); return 1; } vec<1,filter_t> fbb; if (!filters.empty()) { auto db = read_filter_db(filter_db); if (!get_filters(db, filters, fbb)) { return 1; } rebin.push_back(npos); } vec2d cflx, cerr; // Read spectra vec1d lam; vec1s exp_band(files.size()); vec1d exp_seeing(files.size()); vec1d exp_width(files.size()); vec1d exp_offset(files.size()); for (uint_t i : range(files)) { vec1d tflx, terr; fits::input_image iimg(files[i]); iimg.reach_hdu(1); iimg.read(tflx); vec1d tlam = astro::build_axis(astro::wcs(iimg.read_header()), 0, astro::axis_unit::wave_um); if (cflx.empty()) { lam = tlam; } else { if (count(abs(tlam - lam)/mean(lam) > 1e-6) > 0) { error("mismatch in wavelength range, cannot stack"); return 1; } } iimg.read_keyword("BAND", exp_band[i]); iimg.read_keyword("SEEING", exp_seeing[i]); iimg.read_keyword("GWIDTH", exp_width[i]); if (verbose) { note(files[i]); note(" seeing: ", exp_seeing[i], " arcsec", ", width: ", exp_width[i], ", band: ", exp_band[i]); } iimg.read_keyword("GPOS", exp_offset[i]); iimg.reach_hdu(2); iimg.read(terr); if (cflx.empty()) { cflx.resize(tflx.dims, files.size()); cerr.resize(cflx.dims); } tflx *= rescale; terr *= rescale; cflx(_,i) = tflx; cerr(_,i) = terr; } // Define weights vec2d cwei; if (stack_weight == "optimal") { // Inverse variance weighting cwei = 1/sqr(cerr); // Adjust global normalization to avoid numerical errors cwei /= max(cwei[where(is_finite(cwei))]); } else if (stack_weight == "uniform") { cwei = replicate(1.0, cflx.dims); } // Apply sigma clipping (if asked) vec2b crej(cflx.dims); if (do_sigma_clip) { uint_t d1 = (sigma_clip_width-1)/2; uint_t d2 = sigma_clip_width-1 - d1; for (uint_t l : range(cflx.dims[0])) { // Define wavelength region uint_t l0 = (l > d1 ? l - d1 : 0); uint_t l1 = (l < cflx.dims[0]-d2 ? l + d2 : cflx.dims[0]-1); // First compute the weighted median (which we assume is unbiased) vec2d med(l1-l0+1, cflx.dims[1]); for (uint_t ll : range(med.dims[0])) { med(ll,_) = weighted_median(cflx(l0+ll,_), cwei(l0+ll,_)); } // Compute the absolute residuals vec2d res = abs(cflx(l0-_-l1,_) - med); // Compute the RMS of these using the MAD (which we assume is unbiased) double rms = 1.48*median(res); // Select significant outliers in this wavelength element crej(l,_) = res(d1,_) > sigma_clip_threshold*rms; } if (verbose) { uint_t nfinite = count(is_finite(cflx)); uint_t cnt = count(crej); note(cnt, "/", nfinite, " elements sigma clipped (", round(10.0*100.0*cnt/float(nfinite))/10.0, "%)"); } } // Determine information about exposures vec1d exp_fclip(cflx.dims[1]); vec1d exp_wei(cflx.dims[1]); for (uint_t i : range(cflx.dims[1])) { vec1u idl = where(is_finite(cflx(_,i))); exp_fclip[i] = fraction_of(crej(idl,i)); exp_wei[i] = median(cwei(idl,i)); } // Rescale weights for display purposes (max of 1) for (auto b : unique_values(exp_band)) { vec1u idb = where(exp_band == b); exp_wei[idb] /= max(exp_wei[idb]); } // Define function to save this data into the FITS headers auto write_exposures = [&](fits::output_image& oimg) { oimg.write_keyword("NEXP", cflx.dims[1]); for (uint_t i : range(cflx.dims[1])) { std::string base = "E"+align_right(to_string(i), 4, '0'); oimg.write_keyword(base+"SRC", file::get_basename(files[i])); oimg.write_keyword(base+"BND", exp_band[i], "observing band"); oimg.write_keyword(base+"SNG", round(1000*exp_seeing[i])/1000.0, "seeing (arcsec)"); oimg.write_keyword(base+"OFF", round(1000*exp_width[i])/1000.0, "model width (arcsec)"); oimg.write_keyword(base+"OFF", round(1000*exp_offset[i])/1000.0, "slit offset (arcsec)"); oimg.write_keyword(base+"WEI", round(1000*exp_wei[i])/1000.0, "average weight"); oimg.write_keyword(base+"REJ", round(1000*exp_fclip[i])/1000.0, "fraction of rejected pixels"); } }; // Save cubes (if asked) if (save_cubes) { fits::output_image oimg(file::remove_extension(out)+"_cubes.fits"); oimg.write_empty(); auto write_wcs = [&]() { oimg.write_keyword("CTYPE1", "WAVE"); oimg.write_keyword("CUNIT1", "um"); oimg.write_keyword("CRPIX1", 1.0); oimg.write_keyword("CRVAL1", lam[0]); oimg.write_keyword("CDELT1", lam[1]-lam[0]); oimg.write_keyword("CTYPE2", "EPOCH"); oimg.write_keyword("CRPIX2", 1.0); oimg.write_keyword("CRVAL2", 1.0); oimg.write_keyword("CDELT2", 1.0); write_exposures(oimg); }; oimg.reach_hdu(1); oimg.write(transpose(cflx)); write_wcs(); oimg.reach_hdu(2); oimg.write(transpose(cerr)); write_wcs(); oimg.reach_hdu(3); oimg.write(transpose(cwei)); write_wcs(); oimg.reach_hdu(4); oimg.write(transpose(crej)); write_wcs(); } // Down-weight bad pixels { vec1u idb = where(!is_finite(cflx) || !is_finite(cerr) || !is_finite(cwei) || crej); cwei[idb] = 0; cflx[idb] = 0; cerr[idb] = 0; } // Resample the filters to the grid of the spectra for (auto& f : fbb) { uint_t i0 = where_first(lam > f.lam.front()); uint_t i1 = where_last(lam < f.lam.back()); if (i0 != npos && i1 != npos) { f.res = interpolate(f.res, f.lam, lam); f.res[_-i0] = 0; f.res[i1-_] = 0; f.lam = lam; } else { // Filter is not covered f.res.clear(); f.lam.clear(); } } auto stack_elements = [&](const vec2d& fdata, const vec2d& edata, const vec2d& wdata, uint_t l0, uint_t l1, double& flx, double& err, double& errb) { double wei = 0; err = 0; errb = 0; vec1d iflx(fdata.dims[1]); vec1d iwei(fdata.dims[1]); bool noflx = false; if (stack_op == "median") { flx = weighted_median(fdata.safe(l0-_-l1,_), wdata.safe(l0-_-l1,_)); for (uint_t i : range(fdata.dims[1])) { iflx.safe[i] = weighted_median(fdata.safe(l0-_-l1,i), wdata.safe(l0-_-l1,i)); } noflx = true; } else { flx = 0; } for (uint_t l = l0; l <= l1; ++l) for (uint_t i : range(fdata.dims[1])) { wei += wdata.safe(l,i); err += sqr(wdata.safe(l,i)*edata.safe(l,i)); iwei.safe[i] += wdata.safe(l,i); if (!noflx) { flx += wdata.safe(l,i)*fdata.safe(l,i); iflx.safe[i] += wdata.safe(l,i)*fdata.safe(l,i); } } err = sqrt(err)/wei; if (!noflx) { flx /= wei; iflx /= iwei; } // For sample-estimated uncertainty, be sure to compute it on the binned data // rather than on all the data at once wei = 0; uint_t npt = 0; for (uint_t i : range(fdata.dims[1])) { if (iwei.safe[i] > 0) { ++npt; wei += iwei.safe[i]; errb += sqr(iwei.safe[i]*(iflx.safe[i] - flx)); } } errb = sqrt(errb*(npt/(npt-1.0)))/wei; }; auto smooth_spectrum = [&](const vec2d& fcube, const vec2d& ecube, const vec2d& wcube, uint_t bwidth, vec1d& flx, vec1d& err, vec1d& errb) { if (bwidth != npos) { uint_t d1 = (bwidth-1)/2; uint_t d2 = bwidth-1 - d1; for (uint_t l : range(flx)) { uint_t l0 = (l > d1 ? l - d1 : 0); uint_t l1 = (l < flx.size()-d2 ? l + d2 : flx.size()-1); stack_elements(fcube, ecube, wcube, l0, l1, flx[l], err[l], errb[l]); } } else { // Broadband fluxes, use a trick: only set one element of the spectrum to // the flux value, and ignore the rest since we do not want to "smooth" really for (uint_t l : range(fbb)) { if (fbb[l].res.empty()) { flx[l] = dnan; err[l] = dnan; errb[l] = dnan; continue; } vec2d tw = wcube*transpose(replicate(fbb[l].res, wcube.dims[1])); stack_elements(fcube, ecube, tw, 0, wcube.dims[0]-1, flx[l], err[l], errb[l]); } } }; // Define function to write a 1D spectrum to the disk auto write_spectrum = [&](uint_t bwidth, std::string filename, const vec1d& l, const vec1d& flx, const vec1d& err, const vec1d& errb) { fits::output_image oimg(filename); oimg.write_empty(); auto write_wcs = [&]() { oimg.write_keyword("BINNING", bwidth); oimg.write_keyword("CTYPE1", "WAVE"); oimg.write_keyword("CUNIT1", "um"); oimg.write_keyword("CRPIX1", 1.0); oimg.write_keyword("CRVAL1", l[0]); oimg.write_keyword("CDELT1", l[1]-l[0]); write_exposures(oimg); }; oimg.reach_hdu(1); oimg.write(flx); write_wcs(); if (!errb.empty()) { vec1f best_err = cure_error(errb, err); oimg.reach_hdu(2); oimg.write(best_err); write_wcs(); oimg.reach_hdu(3); oimg.write(errb); write_wcs(); } else { oimg.reach_hdu(2); oimg.write(err); write_wcs(); oimg.reach_hdu(3); oimg.write_empty(); } oimg.reach_hdu(4); oimg.write(err); write_wcs(); if (verbose) note("wrote ", filename); }; // Binning, stack, bootstrap and save files for (uint_t bwidth : rebin) { // Smooth with a boxcar of that width and stack vec1d flx(cflx.dims[0]); vec1d err(cflx.dims[0]); vec1d errb(cflx.dims[0]); smooth_spectrum(cflx, cerr, cwei, bwidth, flx, err, errb); std::string ofile = out; if (bwidth != 1) { ofile = file::remove_extension(out)+"_s"+to_string(bwidth)+".fits"; } if (bwidth != npos) { write_spectrum(bwidth, ofile, lam, flx, err, errb); if (bwidth != 1) { // Then bin by picking regularly spaced elements in the smoothed spectrum vec1u idb = bwidth*uindgen(uint_t(ceil(flx.size()/float(bwidth)))) + (bwidth-1)/2; idb = idb[where(idb < flx.size())]; flx = flx[idb]; err = err[idb]; errb = errb[idb]; vec1d tlam = lam[idb]; ofile = file::remove_extension(out)+"_b"+to_string(bwidth)+".fits"; write_spectrum(bwidth, ofile, tlam, flx, err, errb); } } else { // Only keep the two elements we care about vec1u idf = uindgen(fbb.size()); flx = flx[idf]; err = err[idf]; errb = errb[idf]; vec1d tlam; for (auto& f : fbb) { tlam.push_back(f.rlam); } ofile = file::remove_extension(out)+"_broadband.fits"; fits::write_table(ofile, "lambda", tlam, "flux", flx, "flux_err", err, "flux_err_bstrap", errb, "bands", filters ); } } return 0; } void print_help() { using namespace terminal_format; print("stack1d v1.0"); print("usage: stack1d files=[file1.fits,file2.fits,...] out=... [options]"); print(""); print("Main parameters:"); paragraph("The files listed in 'files=[...]' must be valid 1D spectra FITS files, for example " "created by 'extract2d'. It is expected that the fluxes are located in the first HDU, and " "uncertainties in the second HDU. These spectra will be combined into a stacked spectrum, " "with accurate uncertainties determined from the variance between exposures. The 'out=...' " "parameter specifies the file name of the output stacked spectrum."); print(""); print("Output format:"); paragraph("Each output spectrum will contain the stacked flux in the first FITS extension, " "and the best estimate of the uncertainty in the second extension. The third extension " "will contain the bootstrap uncertainty estimate, while the fourth extension will " "contain the formal uncertainty estimate (from standard error propagation)."); paragraph("If the 'filters=[...]' option is set (see below), the program will also create a " "file called '<out>_broadband.fits', which contains the stacked broadband fluxes. This " "file is a FITS binary table (column oriented). It contains the following columns: 'lambda'" "is the central wavelength of the filter, 'flux' is the flux, 'flux_err' is the best " "estimate of the uncertainty, 'flux_err_bstrap' is the bootstrap uncertainty, and 'bands' " "is the code name of the filter."); print(""); print("Options:"); bullet("files=[...]", "Must be a list of files. This is the list of 1D spectra that will be " "stacked."); bullet("out=...", "Must be a string. This sets the name of the file in which to store the " "stacked spectrum. It can include directories, which will be created if they do not exist. " "All other output files will use this file name as a base. For example, setting " "'out=somedir/spectrum.fits' will save all files in the 'somedir' directory, and their " "names will all start with 'spectrum...'."); bullet("rescale=...", "Must be a number. This is a global flux rescaling factor that is " "applied to both fluxes and uncertainties, to account for global transmission issues. " "Default is 1, meaning no rescaling is performed."); bullet("rebin=[...]", "Must be a list of integers. This defines different values of binning " "to apply to the stacked spectrum. Because the uncertainty in binned flux may not scale " "like pure Gaussian noise, the spectra are binned before being stacked, and the " "uncertainties for the binned spectra are computed from the variance in binned fluxes. " "For each value 'X' in this list, the program will create two files: <out>_bX.fits, " "which contains the stacked binned spectrum, and <out>_sX.fits, which contains the " "spectrum smoothed with a boxcar window of width 'X'. A value of one will produce an " "unbinned spectrum (simply saved as <out>.fits). Default is no rebinning."); bullet("filters=[...]", "Must be a list of strings. Each value must be the name of a filter " "form the filter database (see 'filter_db' below). For each filter, the program will " "compute the synthetic broadband flux, with the corresponding uncertainty. If omitted, " "no broadband flux will be computed."); bullet("filter_db=...", "Must be the path to a 'filter.db' file, which contains a list of " "filters. Each filter must be listed on a separate line, with the format '<name>=<path>', " "where 'name' is the code name of the filter (e.g., 'subaru-B' for the Subaru B band), " "and where 'path' is the path to the filter response curve. These response curves must " "be either FITS tables (columns: 'LAM' for the wavelength in microns, and 'RES' for the " "response, normalized to unit integral), or ASCII tables with two columns (wavelength " "and response, with the same units as for the FITS file)."); bullet("stack_weight=...", "Must be either 'optimal' or 'uniform'. This defines the weighting " "used when stacking the 1D spectra. Using 'optimal' weighting will weight spectral data " "by inverse variance, which provides the best S/N. Using 'uniform' weighting will weight " "all data equally. Default is 'optimal'."); bullet("stack_op=...", "Must be either 'mean' or 'median'. This defines the method used for " "stacking the 1D spectra. Default is 'mean'. Both methods make use of the weights " "specified in 'stack_weight'."); bullet("do_sigma_clip", "Set this flag to enable sigma-clipping when stacking the data. " "If enabled, for each spectral element of the final spectrum, the data points that would " "enter the stack are compared to one another, and data points with strong deviations are " "excluded from the stack. Enabled by default."); bullet("sigma_clip_threshold", "Must be a number. When 'do_sigma_clip' is enabled, this sets " "the significance of the deviation required for a spectral element to be excluded. Default " "is 5 sigma."); bullet("sigma_clip_width", "Must be an integer. When 'do_sigma_clip' is enabled, this sets " "the width of the spectral window over which the background level and noise amplitude " "are computed to determine the pixel deviations. Default is 1 element."); }
38.676983
110
0.568864
cschreib
f9396f7de94831c87f31a4b1b87ba5e528433c6f
1,031
cc
C++
src/isa/toy-isa/inst_var.cc
SeanHeelan/superopt
9473e4718d491f6cb375a9754c6213ddf5db680c
[ "MIT" ]
20
2021-06-02T14:21:53.000Z
2022-03-29T09:10:49.000Z
src/isa/toy-isa/inst_var.cc
SeanHeelan/superopt
9473e4718d491f6cb375a9754c6213ddf5db680c
[ "MIT" ]
3
2021-07-28T16:31:25.000Z
2021-07-28T18:36:30.000Z
src/isa/toy-isa/inst_var.cc
SeanHeelan/superopt
9473e4718d491f6cb375a9754c6213ddf5db680c
[ "MIT" ]
2
2021-08-04T09:48:09.000Z
2022-02-08T05:00:33.000Z
#include <random> #include <unordered_set> #include "inst_var.h" using namespace std; default_random_engine gen_toy_isa_inst_var; uniform_real_distribution<double> unidist_toy_isa_inst_var(0.0, 1.0); void update_ps_by_input(prog_state& ps, const inout_t& input) { ps._regs[0] = input.reg; } void update_output_by_ps(inout_t& output, const prog_state& ps) { output.reg = ps._regs[0]; } void get_cmp_lists(vector<int>& val_list1, vector<int>& val_list2, inout_t& output1, inout_t& output2) { val_list1.resize(1); val_list2.resize(1); val_list1[0] = output1.reg; val_list2[0] = output2.reg; } void gen_random_input(vector<inout_t>& inputs, int reg_min, int reg_max) { unordered_set<reg_t> input_set; for (size_t i = 0; i < inputs.size();) { reg_t input = reg_min + (reg_max - reg_min) * unidist_toy_isa_inst_var(gen_toy_isa_inst_var); if (input_set.find(input) == input_set.end()) { input_set.insert(input); inputs[i].reg = input; i++; } } }
27.131579
74
0.685742
SeanHeelan
f93a4711fcc0f6eb3b638328a60626658284d278
2,139
cpp
C++
test/detail/queue.cpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
test/detail/queue.cpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
test/detail/queue.cpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <unet/detail/queue.hpp> namespace unet { namespace detail { TEST(QueueTest, PushPeekAndPop) { Queue q{2}; auto f1 = Frame::makeStr("a"); q.push(f1); ASSERT_FALSE(f1); auto f2 = Frame::makeStr("b"); q.push(f2); ASSERT_FALSE(f2); auto f3 = q.peek(); ASSERT_TRUE(f3); ASSERT_EQ(*f3, "a"); auto f4 = q.pop(); ASSERT_TRUE(f4); ASSERT_EQ(*f4, "a"); auto f5 = q.peek(); ASSERT_TRUE(f5); ASSERT_EQ(*f5, "b"); auto f6 = q.pop(); ASSERT_TRUE(f6); ASSERT_EQ(*f6, "b"); } TEST(QueueTest, PushFull) { Queue q{1}; auto f1 = Frame::makeStr("a"); q.push(f1); ASSERT_FALSE(f1); auto f2 = Frame::makeStr("b"); q.push(f2); ASSERT_TRUE(f2); } TEST(QueueTest, PeekPopEmpty) { Queue q{1}; auto f1 = q.peek(); ASSERT_FALSE(f1); auto f2 = q.pop(); ASSERT_FALSE(f2); } TEST(QueueTest, PopAddsCapacity) { Queue q{1}; auto f1 = Frame::makeStr("a"); q.push(f1); ASSERT_FALSE(f1); auto f2 = q.pop(); ASSERT_TRUE(f2); ASSERT_EQ(*f2, "a"); auto f3 = Frame::makeStr("b"); q.push(f3); ASSERT_FALSE(f3); auto f4 = q.pop(); ASSERT_TRUE(f4); ASSERT_EQ(*f4, "b"); } TEST(QueueTest, HasCapacity) { Queue q{1}; ASSERT_TRUE(q.hasCapacity()); auto f = Frame::makeStr("a"); q.push(f); ASSERT_FALSE(q.hasCapacity()); q.pop(); ASSERT_TRUE(q.hasCapacity()); } TEST(QueueTest, DestroyHuge) { Queue q{100'000}; for (auto count = 0; count < 100'000; count++) { auto f = Frame::makeUninitialized(1); q.push(f); ASSERT_FALSE(f); } } TEST(QueueTest, NonDefaultPolicy) { auto f1 = Frame::makeStr("a"); auto f2 = Frame::makeStr("ab"); auto f3 = Frame::makeStr("abc"); auto p1 = f1.get(); auto p2 = f2.get(); auto p3 = f3.get(); Queue q{4, Queue::Policy::DataLen}; q.push(f1); ASSERT_FALSE(f1); q.push(f2); ASSERT_FALSE(f2); q.push(f3); ASSERT_TRUE(f3); auto f4 = q.pop(); ASSERT_EQ(f4.get(), p1); auto f5 = q.pop(); ASSERT_EQ(f5.get(), p2); q.push(f3); ASSERT_FALSE(f3); auto f6 = q.pop(); ASSERT_EQ(f6.get(), p3); } } // namespace detail } // namespace unet
15.962687
50
0.597008
andreimaximov
f93b45f13226448e0235e846bb8c1a9a6697fd32
69,035
cpp
C++
tests/exchange.test.cpp
VlinderSoftware/securitylayer
0daef0efe08af2649b164affcbdd30845a7806cd
[ "Apache-2.0" ]
1
2020-07-16T01:34:06.000Z
2020-07-16T01:34:06.000Z
tests/exchange.test.cpp
blytkerchan/securitylayer
0daef0efe08af2649b164affcbdd30845a7806cd
[ "Apache-2.0" ]
1
2020-07-23T02:55:31.000Z
2020-07-23T02:55:31.000Z
tests/exchange.test.cpp
blytkerchan/securitylayer
0daef0efe08af2649b164affcbdd30845a7806cd
[ "Apache-2.0" ]
1
2020-07-03T00:06:20.000Z
2020-07-03T00:06:20.000Z
/* Copyright 2019 Ronald Landheer-Cieslak * * 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 "catch.hpp" #include "../outstation.hpp" #include "../master.hpp" #include "deterministicrandomnumbergenerator.hpp" static_assert(DNP3SAV6_PROFILE_HPP_INCLUDED, "profile.hpp should be pre-included in CMakeLists.txt"); using namespace std; using namespace boost::asio; using namespace DNP3SAv6; /* The purpose of this test is to test, in detail, an entire handshake instigated by the Oustation. * We do byte-by-byte comparisons with expected messages here, so we don't have to in subsequent tests. */ SCENARIO( "Outstation sends an initial unsolicited response" "[unsol]") { GIVEN( "An Outstation stack" ) { io_context ioc; Config default_config; Tests::DeterministicRandomNumberGenerator rng; Outstation outstation(ioc, 0/* association ID */, default_config, rng); THEN( "The Outstation will be in the INITIAL state" ) { REQUIRE( outstation.getState() == Outstation::initial__ ); } WHEN( "the Application Layer tries to send an APDU" ) { unsigned char apdu_buffer[2048]; mutable_buffer apdu(apdu_buffer, sizeof(apdu_buffer)); rng.generate(apdu); // NOTE: we really don't care about the contents of the APDU here outstation.postAPDU(apdu); THEN( "The Outstation state will be EXPECT_SESSION_START_REQUEST" ) { REQUIRE( outstation.getState() == Outstation::expect_session_start_request__ ); } THEN( "The Outstation will attempt to send a SessionInitiation message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == (10/*SPDU header size*/) ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { Master master(ioc, 0/* association ID */, default_config, rng); REQUIRE( master.getState() == Master::initial__ ); auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should be in the EXPECT_SESSION_START_RESPONSE state" ) { REQUIRE( master.getState() == Master::expect_session_start_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master should send back a SessionStartRequest" ) { REQUIRE( master.pollSPDU() ); auto spdu(master.getSPDU()); REQUIRE( !master.pollSPDU() ); REQUIRE( spdu.size() == 12 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected_payload_bytes[] = { 0x06, 0x00 }; REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected_payload_bytes, sizeof(expected_payload_bytes)) == 0 ); } //TODO test cases where the Outstation sent its RequestSessionInitation message with sequence numbers // other than 1, according to OPTION_IGNORE_OUTSTATION_SEQ_ON_REQUEST_SESSION_INITIATION WHEN( "The Outstation receives the Master's response" ) { spdu = master.getSPDU(); outstation.postSPDU(spdu); THEN( "The Outstation should go to the EXPECT_SET_KEYS state" ) { REQUIRE( outstation.getState() == Outstation::expect_session_key_change_request__ ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The Outstation should present an SPDU" ) { REQUIRE( outstation.pollSPDU() ); } THEN( "The Outstation should send back a SessionStartResponse" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 15 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected_payload[] = { 0x04 , 0x79, 0x28, 0x11, 0xc8 }; REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected_payload, sizeof(expected_payload)) == 0 ); } WHEN( "The Outstation sends a SessionStartResponse" ) { outstation.getSPDU(); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } WHEN( "The Master receives the SessionStartResponse" ) { auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should go to the EXPECT_SESSION_ACK state" ) { REQUIRE( master.getState() == SecurityLayer::expect_session_key_change_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master will send SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); REQUIRE( spdu.size() == 102 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x04, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected[] = { 0x02, 0x04, 0x58, 0x00 , 0x81, 0x51, 0x97, 0x19, 0xa8, 0x15, 0x74, 0xb7, 0xe0, 0xee, 0xca, 0x85, 0x2f, 0x07, 0x14, 0x50 , 0xa2, 0x75, 0xf1, 0x46, 0xf6, 0xe7, 0x85, 0x5b, 0x86, 0xc5, 0x45, 0x93, 0x84, 0x07, 0xc0, 0x64 , 0xcd, 0x2c, 0xb5, 0xcf, 0xea, 0xc7, 0xbe, 0xa8, 0x72, 0x19, 0xbb, 0x6a, 0x5b, 0xf9, 0xa5, 0xe9 , 0x1c, 0xd5, 0x9c, 0x41, 0x15, 0xe9, 0xa4, 0x17, 0x34, 0x09, 0xe8, 0x84, 0xb9, 0x71, 0x4e, 0x90 , 0x41, 0x3c, 0xbd, 0x16, 0x2b, 0x24, 0xed, 0x0e, 0x11, 0xc8, 0xd3, 0x6d, 0x14, 0x3c, 0x8a, 0xb0 , 0x75, 0x5f, 0x9a, 0x1a, 0x49, 0x6f, 0xc0, 0x10 }; static_assert(sizeof(expected) == 92, "unexpected size for expected response"); REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected, sizeof(expected)) == 0 ); } //TODO check invalid messages (things that should provoke error returns) //TODO check with the wrong sequence number WHEN( "The Outstation receives the SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The outstation should go to the ACTIVE state" ) { REQUIRE( outstation.getState() == Outstation::active__ ); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation will attempt to send a SessionKeyChangeResponse message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 26 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected_payload_bytes[] = { 0xb2, 0x90, 0x5c, 0xdf, 0x5a, 0x71, 0xab, 0x66, 0x09, 0x9f, 0x13, 0x06, 0xeb, 0xcd, 0x96, 0x79 }; REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected_payload_bytes, sizeof(expected_payload_bytes)) == 0 ); } WHEN( "The Outstation to sends a SessionKeyChangeResponse message" ) { auto spdu(outstation.getSPDU()); THEN( "The Outstation has prepared the authenticated-APDU SPDU" ) { outstation.update(); REQUIRE( outstation.pollSPDU() ); // for the pending APDU auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 2048+10/* SPDU header size */+2+16 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x06, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); REQUIRE( spdu_bytes[sizeof(expected_header_bytes) + 0] == 0x00 ); REQUIRE( spdu_bytes[sizeof(expected_header_bytes) + 1] == 0x08 ); REQUIRE( memcmp(apdu.data(), spdu_bytes + (10/*SPDU header size*/) + 2, apdu.size()) == 0 ); unsigned char const expected_payload_bytes[] = { 0xf0, 0xb9, 0x9c, 0xbb, 0x9a, 0x80, 0x86, 0x75, 0x8d, 0x35, 0x2c, 0x27, 0xb5, 0x41, 0x70, 0x9b }; REQUIRE( memcmp(expected_payload_bytes, spdu_bytes + (10/*SPDU header size*/) + 2 + apdu.size(), 16) == 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master should go to the ACTIVE state" ) { REQUIRE( master.getState() == SecurityLayer::active__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 3 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } WHEN( "The Outstation canceled the APDU (timeout)" ) { outstation.onApplicationLayerTimeout(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation canceled the APDU (application reset)" ) { outstation.onApplicationReset(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation canceled the APDU (cancel)" ) { outstation.cancelPendingAPDU(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation does send the APDU" ) { outstation.update(); REQUIRE( outstation.pollSPDU() ); // for the pending APDU auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 4 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 1 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master will have an APDU ready for consumption" ) { REQUIRE( master.pollAPDU() ); } THEN( "The Master can spit out the same APDU we originally sent" ) { auto the_apdu(master.getAPDU()); REQUIRE( the_apdu.size() == apdu.size() ); REQUIRE( memcmp(the_apdu.data(), apdu.data(), apdu.size()) == 0 ); } } } } } } } } //TODO test that a session start request from a broadcast address is ignored //TODO check invalid messages (things that should provoke error returns) } } } } /* We'll only check message headers byte-by-byte here to allow for slightly cleaner code */ SCENARIO( "Master sends an initial poll" "[master-init]") { GIVEN( "A Master that needs to send an APDU" ) { io_context ioc; Config default_config; Tests::DeterministicRandomNumberGenerator rng; Master master(ioc, 0/* association ID */, default_config, rng); REQUIRE( master.getState() == Master::initial__ ); unsigned char apdu_buffer[2048]; mutable_buffer apdu(apdu_buffer, sizeof(apdu_buffer)); rng.generate(apdu); // NOTE: we really don't care about the contents of the APDU here master.postAPDU(apdu); THEN( "The Master go to in the EXPECT_SESSION_START_RESPONSE state" ) { REQUIRE( master.getState() == Master::expect_session_start_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 0 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master should send a SessionStartRequest" ) { REQUIRE( master.pollSPDU() ); auto spdu(master.getSPDU()); REQUIRE( !master.pollSPDU() ); REQUIRE( spdu.size() == 12 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } GIVEN( "A newly booted Outstation" ) { Outstation outstation(ioc, 0/* association ID */, default_config, rng); REQUIRE( outstation.getState() == Outstation::initial__ ); WHEN( "The Outstation receives the Master's request" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The Outstation should go to the EXPECT_SET_KEYS state" ) { REQUIRE( outstation.getState() == Outstation::expect_session_key_change_request__ ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The Outstation should present an SPDU" ) { REQUIRE( outstation.pollSPDU() ); } THEN( "The Outstation should send back a SessionStartResponse" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 15 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } WHEN( "The Outstation sends a SessionStartResponse" ) { outstation.getSPDU(); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } WHEN( "The Master receives the SessionStartResponse" ) { auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should go to the EXPECT_SESSION_ACK state" ) { REQUIRE( master.getState() == SecurityLayer::expect_session_key_change_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master will send SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); REQUIRE( spdu.size() == 102 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x04, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } //TODO check invalid messages (things that should provoke error returns) //TODO check with the wrong sequence number WHEN( "The Outstation receives the SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The outstation should go to the ACTIVE state" ) { REQUIRE( outstation.getState() == Outstation::active__ ); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation will attempt to send a SessionKeyChangeResponse message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 26 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } WHEN( "The Outstation to sends a SessionKeyChangeResponse message" ) { auto spdu(outstation.getSPDU()); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master should go to the ACTIVE state" ) { REQUIRE( master.getState() == SecurityLayer::active__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master is ready to send the APDU" ) { master.update(); REQUIRE( master.pollSPDU() ); } WHEN( "the Master sends the APDU" ) { master.update(); REQUIRE( master.pollSPDU() ); spdu = master.getSPDU(); REQUIRE( !master.pollSPDU() ); THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 1 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "the outstation receives it" ) { outstation.postSPDU(spdu); THEN( "the Outstation will present the APDU" ) { REQUIRE( outstation.pollAPDU() ); auto the_apdu(outstation.getAPDU()); REQUIRE( the_apdu.size() == apdu.size() ); REQUIRE( memcmp(apdu.data(), the_apdu.data(), apdu.size()) == 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } } } } } } } //TODO test that a session start request from a broadcast address is ignored //TODO check invalid messages (things that should provoke error returns) } } } SCENARIO( "Outstation sends an initial unsolicited response, using encryption" "[unsol]") { GIVEN( "An Outstation stack" ) { io_context ioc; Config default_config; default_config.aead_algorithm_ = (decltype(default_config.aead_algorithm_))(AEADAlgorithm::aes256_gcm__); Tests::DeterministicRandomNumberGenerator rng; Outstation outstation(ioc, 0/* association ID */, default_config, rng); THEN( "The Outstation will be in the INITIAL state" ) { REQUIRE( outstation.getState() == Outstation::initial__ ); } WHEN( "the Application Layer tries to send an APDU" ) { unsigned char apdu_buffer[2048]; mutable_buffer apdu(apdu_buffer, sizeof(apdu_buffer)); rng.generate(apdu); // NOTE: we really don't care about the contents of the APDU here outstation.postAPDU(apdu); THEN( "The Outstation state will be EXPECT_SESSION_START_REQUEST" ) { REQUIRE( outstation.getState() == Outstation::expect_session_start_request__ ); } THEN( "The Outstation will attempt to send a SessionInitiation message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 10 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { Master master(ioc, 0/* association ID */, default_config, rng); REQUIRE( master.getState() == Master::initial__ ); auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should be in the EXPECT_SESSION_START_RESPONSE state" ) { REQUIRE( master.getState() == Master::expect_session_start_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master should send back a SessionStartRequest" ) { REQUIRE( master.pollSPDU() ); auto spdu(master.getSPDU()); REQUIRE( !master.pollSPDU() ); REQUIRE( spdu.size() == 12 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected_payload_bytes[] = { 0x06, 0x00 }; REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected_payload_bytes, sizeof(expected_payload_bytes)) == 0 ); } //TODO test cases where the Outstation sent its RequestSessionInitation message with sequence numbers // other than 1, according to OPTION_IGNORE_OUTSTATION_SEQ_ON_REQUEST_SESSION_INITIATION WHEN( "The Outstation receives the Master's response" ) { spdu = master.getSPDU(); outstation.postSPDU(spdu); THEN( "The Outstation should go to the EXPECT_SET_KEYS state" ) { REQUIRE( outstation.getState() == Outstation::expect_session_key_change_request__ ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The Outstation should present an SPDU" ) { REQUIRE( outstation.pollSPDU() ); } THEN( "The Outstation should send back a SessionStartResponse" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 15 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected_payload_bytes[] = { 0x04 , 0x79, 0x28, 0x11, 0xc8 }; REQUIRE( memcmp(spdu_bytes + sizeof(expected_header_bytes), expected_payload_bytes, sizeof(expected_payload_bytes)) == 0 ); } WHEN( "The Outstation sends a SessionStartResponse" ) { outstation.getSPDU(); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } WHEN( "The Master receives the SessionStartResponse" ) { auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should go to the EXPECT_SESSION_ACK state" ) { REQUIRE( master.getState() == SecurityLayer::expect_session_key_change_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master will send SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); REQUIRE( spdu.size() == 102 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x04, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); unsigned char const expected[] = { 0x02, 0x0b, 0x58, 0x00 // we don't check the rest of the payload here }; REQUIRE( memcmp(spdu_bytes + (10/*SPDU header size*/), expected, sizeof(expected)) == 0 ); } //TODO check invalid messages (things that should provoke error returns) //TODO check with the wrong sequence number WHEN( "The Outstation receives the SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The outstation should go to the ACTIVE state" ) { REQUIRE( outstation.getState() == Outstation::active__ ); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation will attempt to send a SessionKeyChangeResponse message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 26 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); // we don't need to check the payload here } WHEN( "The Outstation to sends a SessionKeyChangeResponse message" ) { auto spdu(outstation.getSPDU()); THEN( "The Outstation has prepared the authenticated-APDU SPDU" ) { outstation.update(); REQUIRE( outstation.pollSPDU() ); // for the pending APDU auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 2048+10/* SPDU header size */+2+16 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x06, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); // we only check that the APDU is different here from what was sent REQUIRE( memcmp(apdu.data(), spdu_bytes + sizeof(expected_header_bytes), apdu.size()) != 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master should go to the ACTIVE state" ) { REQUIRE( master.getState() == SecurityLayer::active__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 3 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } WHEN( "The Outstation canceled the APDU (timeout)" ) { outstation.onApplicationLayerTimeout(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation canceled the APDU (application reset)" ) { outstation.onApplicationReset(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation canceled the APDU (cancel)" ) { outstation.cancelPendingAPDU(); THEN( "No SPDU will be pending" ) { REQUIRE( !outstation.pollSPDU() ); } } WHEN( "The Outstation does send the APDU" ) { outstation.update(); REQUIRE( outstation.pollSPDU() ); // for the pending APDU auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 4 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 1 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master will have an APDU ready for consumption" ) { REQUIRE( master.pollAPDU() ); } THEN( "The Master can spit out the same APDU we originally sent" ) { auto the_apdu(master.getAPDU()); REQUIRE( the_apdu.size() == apdu.size() ); REQUIRE( memcmp(the_apdu.data(), apdu.data(), apdu.size()) == 0 ); } } } } } } } } //TODO test that a session start request from a broadcast address is ignored //TODO check invalid messages (things that should provoke error returns) } } } } /* We'll only check message headers byte-by-byte here to allow for slightly cleaner code */ SCENARIO( "Master sends an initial poll, using encryption" "[master-init]") { GIVEN( "A Master that needs to send an APDU" ) { io_context ioc; Config default_config; default_config.aead_algorithm_ = (decltype(default_config.aead_algorithm_))(AEADAlgorithm::aes256_gcm__); Tests::DeterministicRandomNumberGenerator rng; Master master(ioc, 0/* association ID */, default_config, rng); REQUIRE( master.getState() == Master::initial__ ); unsigned char apdu_buffer[2048]; mutable_buffer apdu(apdu_buffer, sizeof(apdu_buffer)); rng.generate(apdu); // NOTE: we really don't care about the contents of the APDU here master.postAPDU(apdu); THEN( "The Master go to in the EXPECT_SESSION_START_RESPONSE state" ) { REQUIRE( master.getState() == Master::expect_session_start_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 0 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master should send a SessionStartRequest" ) { REQUIRE( master.pollSPDU() ); auto spdu(master.getSPDU()); REQUIRE( !master.pollSPDU() ); REQUIRE( spdu.size() == 12 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } GIVEN( "A newly booted Outstation" ) { Outstation outstation(ioc, 0/* association ID */, default_config, rng); REQUIRE( outstation.getState() == Outstation::initial__ ); WHEN( "The Outstation receives the Master's request" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The Outstation should go to the EXPECT_SET_KEYS state" ) { REQUIRE( outstation.getState() == Outstation::expect_session_key_change_request__ ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The Outstation should present an SPDU" ) { REQUIRE( outstation.pollSPDU() ); } THEN( "The Outstation should send back a SessionStartResponse" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 15 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } WHEN( "The Outstation sends a SessionStartResponse" ) { outstation.getSPDU(); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } WHEN( "The Master receives the SessionStartResponse" ) { auto spdu(outstation.getSPDU()); master.postSPDU(spdu); THEN( "The Master should go to the EXPECT_SESSION_ACK state" ) { REQUIRE( master.getState() == SecurityLayer::expect_session_key_change_response__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 1 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master will send SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); REQUIRE( spdu.size() == 102 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x04, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } //TODO check invalid messages (things that should provoke error returns) //TODO check with the wrong sequence number WHEN( "The Outstation receives the SessionKeyChangeRequest message" ) { auto spdu(master.getSPDU()); outstation.postSPDU(spdu); THEN( "The outstation should go to the ACTIVE state" ) { REQUIRE( outstation.getState() == Outstation::active__ ); } THEN( "The Outstation should not present an APDU" ) { REQUIRE( !outstation.pollAPDU() ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Outstation will attempt to send a SessionKeyChangeResponse message" ) { REQUIRE( outstation.pollSPDU() ); auto spdu(outstation.getSPDU()); REQUIRE( !outstation.pollSPDU() ); REQUIRE( spdu.size() == 26 ); unsigned char const *spdu_bytes(static_cast< unsigned char const * >(spdu.data())); unsigned char const expected_header_bytes[] = { 0xc0, 0x80, 0x40, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 }; REQUIRE( memcmp(spdu_bytes, expected_header_bytes, sizeof(expected_header_bytes)) == 0 ); } WHEN( "The Outstation to sends a SessionKeyChangeResponse message" ) { auto spdu(outstation.getSPDU()); THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "The Master receives it" ) { master.postSPDU(spdu); THEN( "The Master should go to the ACTIVE state" ) { REQUIRE( master.getState() == SecurityLayer::active__ ); } THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } THEN( "The Master should not present anything as an APDU" ) { REQUIRE( !master.pollAPDU() ); } THEN( "The Master is ready to send the APDU" ) { master.update(); REQUIRE( master.pollSPDU() ); } WHEN( "the Master sends the APDU" ) { master.update(); REQUIRE( master.pollSPDU() ); spdu = master.getSPDU(); REQUIRE( !master.pollSPDU() ); THEN( "The Master statistics should be OK" ) { REQUIRE( master.getStatistic(Statistics::total_messages_sent__) == 3 ); REQUIRE( master.getStatistic(Statistics::total_messages_received__) == 2 ); REQUIRE( master.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( master.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( master.getStatistic(Statistics::secure_messages_sent_) == 1 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } WHEN( "the outstation receives it" ) { outstation.postSPDU(spdu); THEN( "the Outstation will present the APDU" ) { REQUIRE( outstation.pollAPDU() ); auto the_apdu(outstation.getAPDU()); REQUIRE( the_apdu.size() == apdu.size() ); REQUIRE( memcmp(apdu.data(), the_apdu.data(), apdu.size()) == 0 ); } THEN( "The outstation statistics should be OK" ) { REQUIRE( outstation.getStatistic(Statistics::total_messages_sent__) == 2 ); REQUIRE( outstation.getStatistic(Statistics::total_messages_received__) == 3 ); REQUIRE( outstation.getStatistic(Statistics::discarded_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::error_messages_sent__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::unexpected_messages__) == 0 ); REQUIRE( outstation.getStatistic(Statistics::secure_messages_sent_) == 0 ); static_assert(static_cast< int >(Statistics::statistics_count__) == 6, "New statistic added?"); } } } } } } } } //TODO test that a session start request from a broadcast address is ignored //TODO check invalid messages (things that should provoke error returns) } } }
64.700094
155
0.556964
VlinderSoftware
f93d694d135b74615a2c6078bad826606ab8a22c
1,644
cpp
C++
src/libsnw_lang/parser.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
src/libsnw_lang/parser.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
src/libsnw_lang/parser.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
#include <stdexcept> #include <iostream> #include "object_transaction.h" #include "parser.h" using namespace snw; parser::parser(object_heap& heap) : heap_(heap) { } object_ref parser::parse(const char* str) { try { object_transaction txn(&heap_); snw::parse(str, *this); txn.commit(); return program_; } catch (const std::exception&) { stack_.clear(); throw; } } void parser::open_file() { stack_.push_back(frame{}); } void parser::close_file() { if (stack_.size() != 1) { throw std::runtime_error("unclosed list"); } program_ = pop_list(); } void parser::open_list() { stack_.push_back(frame{}); } void parser::close_list() { if (stack_.size() == 1) { throw std::runtime_error("unopened list"); } object_ref ref = pop_list(); stack_.back().push_back(ref); } void parser::integer(int64_t value) { stack_.back().push_back(heap_.new_integer(value)); } void parser::string(const char* first, const char* last) { stack_.back().push_back(heap_.new_string(first, last)); } void parser::symbol(const char* first, const char* last) { stack_.back().push_back(heap_.new_symbol(first, last)); } void parser::comment(const char* first, const char* last) { (void)first; (void)last; } void parser::error(const snw::lexer_error& err) { throw std::runtime_error(err.msg); } object_ref parser::pop_list() { auto& frame = stack_.back(); auto first = frame.data(); auto last = first + frame.size(); object_ref ref = heap_.new_list(first, last); stack_.pop_back(); return ref; }
20.296296
59
0.631387
Sojourn
f93e75025a86aa917d49e97b3c96905dc7431209
1,653
hpp
C++
include/ampi/detail/msgunpack_ctx_base.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
null
null
null
include/ampi/detail/msgunpack_ctx_base.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
null
null
null
include/ampi/detail/msgunpack_ctx_base.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
1
2021-03-30T15:49:55.000Z
2021-03-30T15:49:55.000Z
// Copyright 2021 Pavel A. Lebedev // Licensed under the Apache License, Version 2.0. // (See accompanying file LICENSE.txt or copy at // http://www.apache.org/licenses/LICENSE-2.0) // SPDX-License-Identifier: Apache-2.0 #ifndef UUID_AAF4E171_A2F9_4892_8578_A9CDFF078116 #define UUID_AAF4E171_A2F9_4892_8578_A9CDFF078116 #include <ampi/detail/msgpack_ctx_base.hpp> #include <ampi/event_sinks/event_sink.hpp> #include <ampi/filters/parser.hpp> namespace ampi { class msgunpack_ctx_base : public msgpack_ctx_base { public: explicit msgunpack_ctx_base(parser_options po = {},segmented_stack_resource ssr = {}) noexcept : msgpack_ctx_base{std::move(ssr)}, po_{po} {} protected: parser_options po_; }; template<typename BufferSource> class msgunpack_ctx_base_with_parser : public msgunpack_ctx_base { public: template<typename BufferSourceFactory> msgunpack_ctx_base_with_parser(BufferSourceFactory bsf, shared_polymorphic_allocator<> spa,parser_options po, segmented_stack_resource ssr) noexcept : msgunpack_ctx_base{po,std::move(ssr)}, bf_{std::move(spa)}, bs_{bsf(bf_)}, p_{bs_,bf_,po,ctx_.ex} {} void set_initial(cbuffer buf) noexcept { p_.set_initial(std::move(buf)); } cbuffer rest() noexcept { return p_.rest(); } protected: pmr_buffer_factory bf_; BufferSource bs_; parser<BufferSource,pmr_buffer_factory,pmr_system_executor> p_; }; } #endif
28.5
102
0.651543
palebedev
f93f8f3365ef6cc472606ea073b993e33880b0c2
387
cpp
C++
level_zero/tools/source/debug/linux/prelim/debug_session_linux_helper.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
level_zero/tools/source/debug/linux/prelim/debug_session_linux_helper.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
level_zero/tools/source/debug/linux/prelim/debug_session_linux_helper.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/tools/source/debug/linux/prelim/debug_session.h" #include <level_zero/ze_api.h> namespace L0 { DebugSession *createDebugSessionHelper(const zet_debug_config_t &config, Device *device, int debugFd) { return new DebugSessionLinux(config, device, debugFd); } } // namespace L0
22.764706
103
0.749354
mattcarter2017
f9479c5354fb09b4084cebc47625f422ec63da41
925
hpp
C++
src/RandomNumberEngine.hpp
Santi-7/Minimum_cut
d0f9f404ab5533d26096163aabe434ad501d8c03
[ "Apache-2.0" ]
null
null
null
src/RandomNumberEngine.hpp
Santi-7/Minimum_cut
d0f9f404ab5533d26096163aabe434ad501d8c03
[ "Apache-2.0" ]
null
null
null
src/RandomNumberEngine.hpp
Santi-7/Minimum_cut
d0f9f404ab5533d26096163aabe434ad501d8c03
[ "Apache-2.0" ]
null
null
null
/** --------------------------------------------------------------------------- ** rng.hpp ** Header file that contains random number generator abstractions. ** ** Author: Miguel Jorge Galindo Ramos, NIA: 679954 ** Santiago Gil Begué, NIA: 683482 ** -------------------------------------------------------------------------*/ #ifndef MINIMUM_CUT_RNG_HPP #define MINIMUM_CUT_RNG_HPP #include <random> /** Suportted random generator engines. */ enum Engine {MERSENNE, CLASSIC_C}; class RandomNumberEngine { public: RandomNumberEngine(Engine selection); /** * @param from Minimum value that can be returned. * @param to Maximum value that can be returned. * @return Random value in the specified range. */ unsigned int GetRandom(unsigned int from, unsigned int to); private: /** Random generator engine selected. */ Engine mEngine; }; #endif // MINIMUM_CUT_RNG_HPP
25
79
0.581622
Santi-7
f95382a4dba726d05d62b0d6799520fa5395f4be
2,675
cpp
C++
cubecode/13种方法/1.sirgedas/SolveCube.cpp
YuYuCong/Color-recognition-of-Rubik-s-Cube
35d5af5383ed56d38e596983aaeda98540fdb646
[ "CC0-1.0" ]
11
2018-07-28T03:20:26.000Z
2022-02-18T07:36:35.000Z
cubecode/13种方法/1.sirgedas/SolveCube.cpp
technicianliu/Color-recognition-of-Rubik-s-Cube
35d5af5383ed56d38e596983aaeda98540fdb646
[ "CC0-1.0" ]
null
null
null
cubecode/13种方法/1.sirgedas/SolveCube.cpp
technicianliu/Color-recognition-of-Rubik-s-Cube
35d5af5383ed56d38e596983aaeda98540fdb646
[ "CC0-1.0" ]
9
2018-07-28T03:20:29.000Z
2021-05-09T05:54:30.000Z
#include <string> #include <iostream> using namespace std; #define SH << #define PP = -1; ++ #define _F ;) #define FOR_i for (int i PP i < __LINE__%21 _F #define FOR_k for (int k PP k < #define _E ); #define _G ;} #define _I [i #define _Q ){ #define FOR_cur_phase ; for (cur_phase PP cur_phase < 4 _F #define _48_ [48] #define Ci12 cubelet _I +12]. #define Ci cubelet _I ]. #define FOR_RET2 ret += ret + #define _IF if ( string data = "2#6'&78)5+1/AT[NJ_PERLQO@IAHPNSMBJCKLRMSDHEJNPOQFKGIQLSNF@DBROPMAGCEMPOACSRQDF"; char inva _48_, b _48_, cur_phase, search_mode, history_idx, history_mov _48_, history_rpt _48_, depth_to_go[5 SH __LINE__], hash_table _48_[6912]; #define PA cubelet[64^data[20+cur_phase*8+i struct Cubelet { char pos, twi _G cubelet _48_; #define PB ]] void rot(char cur_phase _Q _IF cur_phase < 4) FOR_i PA PB.twi = (PA PB.twi + 2 - i%2) % 3, PA +4 PB.twi ^= cur_phase < 2; FOR_i swap(PA +(i!=3) PB, PA PB _E _G int hashf( _Q int ret = 0; switch(cur_phase _Q case 0: FOR_i FOR_RET2 Ci twi; return ret; case 1: #define RRR ; FOR_i FOR_RET2 (Ci pos > FOR_i ret = ret*3 + Ci12 twi RRR 7 _E return ret-7; #define INVABA (inva[b[0 PB ^inva[b[ case 2: FOR_i _IF Ci12 pos<16) inva[Ci12 pos&3] = ret++; else b _I -ret] = Ci12 pos&3 RRR 3 _E FOR_i FOR_RET2 (Ci12 pos > 15 _E return ret*54 + INVABA 1 PB )*2 + (INVABA 2 PB ) > INVABA 3 PB )) - 3587708 _G FOR_i { ret *= 24; int cur_phase FOR_cur_phase FOR_k cur_phase _F _IF cubelet _I *4+cur_phase].pos < cubelet _I *4+k].pos) ret += cur_phase SH cur_phase/3 _G return ret/2 _G #define H0 hash_table[cur_phase ][h%q] #define H1 hash_table[cur_phase+4][h/q] int do_search(int dpt _Q int h = hashf(), q = cur_phase/2*19+8 SH 7; _IF (dpt < H0 | dpt < H1) ^ search_mode _Q _IF search_mode) _IF dpt <= depth_to_go[h]) return !h; else depth_to_go[h] = dpt; H0 <?= dpt; H1 <?= dpt; FOR_k 6 _F FOR_i { rot(k _E _IF k < cur_phase*2 & i != 1 || i > 2) continue; history_mov[history_idx] = k; history_rpt[history_idx++] = i; _IF do_search(dpt-search_mode*2+1)) return 1; history_idx-- _G } return 0 _G int main(int, char** arg _Q memset(hash_table, 6, sizeof(hash_table) _E FOR_i Ci pos = i FOR_cur_phase do_search(0 _E FOR_i { string s = arg _I +1] + string("!" _E Ci pos = data.find(s[0] ^ s[1] ^ s[2] _E int x = min(s.find(85), s.find(68) _E Ci twi = ~x ? x : s[0]>70 _G FOR_i swap(PA +16 PB, PA +21 PB _E search_mode = 1 FOR_cur_phase FOR_i _IF do_search(i)) break; FOR_k history_idx _F cout SH "FBRLUD"[history_mov[k PB SH history_rpt[k]+1 SH " "; return 0 _G
25.970874
147
0.649346
YuYuCong
f95f0bcc0a8dc2f67135c3e6fd067a33a8dfeba8
481
hpp
C++
gearoenix/system/gx-sys-application.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/system/gx-sys-application.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/system/gx-sys-application.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_SYSTEM_APPLICATION_HPP #define GEAROENIX_SYSTEM_APPLICATION_HPP #include "../core/gx-cr-build-configuration.hpp" #ifdef GX_USE_SDL #include "sdl/gx-sys-sdl-app.hpp" #elif defined(GX_USE_GLFW) #include "glfw/gx-sys-glfw.hpp" #elif defined(GX_IN_ANDROID) #include "android/gx-sys-and-app.hpp" #elif defined(GX_USE_WINAPI) #include "win/gx-sys-win-app.hpp" #else #error "Unspecified platform application interface." #endif #endif // GEAROENIX_SYSTEM_APPLICATION_HPP
30.0625
52
0.802495
Hossein-Noroozpour
f95f7d7531ae20112a1135978273565088d6fc87
2,130
cc
C++
mediapipe/calculators/util/gesture_to_render_data_calculator.cc
blackhatdwh/MediaPipe_Gesture
2b4ab4c0ec0452c93c1e9fb8fd49b0fdfcd56385
[ "Apache-2.0" ]
1
2020-02-07T23:49:02.000Z
2020-02-07T23:49:02.000Z
mediapipe/calculators/util/gesture_to_render_data_calculator.cc
blackhatdwh/MediaPipe_Gesture
2b4ab4c0ec0452c93c1e9fb8fd49b0fdfcd56385
[ "Apache-2.0" ]
null
null
null
mediapipe/calculators/util/gesture_to_render_data_calculator.cc
blackhatdwh/MediaPipe_Gesture
2b4ab4c0ec0452c93c1e9fb8fd49b0fdfcd56385
[ "Apache-2.0" ]
2
2020-08-18T03:49:45.000Z
2022-02-08T05:13:05.000Z
#include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/util/color.pb.h" #include "mediapipe/util/render_data.pb.h" namespace mediapipe { namespace { constexpr char kGestureTag[] = "GESTURE"; constexpr char kRenderDataTag[] = "RENDER_DATA"; } class GestureToRenderDataCalculator : public CalculatorBase { public: GestureToRenderDataCalculator() {} ~GestureToRenderDataCalculator() override {} static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; }; REGISTER_CALCULATOR(GestureToRenderDataCalculator); ::mediapipe::Status GestureToRenderDataCalculator::GetContract(CalculatorContract* cc) { cc->Inputs().Tag(kGestureTag).Set<int>(); cc->Outputs().Tag(kRenderDataTag).Set<RenderData>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureToRenderDataCalculator::Open(CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); return ::mediapipe::OkStatus(); } ::mediapipe::Status GestureToRenderDataCalculator::Process(CalculatorContext* cc) { const auto& gesture = cc->Inputs().Tag(kGestureTag).Get<int>(); auto render_data = absl::make_unique<RenderData>(); auto* render_data_annotation = render_data.get()->add_render_annotations(); auto* data = render_data_annotation->mutable_text(); data->set_normalized(true); data->set_display_text(std::to_string(gesture)); data->set_left(0.5); data->set_baseline(0.9); data->set_font_height(0.05); render_data_annotation->set_thickness(2.0); render_data_annotation->mutable_color()->set_r(255); cc->Outputs().Tag(kRenderDataTag).Add(render_data.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } }
38.035714
88
0.749765
blackhatdwh
f9671d17f0abbd8eb21f51c56bc4e58f50fe943b
5,427
cpp
C++
notes_tool_tests.cpp
philtherobot/notes_tool
df22ff8bb3e8930c06ac45f37e9cf8270efd7d05
[ "MIT" ]
null
null
null
notes_tool_tests.cpp
philtherobot/notes_tool
df22ff8bb3e8930c06ac45f37e9cf8270efd7d05
[ "MIT" ]
null
null
null
notes_tool_tests.cpp
philtherobot/notes_tool
df22ff8bb3e8930c06ac45f37e9cf8270efd7d05
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> TEST(parse_filename, simple) { File file(L"./inro desktop The subject.md"); Name fi; ASSERT_TRUE( parse_filename(file, fi) ); ASSERT_TRUE( fi.sphere ); EXPECT_EQ( *fi.sphere, L"#inro" ); ASSERT_TRUE( fi.project ); EXPECT_EQ( *fi.project, L"#desktop" ); ASSERT_TRUE( fi.subject ); EXPECT_EQ( *fi.subject, L"The subject" ); } TEST(parse_filename, accented) { File file(L"./inro desktop Arrêt.md"); Name fi; ASSERT_TRUE( parse_filename(file, fi) ); ASSERT_TRUE( fi.subject ); EXPECT_EQ( *fi.subject, L"Arrêt" ); } TEST(parse_filename, any_character) { File file(L"./+=*\\ d!@#$%^&() ~`|,.<>{}[].md"); Name fi; ASSERT_TRUE( parse_filename(file, fi) ); ASSERT_TRUE( fi.sphere ); EXPECT_EQ( *fi.sphere, L"#+=*\\" ); ASSERT_TRUE( fi.project ); EXPECT_EQ( *fi.project, L"#d!@#$%^&()" ); ASSERT_TRUE( fi.subject ); EXPECT_EQ( *fi.subject, L"~`|,.<>{}[]" ); } TEST(parse_filename, empty_string) { File file; Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, start_with_space) { File file(L"./ inro desktop Arrêt.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, end_with_space) { File file(L"./inro desktop Arrêt .md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_subject) { File file(L"./inro desktop.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_project) { File file(L"./inro.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_basename) { File file(L"./.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, subject_starts_with_space) { File file(L"./inro desktop Two spaces.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, subject_is_space) { File file(L"./inro desktop .md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, two_spaces_between_sphere_and_project) { File file(L"./inro desktop Two spaces.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_tabs) { File file(L"./in\tro desktop OK.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_carriage_return) { File file(L"./in\ro desktop OK.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_filename, no_line_feed) { File file(L"./in\nro desktop OK.md"); Name fi; EXPECT_FALSE( parse_filename(file, fi) ); } TEST(parse_header_field, empty) { wstring name, body; EXPECT_FALSE( parse_header_field( L"", name, body ) ); EXPECT_FALSE( parse_header_field( L"\n", name, body ) ); EXPECT_FALSE( parse_header_field( L" \n", name, body ) ); } TEST(parse_header_field, not_a_field) { wstring name, body; EXPECT_FALSE( parse_header_field( L"# Subject", name, body ) ); EXPECT_FALSE( parse_header_field( L"# Subject\n", name, body ) ); } TEST(parse_header_field, fields) { wstring name, body; ASSERT_TRUE( parse_header_field( L"Sujet: le sujet", name, body ) ); EXPECT_EQ( name, L"Sujet" ); EXPECT_EQ( body, L"le sujet" ); ASSERT_TRUE( parse_header_field( L"Sujet: le sujet\n", name, body ) ); EXPECT_EQ( name, L"Sujet" ); EXPECT_EQ( body, L"le sujet" ); ASSERT_TRUE( parse_header_field( L"Sujet: avec deux : points\n", name, body ) ); EXPECT_EQ( name, L"Sujet" ); EXPECT_EQ( body, L"avec deux : points" ); } TEST( parse_note_text, empty ) { Note n; n.parse_text( L"" ); EXPECT_EQ( n.header.size(), std::size_t{0} ); EXPECT_EQ( n.body, L"\n" ); n.parse_text( L"\n" ); EXPECT_EQ( n.header.size(), std::size_t{0} ); EXPECT_EQ( n.body, L"\n" ); } TEST( parse_note_text, with_fields ) { Note n; n.parse_text( L"Sujet: le sujet\n" L"Etiquettes: #inro #desktop\n" L"\n" L"Le corps\n" L"est ici.\n"); EXPECT_EQ( n.header.size(), std::size_t{2} ); EXPECT_EQ( n.header[L"Sujet"], L"le sujet" ); EXPECT_EQ( n.header[L"Etiquettes"], L"#inro #desktop" ); EXPECT_EQ( n.body, L"Le corps\nest ici.\n" ); } TEST( parse_tags, empty ) { set<wstring> tags; ASSERT_TRUE( parse_tags(L"", tags) ); } TEST( parse_tags, bad ) { set<wstring> tags; ASSERT_FALSE( parse_tags(L"inro", tags) ); ASSERT_FALSE( parse_tags(L"#inro #", tags) ); ASSERT_FALSE( parse_tags(L"#hash#hash", tags) ); } TEST( parse_tags, valid ) { set<wstring> tags; ASSERT_TRUE( parse_tags(L"#inro #desktop", tags) ); EXPECT_EQ( tags.size(), std::size_t{2} ); EXPECT_EQ( tags.count(L"#inro"), std::size_t{1} ); EXPECT_EQ( tags.count(L"#desktop"), std::size_t{1} ); ASSERT_TRUE( parse_tags(L"#inro #spaces", tags) ); EXPECT_EQ( tags.size(), std::size_t{2} ); EXPECT_EQ( tags.count(L"#inro"), std::size_t{1} ); EXPECT_EQ( tags.count(L"#spaces"), std::size_t{1} ); } TEST( is_tag, test ) { ASSERT_TRUE( is_tag(L"#inro") ) ; ASSERT_FALSE( is_tag(L"#") ) ; ASSERT_FALSE( is_tag(L"") ) ; ASSERT_FALSE( is_tag(L"#in#ro") ) ; ASSERT_FALSE( is_tag(L"#in ro") ) ; } int tests(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
22.42562
84
0.624286
philtherobot
f97936c86de4e82372892aa95a871616fe2a4d58
12,066
hpp
C++
Optimization/src/InstanceAnalyser.hpp
AndreaBorghesi/PA-HPC-SIM
2caac39033b38496c714831f0c6f467be596b770
[ "Apache-2.0" ]
null
null
null
Optimization/src/InstanceAnalyser.hpp
AndreaBorghesi/PA-HPC-SIM
2caac39033b38496c714831f0c6f467be596b770
[ "Apache-2.0" ]
null
null
null
Optimization/src/InstanceAnalyser.hpp
AndreaBorghesi/PA-HPC-SIM
2caac39033b38496c714831f0c6f467be596b770
[ "Apache-2.0" ]
null
null
null
#ifndef INSTANCEANALYSER_HPP_ #define INSTANCEANALYSER_HPP_ #include <algorithm> #include <map> #include <iomanip> #include <limits> #include <Optimizer.hpp> #include <FixedStartSchedule.hpp> #include <Rankers.hpp> #include <NodeReader.hpp> #include <JobReader.hpp> #include <JobQueueReader.hpp> #include <Util.hpp> #include "Predictor.hpp" using namespace std; namespace optimization_core { // ============================================================================= // = Instance Analyser class = // ============================================================================= /* This class is used to analyse an instance: compute some interesting * metrics regarding the composition (in terms of job requests) of the instance */ /* Class to analyze the dispatching problem */ class InstanceAnalyser { private: Predictor* predictor_; vector<Job>& jobs_vector_; vector<JobQueue>& queues_; vector<Node>& nodes_; int ndims_; long long ref_time_; /* Minimum duration (s) of jobs considered when computing BSLD. */ double bsld_threshold_ = 60; // data structure to store information about a job typedef struct _job_info { long long job_idx; long long dur; // Job (real) duration long long ewt; // Expected waiting time long long qet; double power_pred; // Predicted Consumed Power double cur_power; // Current consumed power - may vary // requirements for each job unit long long st; long long et; vector< vector<long long > > reqs; // sum of requirements for each dimensions vector<long long> tot_reqs; // nodes mapping vector<int> node_mapping; long long node_type; // type of used nodes (we assume no mixed nodes) int application_type; // 0: average, 1: cpu-intensive, 2: mem-intensive int frequency; long long energy; } job_info_; /* Support function to help sorting job info: job with larger predicted * powers are preferred */ struct job_info_byPower_sorter { inline bool operator() (const _job_info& ji1, const _job_info& ji2) { return (ji1.power_pred > ji2.power_pred); } }; /* Map with the info of all jobs in the problem - useful for compute metrics */ map<long long, job_info_> jobs_; public: void addJob(int job_idx); void analyse(); InstanceAnalyser(vector<Job>& jobs_vector, vector<JobQueue>& qs, vector<Node>& nodes, Predictor* predictor, long long ref_time, int ndims); /* Simple destructor */ virtual ~InstanceAnalyser() {} }; // ============================================================================= // = Method Implementations (InstanceAnalyser) = // ============================================================================= void InstanceAnalyser::addJob(int job_idx){ // Obtain a reference to the job Job& job = jobs_vector_[job_idx]; // structure used only to later compute metrics // - no impact on scheduling decisions _job_info j_info; j_info.job_idx = job_idx; // Obtain the job duration // this is the duration used to compute schedules long long dur = job.getEstimatedDuration(); // Obtain the job predicted power consumption // This power is used to respect the power cap double power_pred; power_pred = predictor_->get_power_prediction(job); /* Some power predictions could be wrong. Extreme small values * (smaller than 1) are extremely suspicious (and can cause later problems): * just in case we set them to 1. In this way we are also being robust * and conservative by overestimating the power consumptions */ if(power_pred < 1) power_pred = 1; j_info.power_pred = power_pred; // initially, the job power is the predicted one double cur_power = power_pred; j_info.cur_power = power_pred; int application_type = jobs_vector_[job_idx].getApplicationType(); j_info.application_type = application_type; /* sanitize strange input: if real duration longer than expected * (this shouldn't happen but it does - probably due to bugs in the * historical trace collecting mechanism), reduce real duration * -> simplify testing */ (job.getEstimatedDuration() < job.getRealDuration() ? j_info.dur = job.getEstimatedDuration() : j_info.dur = job.getRealDuration()); // Obtain the job waiting time long long ewt = 1800; // default value for reservations for (JobQueue& q : queues_){ if (q.getId().compare(job.getQueue()) == 0) { ewt = q.getMaxMinutesToWait(); break; } } j_info.ewt = ewt; // the job frequency is decided only after mapping j_info.frequency = -1; // The time already spent in queue long long qet = job.getEnterQueueTime() - ref_time_; j_info.qet = qet; long long st = job.getStartTime() - ref_time_; long long et = st + dur; j_info.st = st; j_info.et = et; // Add job units one by one int nunits = job.getNumberOfNodes(); vector<vector<long long> > unit_reqs; j_info.reqs.resize(nunits); j_info.tot_reqs.resize(ndims_,0); for (int u = 0; u < nunits; ++u) { j_info.reqs[u].resize(ndims_); // get the requirement of each job unit // (and store them for the internal job_info map) long long rcores = job.getNumberOfCores() / nunits; j_info.reqs[u][0] = rcores; j_info.tot_reqs[0] += rcores; long long rgpus = job.getNumberOfGPU() / nunits; j_info.reqs[u][1] = rgpus; j_info.tot_reqs[1] += rgpus; long long rmics = job.getNumberOfMIC() / nunits; j_info.reqs[u][2] = rmics; j_info.tot_reqs[2] += rmics; long long rmem = job.getMemory() / nunits; j_info.reqs[u][3] = rmem; j_info.tot_reqs[3] += rmem; // store the unit requirements unit_reqs.push_back({rcores, rgpus, rmics, rmem}); } j_info.energy = -1; // store the information about the job in the internal map jobs_[job_idx] = {j_info}; } void InstanceAnalyser::analyse(){ cout << "[InstanceAnalyser] analysis begin" << endl; double totDur = 0; int short_jobs_count = 0; vector<int> totReqs; totReqs.resize(ndims_, 0); double totPower = 0; double avgDur, avgPower; double maxDur = 0; double minDur = std::numeric_limits<double>::max(); vector<double> avgReqs; avgReqs.resize(ndims_, 0); int res_count = 0; int longpar_count = 0; int debug_count = 0; int par_count = 0; int plain_appType_count = 0; int mem_appType_count = 0; int cpu_appType_count = 0; int tot_unitsPerJob = 0; double avg_unitsPerJob = 0; long long max_end_time = 0; long long max_qet = 0; int max_jobs_same_eqt_count = 0; for(auto ji : jobs_){ int jobs_same_eqt_count = 0; totDur += ji.second.dur; if(ji.second.dur < 60) ++short_jobs_count; if(ji.second.dur > maxDur) maxDur = ji.second.dur; if(ji.second.dur < minDur) minDur = ji.second.dur; totPower += ji.second.power_pred; for(int k = 0; k < ndims_; ++k) totReqs[k] += ji.second.tot_reqs[k]; if(ji.second.et > max_end_time) max_end_time = ji.second.et; if(ji.second.qet > max_qet) max_qet = ji.second.qet; tot_unitsPerJob += ji.second.reqs.size(); switch(ji.second.ewt){ case 1800: ++res_count; break; case 3600: ++debug_count; break; case 21600: ++par_count; break; case 86400: ++longpar_count; break; } switch(ji.second.application_type){ case 0: ++plain_appType_count; break; case 1: ++cpu_appType_count; break; case 2: ++mem_appType_count; break; } for(auto oj : jobs_) if(oj.first != ji.first) if(oj.second.qet == ji.second.qet) ++jobs_same_eqt_count; if(max_jobs_same_eqt_count < jobs_same_eqt_count) max_jobs_same_eqt_count = jobs_same_eqt_count; } avgDur = totDur / (double) jobs_.size(); avgPower = totPower / (double) jobs_.size(); for(int k = 0; k < ndims_; ++k) avgReqs[k] = totReqs[k] / (double) jobs_.size(); avg_unitsPerJob = tot_unitsPerJob / (double) jobs_.size(); double stdDur = 0; double stdPower = 0; double stdUnitsPerJob = 0; vector<double> stdReqs; stdReqs.resize(ndims_, 0); for(auto ji : jobs_){ stdDur += (ji.second.dur - avgDur)*(ji.second.dur - avgDur); stdPower += (ji.second.power_pred - avgPower) *(ji.second.power_pred - avgPower); for(int k = 0; k < ndims_; ++k) stdReqs[k] += (ji.second.tot_reqs[k] - avgReqs[k])* (ji.second.tot_reqs[k] - avgReqs[k]); stdUnitsPerJob += (ji.second.reqs.size() - avg_unitsPerJob) * (ji.second.reqs.size() - avg_unitsPerJob); } stdDur /= (double) jobs_.size(); stdPower /= (double) jobs_.size(); stdUnitsPerJob /= (double) jobs_.size(); for(int k = 0; k < ndims_; ++k) stdReqs[k] /= (double) jobs_.size(); stdDur = sqrt(stdDur); stdPower = sqrt(stdPower); stdUnitsPerJob = sqrt(stdUnitsPerJob); for(int k = 0; k < ndims_; ++k) stdReqs[k] = sqrt(stdReqs[k]); //long long time_window = max_qet - ref_time_; long long time_window = max_qet; double job_arrival_freq = time_window / (double) jobs_.size(); cout << std::fixed; cout << std::setprecision(2); cout << "[InstanceAnalyser] # Jobs: " << jobs_.size() << "; time window: " << time_window << "; job arrival frequency: " << job_arrival_freq << "; max. # of jobs with same QET (" << "Queue Enter Time, i.e. arrival time): " << max_jobs_same_eqt_count << endl; cout << "[InstanceAnalyser] Avg. Duration: " << avgDur << "; # short jobs: " << short_jobs_count << "; short jobs %: " << short_jobs_count / (double) jobs_.size() * 100 << "; avg. power: " << avgPower << endl; cout << "[InstanceAnalyser] Avg. Reqs: "; for(int k = 0; k < ndims_; ++k) cout << avgReqs[k] << ", "; cout << "; avg. units per job: " << avg_unitsPerJob << endl; cout << "[InstanceAnalyser] Standard Deviation of Durations: " << stdDur << "; std. power: " << stdPower << endl; cout << "[InstanceAnalyser] Standard Deviation of Reqs: "; for(int k = 0; k < ndims_; ++k) cout << stdReqs[k] << ", "; cout << "; std. units per job: " << stdUnitsPerJob << endl; cout << "[InstanceAnalyser] Avg. app. type %: " << plain_appType_count / (double) jobs_.size() * 100; cout << "; cpu app. type %: " << cpu_appType_count / (double) jobs_.size() * 100; cout << "; mem app. type %: " << mem_appType_count / (double) jobs_.size() * 100; cout << endl; cout << "[InstanceAnalyser] Reservation %: " << res_count / (double) jobs_.size() * 100; cout << "; debug %: " << debug_count / (double) jobs_.size() * 100; cout << "; par %: " << par_count / (double) jobs_.size() * 100; cout << "; longpar %: " << longpar_count / (double) jobs_.size() * 100; cout << endl; } InstanceAnalyser::InstanceAnalyser(vector<Job>& jobs_vector, vector<JobQueue>& qs, vector<Node>& nodes, Predictor* predictor, long long ref_time, int ndims) : jobs_vector_(jobs_vector), queues_(qs), nodes_(nodes), predictor_(predictor), ref_time_(ref_time), ndims_(ndims){ for(int i = 0; i < jobs_vector.size(); ++i) addJob(i); } } // end of optimization_core namespace #endif
30.938462
82
0.588679
AndreaBorghesi
f97a4569577173e7e43007a7d80c5960a6878b6a
15,224
cpp
C++
src/methods/Octane.cpp
anassmeskini/GPH
c3ded30f5cd780a86e8c92d9db6ea89764fcc499
[ "MIT" ]
4
2020-10-30T14:57:41.000Z
2021-07-14T09:00:53.000Z
src/methods/Octane.cpp
anassmeskini/GPH
c3ded30f5cd780a86e8c92d9db6ea89764fcc499
[ "MIT" ]
2
2021-03-23T02:49:31.000Z
2021-10-09T02:59:09.000Z
src/methods/Octane.cpp
anassmeskini/GPH
c3ded30f5cd780a86e8c92d9db6ea89764fcc499
[ "MIT" ]
1
2020-10-30T14:58:05.000Z
2020-10-30T14:58:05.000Z
#include "Octane.h" #include "core/Common.h" #include "core/Numerics.h" #include "io/Message.h" void Octane::search(const MIP& mip, const std::vector<double>& lb, const std::vector<double>& ub, const std::vector<Activity>&, const LPResult& result, const std::vector<double>&, const std::vector<int>&, std::shared_ptr<const LPSolver>, TimeLimit, SolutionPool& pool) { int ncols = mip.getNCols(); const auto& objective = mip.getObj(); if (mip.getStats().nbin < mip.getNCols()) return; // get the active columns in Octane std::vector<int> active_columns; std::vector<int> fixed_columns; if (use_frac_subspace) { Message::debug_details("Octane: using fractional space"); for (int col = 0; col < ncols; ++col) { if (Num::isFeasInt(result.primalSol[col])) fixed_columns.push_back(col); else active_columns.push_back(col); } } else { Message::debug_details("Octane: using the entire space"); for (int col = 0; col < ncols; ++col) { if (!Num::isFeasEQ(lb[col], ub[col])) active_columns.push_back(col); else fixed_columns.push_back(col); } } Message::debug_details("Octane: active cols: {}, fixed cols: {}", active_columns.size(), fixed_columns.size()); assert(static_cast<int>(fixed_columns.size() + active_columns.size()) == ncols); if (std::all_of(std::begin(active_columns), std::end(active_columns), [&objective](int col) -> bool { return objective[col] == 0.0; })) { Message::debug("Octane: Active ray = zero"); return; } // the origin is the shifted optimal lp vertex std::vector<double> origin(active_columns.size()); for (size_t i = 0; i < active_columns.size(); ++i) { int col = active_columns[i]; origin[i] = result.primalSol[col] - 0.5; } // create the shooting ray Ray raytype = Ray::OBJECTIVE; std::vector<double> ray = makeRay(raytype, active_columns, mip, result); // scale the ray if (scale_ray) { double orig_norm = 0.5 * std::sqrt(static_cast<double>(origin.size())); double ray_norm = 0.0; for (double val : ray) ray_norm += val * val; ray_norm = std::sqrt(ray_norm); for (double& val : ray) val = orig_norm / ray_norm * val; Message::debug_details("Octane: origin norm: {}, ray norm {}", orig_norm, ray_norm); } // what columns had changed signs to make // the ray nonnegative std::vector<int> flipped_signs; // flip signs and compute column ratios std::vector<double> column_ratios(active_columns.size()); for (size_t i = 0; i < active_columns.size(); ++i) { if (ray[i] < 0) { ray[i] *= -1.0; origin[i] *= -1.0; flipped_signs.push_back(i); } if (Num::isFeasEQ(ray[i], 0.0)) { if (origin[i] > 0) column_ratios[i] = -Num::infval; else column_ratios[i] = Num::infval; } else column_ratios[i] = -origin[i] / ray[i]; } Message::debug_details("Octane: flipped signs for {} cols", flipped_signs.size()); // columns are permuted to have a nonincreasing order of column_ratios // (v_i) std::vector<int> active_cols_perm(active_columns.size()); std::generate(std::begin(active_cols_perm), std::end(active_cols_perm), [](){ static int i = 0; return i++; }); std::sort(std::begin(active_cols_perm), std::end(active_cols_perm), [&column_ratios](int left, int right) { return column_ratios[left] > column_ratios[right]; }); // permute the column ratios { std::vector<double> buffer(column_ratios.size()); for (size_t i = 0; i < column_ratios.size(); ++i) { buffer[i] = column_ratios[active_cols_perm[i]]; } column_ratios = std::move(buffer); assert(std::is_sorted(std::rbegin(column_ratios), std::rend(column_ratios))); } // permute the origin { std::vector<double> buffer(column_ratios.size()); for (size_t i = 0; i < column_ratios.size(); ++i) { buffer[i] = origin[active_cols_perm[i]]; } origin = std::move(buffer); } // permute the ray { std::vector<double> buffer(column_ratios.size()); for (size_t i = 0; i < column_ratios.size(); ++i) { buffer[i] = ray[active_cols_perm[i]]; } ray = std::move(buffer); } assert(std::all_of(std::begin(ray), std::end(ray), [](double v) { return v >= 0; })); assert(std::all_of(std::begin(origin), std::end(origin), [](double v) { return v >= -0.5 && v <= 0.5; })); auto firstFacet = getFirstFacet(origin, ray, column_ratios); if (Num::isFeasEQ(firstFacet.lambda_denom, 0.0)) { Message::debug("Octane: lambda denom numerically = 0"); return; } // get the k closest facets auto k_closest_facets = getKFacets(std::move(firstFacet), origin, ray, column_ratios); #ifndef NDEBUG // check that we did not generate the same facets twice auto equal = [](const Bitset& l, const Bitset& r) -> bool { assert(l.size() == r.size()); for (size_t k = 0; k < l.size(); ++k) { if (l[k] != r[k]) return false; } return true; }; for (size_t i = 0; i < k_closest_facets.size(); ++i) { for (size_t j = i + 1; j < k_closest_facets.size(); ++j) if (equal(k_closest_facets[i].facet, k_closest_facets[j].facet)) { Message::debug_details("Octane: two similar facets {} and {}", i, j); } } #endif Message::debug_details("Octane: generated {} facets", k_closest_facets.size()); // check feasibility of the solutions corresponding to the facets for (auto& [facet, ln, ld, id] : k_closest_facets) { #ifndef NDEBUG std::vector<double> solution(ncols); #else std::vector<double> solution(ncols, Num::infval); #endif double cost = 0.0; // get the solution in the original search space std::vector<double> partial_solution = getSolFromFacet(facet, flipped_signs, active_cols_perm); assert(partial_solution.size() == active_columns.size()); // set the active columns for (size_t i = 0; i < active_columns.size(); ++i) { int col = active_columns[i]; solution[col] = partial_solution[i]; cost += solution[col] * objective[col]; } // set the fixed columns for (size_t i = 0; i < fixed_columns.size(); ++i) { int col = fixed_columns[i]; solution[col] = result.primalSol[col]; cost += solution[col] * objective[col]; } assert(std::all_of( std::begin(solution), std::end(solution), [](double val) { return val != Num::infval && Num::isIntegral(val); })); static auto lpFeas = checkFeasibility<double, true>; if (lpFeas(mip, solution, 1e-6, 1e-6)) { Message::debug_details("Octane: found a feasible solution"); pool.add(std::move(solution), cost); } } } Octane::FacetInfo Octane::getFirstFacet(const std::vector<double>& origin, const std::vector<double>& ray, const std::vector<double>& column_ratios) { int space_size = origin.size(); assert(ray.size() == origin.size()); assert(std::all_of(std::begin(ray), std::end(ray), [](double val) { return val >= 0.0; })); assert(std::is_sorted(std::rbegin(column_ratios), std::rend(column_ratios))); double lambda_num = 0.5 * space_size; double lambda_denom = 0.0; // we start from the [1, 1, ... 1, 1] facet Bitset facet; for (int i = 0; i < space_size; ++i) { facet.push_back(true); lambda_num += -origin[i]; lambda_denom += ray[i]; } assert(lambda_num >= 0); assert(lambda_denom > 0); for (int i = 0; i < space_size; ++i) { if (column_ratios[i] * lambda_denom > lambda_num) { assert(facet[i]); facet[i] = 0; lambda_num += 2.0 * origin[i]; lambda_denom += -2.0 * ray[i]; assert(lambda_num >= 0); assert(lambda_denom > 0); } else break; } Message::debug_details("Octane: First facet: lambda {}", lambda_num / lambda_denom); int min_plus_index = -1; for (int i = 0; i < space_size; ++i) { if (facet[i]) { min_plus_index = i; break; } } assert(min_plus_index >= 0); return {std::move(facet), lambda_num, lambda_denom, min_plus_index}; } std::vector<Octane::FacetInfo> Octane::getKFacets(FacetInfo&& firstFacet, const std::vector<double>& origin, const std::vector<double>& ray, const std::vector<double>& column_ratios) { assert(ray.size() == origin.size()); assert(std::all_of(std::begin(ray), std::end(ray), [](double val) { return val >= 0.0; })); auto insert = [](std::vector<FacetInfo>& unscanned, FacetInfo&& facet) { double facet_lambda = facet.lambda_num / facet.lambda_denom; int i = 0; while (i < static_cast<int>(unscanned.size()) && unscanned[i].lambda_num < facet_lambda * unscanned[i].lambda_denom) { ++i; } unscanned.resize(unscanned.size() + 1); int size = static_cast<int>(unscanned.size()); for (int j = size - 2; j >= i; --j) { assert(j + 1 < static_cast<int>(unscanned.size())); assert(j >= 0); assert(j >= i); unscanned[j + 1] = std::move(unscanned[j]); } unscanned[i] = std::move(facet); }; auto pop_front = [](std::vector<FacetInfo>& unscanned) { auto tmp = std::move(unscanned[0]); int size = unscanned.size(); for (int i = 0; i < size - 1; ++i) unscanned[i] = std::move(unscanned[i + 1]); assert(!unscanned.empty()); unscanned.resize(unscanned.size() - 1); return tmp; }; // array of unscanned facets std::vector<FacetInfo> unscanned_facets = {firstFacet}; std::vector<FacetInfo> scanned_facets; unscanned_facets.reserve(5 * fmax); scanned_facets.reserve(fmax); Message::debug_details("Octane: generating neighbor facets"); int count = 0; do { assert(!unscanned_facets.empty()); auto min_lambda_facet = pop_front(unscanned_facets); assert(!min_lambda_facet.facet.empty()); auto neighbors = getReverseF(min_lambda_facet, origin, ray, column_ratios); Message::debug_details("Octane: current lambda {} node degree {}", min_lambda_facet.lambda_num / min_lambda_facet.lambda_denom, neighbors.size()); for (auto& facet : neighbors) insert(unscanned_facets, std::move(facet)); scanned_facets.emplace_back(std::move(min_lambda_facet)); if (unscanned_facets.size() >= candidate_max) { Message::debug_details( "Octane: max number of unscanned candidates reached"); size_t i = 0; while (scanned_facets.size() < fmax && i < unscanned_facets.size()) { scanned_facets.emplace_back(std::move(unscanned_facets[i++])); } break; } } while (++count < fmax && !unscanned_facets.empty()); return scanned_facets; } std::vector<Octane::FacetInfo> Octane::getReverseF(const FacetInfo& facetInfo, const std::vector<double>& origin, const std::vector<double>& ray, const std::vector<double>& column_ratios) { int space_size = origin.size(); assert(ray.size() == origin.size()); std::vector<FacetInfo> reverseF; auto& [facet, lambda_num, lambda_denom, min_plus_index] = facetInfo; double lambda = lambda_num / lambda_denom; #ifndef NDEBUG int min_plus_dbg = -1; for (int i = 0; i < space_size; ++i) { if (facet[i]) { min_plus_dbg = i; break; } } assert(min_plus_dbg >= 0); assert(min_plus_dbg == min_plus_index); #endif assert(facet.size() == origin.size()); int i = 0; while (i < space_size && static_cast<bool>(!facet[i]) && column_ratios[i] > lambda) { double new_num = lambda_num - 2.0 * origin[i]; double new_denom = lambda_denom + 2.0 * ray[i]; assert(new_num / new_denom >= lambda); reverseF.emplace_back(facet, new_num, new_denom, i); reverseF.back().facet[i] = 1; ++i; } i = space_size - 1; double ratio_min_plus = -origin[min_plus_index] / ray[min_plus_index]; while (i >= 0 && facet[i] && column_ratios[i] <= lambda) { double new_num = lambda_num + 2.0 * origin[i]; double new_denom = lambda_denom - 2.0 * ray[i]; double new_lambda = new_num / new_denom; if (new_denom > 0 && ratio_min_plus <= new_lambda) { assert(new_num / new_denom >= lambda); int new_min_plus = min_plus_index + (i == min_plus_index); reverseF.emplace_back(facet, new_num, new_denom, new_min_plus); reverseF.back().facet[i] = 0; assert(min_plus_index < space_size && min_plus_index >= 0); } --i; } return reverseF; } // the changes made to the original space: // 1- restrict the search space to a subset of columns // 2- flip signs of negative ray components // 3- permute the columns for nonincreasing columns ratios std::vector<double> Octane::getSolFromFacet(const Bitset& facet, const std::vector<int>& flipped_signs, const std::vector<int>& permutation) { int space_size = facet.size(); std::vector<double> sol(space_size); std::vector<double> buffer(space_size); assert(static_cast<size_t>(space_size) == permutation.size()); for (int i = 0; i < space_size; ++i) sol[i] = static_cast<double>(facet[i]); // undo the permutation for (int i = 0; i < space_size; ++i) buffer[permutation[i]] = sol[i]; sol = std::move(buffer); // undo the flipped signs for (int col : flipped_signs) sol[col] = 1.0 - sol[col]; return sol; } std::vector<double> Octane::makeRay(Ray raytype, const std::vector<int>& columns, const MIP& mip, const LPResult&) { int space_size = columns.size(); std::vector<double> ray(space_size); if (raytype == Ray::OBJECTIVE) { const auto& objective = mip.getObj(); for (int i = 0; i < space_size; ++i) ray[i] = -objective[columns[i]]; } else { assert(0); return {}; } return ray; }
28.140481
80
0.567459
anassmeskini
f97ffba7dc2f3c27c0d869a4bc00443d1046018e
559
cpp
C++
src/sample.cpp
NweZinOo/cnf
6f5774486d8751bf7885d03882a1e39881f041b0
[ "BSD-3-Clause" ]
null
null
null
src/sample.cpp
NweZinOo/cnf
6f5774486d8751bf7885d03882a1e39881f041b0
[ "BSD-3-Clause" ]
null
null
null
src/sample.cpp
NweZinOo/cnf
6f5774486d8751bf7885d03882a1e39881f041b0
[ "BSD-3-Clause" ]
1
2016-05-26T21:28:14.000Z
2016-05-26T21:28:14.000Z
# include <learner.hpp> # include <tagger.hpp> using namespace Cnf; using namespace SemiCnf; int main(int argc, char **argv) { Learner<Cnflearn> learner(*(argv+1), // template *(argv+2), // corpus 1000000); // poolsize learner.init(); learner.learn(50,1); // iter=50, L2-regularization learner.save(*(argv+3)); // save model parameter Tagger<Cnftagger> tagger(*(argv+1), // template 1000000); // poolsize tagger.read(*(argv+3)); // read model parameter tagger.tagging(*(argv+2)); // tagging return 0; }
23.291667
53
0.626118
NweZinOo
f9865d0acceb496fc510592fabad057f222bff5b
83
hpp
C++
mod/meta/type/adam.hpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/meta/type/adam.hpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/meta/type/adam.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#pragma once #include "../common.hpp" namespace wrd { class _wout adam {}; }
10.375
24
0.626506
kniz
f986cce029dcbbdc56a5717345d6ac186a500717
2,928
cpp
C++
src/cimple/ref/DZT_String.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/disp/DZT_String.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/disp/DZT_String.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** 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 "DZT_String.h" CIMPLE_NAMESPACE_BEGIN DZT_String::DZT_String(const DZT_String& x) { _assign(x); } void DZT_String::reserve(size_t n) { if (n > _capacity) { _str = (char*)realloc(_str, n + 2); _capacity = n; } } void DZT_String::assign(const DZT_String& x) { if (&x != this) { clear(); _assign(x); } } void DZT_String::_assign(const DZT_String& x) { if (x._size) { _size = x._size; _capacity = x._size; _str = (char*)malloc(_capacity + 2); memcpy(_str, x._str, _size); _str[_size] = '\0'; _str[_size + 1] = '\0'; } else { _str = 0; _size = 0; _capacity = 0; } } char* DZT_String::steal() { char* tmp = _str; _str = 0; _size = 0; _capacity = 0; return tmp; } void DZT_String::append(const char* s, size_t n) { #ifdef CIMPLE_DEBUG for (size_t i = 0; i < n; i++) CIMPLE_ASSERT(s[i] != '\0'); #endif /* CIMPLE_DEBUG */ if (_size) { size_t new_size = _size + 1 + n; if (new_size > _capacity) reserve(new_size); memcpy(_str + 1 + _size, s, n); _size = new_size; } else { if (n > _capacity) reserve(n); memcpy(_str, s, n); _size = n; } _str[_size] = '\0'; _str[_size + 1] = '\0'; } void dzt_next(const char*& str) { char* p = strchr(str, '\0'); CIMPLE_ASSERT(p != 0 && *p == '\0'); p++; if (*p == '\0') str = 0; else str = p; } CIMPLE_NAMESPACE_END
22.875
80
0.567623
LegalizeAdulthood
f987731e7645cd3c702cd80e27c6f2fb95e5bcd9
733
hpp
C++
src/tcc/tcc/parser/skipper.hpp
tobiashienzsch/tcc
0311a92804fb32baca8b562bb18683e40f4686e2
[ "MIT" ]
null
null
null
src/tcc/tcc/parser/skipper.hpp
tobiashienzsch/tcc
0311a92804fb32baca8b562bb18683e40f4686e2
[ "MIT" ]
null
null
null
src/tcc/tcc/parser/skipper.hpp
tobiashienzsch/tcc
0311a92804fb32baca8b562bb18683e40f4686e2
[ "MIT" ]
null
null
null
#if !defined(TCC_PARSER_QI_SKIPPER_HPP) #define TCC_PARSER_QI_SKIPPER_HPP #include <boost/spirit/include/qi.hpp> namespace tcc { namespace parser { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; /** * The skipper grammar */ template<typename Iterator> struct Skipper : qi::grammar<Iterator> { Skipper() : Skipper::base_type(start) { qi::char_type char_; ascii::space_type space; // clang-format off start = space | "/*" >> *(char_ - "*/") >> "*/" ; // clang-format on } qi::rule<Iterator> start; }; } // namespace parser } // namespace tcc #endif
18.794872
48
0.55116
tobiashienzsch
f98e447df57fd3769427e564a046449743caf1f5
646
cpp
C++
source/main.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
3
2018-12-14T17:36:21.000Z
2020-11-06T19:29:49.000Z
source/main.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
null
null
null
source/main.cpp
amanb014/NxReader
f7c74b78e3c676cab29da78079d4c2d12c9065a1
[ "MIT" ]
null
null
null
#include <switch.h> #include <SDL2/SDL.h> #include "main.hpp" #include "App.hpp" #include <string.h> #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/errno.h> #include <unistd.h> #include <switch.h> int main() { consoleInit(NULL); // TODO remove in final releases socketInitializeDefault(); nxlinkStdio(); printf("starting application...\n"); App* app = new App(); app->start(); while (app->isRunning && appletMainLoop()) { app->update(); } printf("stopping application...\n"); delete app; consoleExit(NULL); // TODO remove in final release socketExit(); SDL_Quit(); return EXIT_SUCCESS; }
17
52
0.676471
amanb014
f98e8141cdc07d3fc590b592332c8c55cb1fbc7e
507
cpp
C++
showcase/source/Renderer/Shader.cpp
ravi688/VulkanRenderer
2e4d15cd53a7fef49fc2e6fe27643746ca1245da
[ "MIT" ]
null
null
null
showcase/source/Renderer/Shader.cpp
ravi688/VulkanRenderer
2e4d15cd53a7fef49fc2e6fe27643746ca1245da
[ "MIT" ]
3
2022-01-28T23:19:13.000Z
2022-02-02T07:51:30.000Z
showcase/source/Renderer/Shader.cpp
ravi688/VulkanRenderer
2e4d15cd53a7fef49fc2e6fe27643746ca1245da
[ "MIT" ]
null
null
null
#include <Renderer/Shader.hpp> #include <Renderer/Renderer.hpp> namespace V3D { SHOWCASE_API Shader::Shader(Renderer& renderer, const std::string& filePath) { handle = shader_load(renderer.handle, filePath.c_str()); } SHOWCASE_API void Shader::destroy() const { shader_destroy(handle); } SHOWCASE_API void Shader::releaseResources() const { shader_release_resources(handle); } SHOWCASE_API void Shader::drop() const { shader_destroy(handle); shader_release_resources(handle); } }
18.107143
77
0.741617
ravi688
f98f057143f80a2437962b317892546cad68c7c6
4,438
inl
C++
legion/engine/core/containers/shared_data_view.inl
Legion-Engine/Legion-Engine
a2b898e1cc763b82953c6990dde0b379491a30d0
[ "MIT" ]
258
2020-10-22T07:09:57.000Z
2021-09-09T05:47:09.000Z
legion/engine/core/containers/shared_data_view.inl
LeonBrands/Legion-Engine
40aa1f4a8c59eb0824de1cdda8e17d8dba7bed7c
[ "MIT" ]
51
2020-11-17T13:02:10.000Z
2021-09-07T18:19:39.000Z
legion/engine/core/containers/shared_data_view.inl
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
13
2020-12-08T08:06:48.000Z
2021-09-09T05:47:19.000Z
#include <core/containers/shared_data_view.hpp> #pragma once namespace legion::core { template<typename DataType> inline L_ALWAYS_INLINE shared_data_view<DataType>::shared_data_view(std::nullptr_t) noexcept : shared_data_view(nullptr, 0, 0, false) {} template<typename DataType> inline shared_data_view<DataType>::shared_data_view(ptr_type ptr, size_type size, diff_type offset) noexcept : m_data(ptr), m_offset(offset), m_size(size) {} template<typename DataType> inline shared_data_view<DataType>::shared_data_view(const shared_data_view<DataType>& other) noexcept : m_data(other.m_data), m_offset(other.m_offset), m_size(other.m_size) {} template<typename DataType> inline shared_data_view<DataType>::shared_data_view(shared_data_view<DataType>&& other) noexcept : m_data(std::move(other.m_data)), m_offset(std::move(other.m_offset)), m_size(std::move(other.m_size)) {} template<typename DataType> inline shared_data_view<DataType>& shared_data_view<DataType>::operator=(const shared_data_view<DataType>& other) noexcept { m_data = other.m_data; m_offset = other.m_offset; m_size = other.m_size; return *this; } template<typename DataType> inline shared_data_view<DataType>& shared_data_view<DataType>::operator=(shared_data_view<DataType>&& other) noexcept { m_data = std::move(other.m_data); m_offset = std::move(other.m_offset); m_size = std::move(other.m_size); return *this; } template<typename DataType> inline shared_data_view<DataType>::operator bool() const noexcept { return m_data ? true : false; } template<typename DataType> inline bool shared_data_view<DataType>::operator==(const shared_data_view& other) const noexcept { return m_data == other.m_data && m_offset == other.m_offset && m_size == other.m_size; } template<typename DataType> inline bool shared_data_view<DataType>::operator!=(const shared_data_view& other) const noexcept { return !operator==(other); } template<typename DataType> inline DataType& shared_data_view<DataType>::at(size_type idx) { if (idx > m_size) throw std::out_of_range("shared_data_view subscript out of range"); return *(m_data.get() + m_offset + static_cast<ptrdiff_t>(idx)); } template<typename DataType> inline const DataType& shared_data_view<DataType>::at(size_type idx) const { if (idx > m_size) throw std::out_of_range("shared_data_view subscript out of range"); return *(m_data.get() + m_offset + static_cast<ptrdiff_t>(idx)); } template<typename DataType> inline DataType& shared_data_view<DataType>::operator[](size_type idx) { return at(idx); } template<typename DataType> inline const DataType& shared_data_view<DataType>::operator[](size_type idx) const { return at(idx); } template<typename DataType> inline typename shared_data_view<DataType>::iterator shared_data_view<DataType>::begin() noexcept { return m_data.get() + m_offset; } template<typename DataType> inline typename shared_data_view<DataType>::iterator shared_data_view<DataType>::end() noexcept { return begin() + m_size; } template<typename DataType> inline DataType* shared_data_view<DataType>::data() noexcept { return begin(); } template<typename DataType> typename shared_data_view<DataType>::const_iterator shared_data_view<DataType>::begin() const noexcept { return m_data.get() + m_offset; } template<typename DataType> typename shared_data_view<DataType>::const_iterator shared_data_view<DataType>::end() const noexcept { return begin() + m_size; } template<typename DataType> const DataType* shared_data_view<DataType>::data() const noexcept { return begin(); } template<typename DataType> inline size_type shared_data_view<DataType>::size() const noexcept { return m_size; } template<typename DataType> inline diff_type shared_data_view<DataType>::offset() const noexcept { return m_offset; } template<typename DataType> inline size_type shared_data_view<DataType>::max_size() const noexcept { return m_size; } }
31.7
126
0.687247
Legion-Engine
f9921dd157206a112f4fecbcb1764952090856ba
1,427
hpp
C++
src/GUI/ButtonsList/ButtonsList.hpp
YaroshenkoYaroslav/FVNEngine
a242e7a289e50819c1edda4b6fe3cd312cf7667d
[ "MIT" ]
null
null
null
src/GUI/ButtonsList/ButtonsList.hpp
YaroshenkoYaroslav/FVNEngine
a242e7a289e50819c1edda4b6fe3cd312cf7667d
[ "MIT" ]
null
null
null
src/GUI/ButtonsList/ButtonsList.hpp
YaroshenkoYaroslav/FVNEngine
a242e7a289e50819c1edda4b6fe3cd312cf7667d
[ "MIT" ]
null
null
null
#ifndef SRC_GUI_BUTTONS_LIST_BUTTONS_LIST #define SRC_GUI_BUTTONS_LIST_BUTTONS_LIST #include <vector> #include "Button.hpp" namespace FVNEngine { class ButtonsList { public: ButtonsList(); int UpdateSfmlEvents(); void Update(); void Draw(); //Controller void AddButton(); void AddButtons(size_t count); void DeleteButton(size_t index); void DeleteButtons(size_t f_index, size_t s_index); size_t GetButtonsCount(); size_t GetPressedButtonIndex(); //Setters void SetWindow(sf::RenderWindow* window); void SetEvent(sf::Event* event); void SetSize(size_t index, sf::Vector2f size); void SetPosition(size_t index, sf::Vector2f position); void LoadTexture(size_t index, std::string texture_file_name); void LoadFont(size_t index, std::string font_file_name); void SetCharacterSize(size_t index, uint8_t character_size); void SetTextFillColor(size_t index, sf::Color color); void SetContent(size_t index, std::wstring content); void LoadButtonPressedSound(size_t index, std::string button_pressed_sound_file_name); //Getters sf::Vector2f GetSize(size_t index); sf::Vector2f GetPosition(size_t index); uint8_t GetCharacterSize(size_t index); sf::Color GetTextFillColor(size_t index); std::wstring GetContent(size_t index); private: sf::RenderWindow* window; sf::Event* event; size_t pressed_button_index; std::vector<Button> buttons_arr; }; } #endif
23.393443
88
0.755431
YaroshenkoYaroslav
f992b42725c8d64f9234881a0679d32a390e3ee2
217
cpp
C++
math/extgcd.cpp
beet-aizu/library-3
6437cddd6011fa4797b98e81577b1a06f11f3350
[ "CC0-1.0" ]
1
2020-11-06T03:36:03.000Z
2020-11-06T03:36:03.000Z
math/extgcd.cpp
beet-aizu/library-3
6437cddd6011fa4797b98e81577b1a06f11f3350
[ "CC0-1.0" ]
null
null
null
math/extgcd.cpp
beet-aizu/library-3
6437cddd6011fa4797b98e81577b1a06f11f3350
[ "CC0-1.0" ]
2
2020-11-06T03:39:10.000Z
2021-04-04T04:38:30.000Z
template<typename T> T extgcd(T a, T b, T &x ,T &y){ for (T u = y = 1, v = x = 0; a; ) { ll q = b/a; swap(x -= q*u, u); swap(y -= q*v, v); swap(b -= q*a, a); } return b; }
19.727273
39
0.364055
beet-aizu
f99db7d7abd2a867d738d1fc5fff577b2ad98727
2,618
cpp
C++
src/ui/widgets/Label.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
65
2018-06-03T23:09:46.000Z
2021-07-22T22:03:34.000Z
src/ui/widgets/Label.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
8
2018-06-20T17:21:30.000Z
2020-06-30T01:06:26.000Z
src/ui/widgets/Label.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
34
2018-06-04T03:40:52.000Z
2022-02-15T07:02:05.000Z
#include "Vorb/stdafx.h" #include "Vorb/ui/widgets/Label.h" #include "Vorb/ui/UIRenderer.h" #include "Vorb/ui/widgets/Viewport.h" vui::Label::Label() : TextWidget(), m_labelColor(color::Transparent), m_labelHoverColor(color::Transparent), m_labelTexture(0), m_labelHoverTexture(0), m_textColor(color::DarkGray), m_textHoverColor(color::AliceBlue) { m_flags.needsDrawableRecalculation = true; } vui::Label::~Label() { // Empty } void vui::Label::addDrawables(UIRenderer& renderer) { // Add the label rect. renderer.add(makeDelegate(&m_drawableRect, &DrawableRect::draw)); // Add the text <- after checkbox to be rendererd on top! TextWidget::addDrawables(renderer); } void vui::Label::setLabelColor(const color4& color) { m_labelColor = color; m_flags.needsDrawableRecalculation = true; } void vui::Label::setLabelHoverColor(const color4& color) { m_labelHoverColor = color; m_flags.needsDrawableRecalculation = true; } void vui::Label::setLabelTexture(VGTexture texture) { m_labelTexture = texture; m_flags.needsDrawableRecalculation = true; } void vui::Label::setLabelHoverTexture(VGTexture texture) { m_labelHoverTexture = texture; m_flags.needsDrawableRecalculation = true; } void vui::Label::setTextColor(const color4& color) { m_textColor = color; m_flags.needsDrawableRecalculation = true; } void vui::Label::setTextHoverColor(const color4& color) { m_textHoverColor = color; m_flags.needsDrawableRecalculation = true; } void vui::Label::calculateDrawables() { m_drawableRect.setPosition(getPaddedPosition()); m_drawableRect.setSize(getPaddedSize()); m_drawableRect.setClipRect(m_clipRect); m_drawableRect.setTexture(m_flags.isMouseIn ? m_labelHoverTexture : m_labelTexture); updateColor(); TextWidget::calculateDrawables(); } void vui::Label::updateColor() { if (m_flags.isMouseIn) { m_drawableText.setColor(m_textHoverColor); m_drawableRect.setColor(m_labelHoverColor); } else { m_drawableText.setColor(m_textColor); m_drawableRect.setColor(m_labelColor); } } void vui::Label::onMouseMove(Sender, const MouseMotionEvent& e) { if (!m_flags.isEnabled) return; if (isInBounds((f32)e.x, (f32)e.y)) { if (!m_flags.isMouseIn) { m_flags.isMouseIn = true; MouseEnter(e); updateColor(); } MouseMove(e); } else { if (m_flags.isMouseIn) { m_flags.isMouseIn = false; MouseLeave(e); updateColor(); } } }
24.933333
88
0.682964
ChillstepCoder
f9a61aa1813970e703095f5b79b442157b9120a8
1,624
cpp
C++
src/app/cmds/loop.cpp
glfernando/sc
55972c296b8a873fed29d4ec6cfdd565da079047
[ "BSD-3-Clause" ]
1
2021-01-18T03:43:37.000Z
2021-01-18T03:43:37.000Z
src/app/cmds/loop.cpp
glfernando/sc
55972c296b8a873fed29d4ec6cfdd565da079047
[ "BSD-3-Clause" ]
null
null
null
src/app/cmds/loop.cpp
glfernando/sc
55972c296b8a873fed29d4ec6cfdd565da079047
[ "BSD-3-Clause" ]
null
null
null
/* * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2021 Fernando Lugo <lugo.fernando@gmail.com> */ /* * Command to sleep for speficied time */ #include <app/shell.h> #include <errcodes.h> #include <string.h> import lib.fmt; import std.string; import std.vector; using lib::fmt::println; using std::string; using std::vector; static void cmd_loop_usage() { println("loop <range> <command>"); // TODO: add support for range with variable name with syntax likeL: loop [var=][x..]y[:step]. // Examples // loop i=0..10:2 echo $i // it should print: // 0 // 2 // 4 // 6 // 8 } static vector<string> split_by(string const& str, char delim) { vector<string> strings; string tmp = ""; for (auto c : str) { if (c != delim) { tmp += c; } else if (tmp != "") { strings.push_back(tmp); tmp = ""; } } // push remaining if (tmp != "") strings.push_back(tmp); return strings; } static int cmd_loop(int argc, char const* argv[]) { if (argc < 3) { cmd_loop_usage(); return ERR_INVALID_ARGS; } size_t num = strtoul(argv[1], nullptr, 0); string cmd_str = ""; for (int i = 2; i < argc; ++i) { if (i != 2) cmd_str += " "; cmd_str += argv[i]; } auto cmds = split_by(cmd_str, ';'); for (size_t i = 0; i != num; ++i) for (auto& cmd : cmds) shell_exec_cmd(cmd.c_str()); return 0; } shell_declare_static_cmd(loop, "loop over a range and execute commands", cmd_loop, cmd_loop_usage);
20.049383
99
0.552956
glfernando
e2fe7ce15de352af154c53b46e8e14ca789ce17f
453
cpp
C++
competitive_programming/programming_contests/uri/sum_of_consecutive_odd_numbers_3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/sum_of_consecutive_odd_numbers_3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/sum_of_consecutive_odd_numbers_3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1158 #include <iostream> using namespace std; int main() { int n, n1, n2, counter=0, total=0; cin >> n; while (n--) { cin >> n1 >> n2; while (true) { if (n1 % 2 != 0) { total += n1; counter++; } if (counter == n2) { break; } n1++; } cout << total << endl; counter = 0; total = 0; } return 0; }
12.583333
64
0.461369
LeandroTk
3900f714b37a4fe65b4a499f6da666044f565f37
47,373
cpp
C++
src/02-opengl/opengl.cpp
randomgraphics/random-graphics
80232edd4f9c66ca2b918ba69a8f94bddd328dfc
[ "BSL-1.0", "BSD-2-Clause" ]
null
null
null
src/02-opengl/opengl.cpp
randomgraphics/random-graphics
80232edd4f9c66ca2b918ba69a8f94bddd328dfc
[ "BSL-1.0", "BSD-2-Clause" ]
null
null
null
src/02-opengl/opengl.cpp
randomgraphics/random-graphics
80232edd4f9c66ca2b918ba69a8f94bddd328dfc
[ "BSL-1.0", "BSD-2-Clause" ]
null
null
null
#ifndef RG_INTERNAL #define RG_INTERNAL #endif #include "rg/opengl.h" #include <sstream> #include <fstream> #include <algorithm> #include <atomic> #include <stack> #include <iomanip> #include <cmath> #if RG_HAS_EGL #include <glad/glad_egl.h> #include <glad/glad_glx.h> #endif using namespace rg; using namespace rg::opengl; // ----------------------------------------------------------------------------- // bool rg::opengl::initExtensions() { if (!gladLoadGL()) { RG_LOGE("fail to load GL extensions."); return 0; } #if RG_MSWIN // TODO: acquire an windows DC and initialize all WGL functions. // HDC dc = ::GetDC(0); // if (gladLoadWGL(dc)) { // ::ReleaseDC(dc); // RG_LOGE("fail to load GL extensions."); // return 0; // } // ::ReleaseDC(dc); #endif #if RG_HAS_EGL if (!gladLoadEGL()) { RG_LOGE("fail to load GL extensions."); return 0; } #endif #if RG_BUILD_DEBUG enableDebugRuntime(); #endif // done return true; } // ----------------------------------------------------------------------------- // void rg::opengl::enableDebugRuntime() { struct OGLDebugOutput { static const char* source2String(GLenum source) { switch (source) { case GL_DEBUG_SOURCE_API_ARB: return "GL API"; case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: return "Window System"; case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: return "Shader Compiler"; case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: return "Third Party"; case GL_DEBUG_SOURCE_APPLICATION_ARB: return "Application"; case GL_DEBUG_SOURCE_OTHER_ARB: return "Other"; default: return "INVALID_SOURCE"; } } static const char* type2String(GLenum type) { switch (type) { case GL_DEBUG_TYPE_ERROR_ARB: return "Error"; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: return "Deprecation"; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: return "Undefined Behavior"; case GL_DEBUG_TYPE_PORTABILITY_ARB: return "Portability"; case GL_DEBUG_TYPE_PERFORMANCE_ARB: return "Performance"; case GL_DEBUG_TYPE_OTHER_ARB: return "Other"; default: return "INVALID_TYPE"; } } static const char* severity2String(GLenum severity) { switch (severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: return "High"; case GL_DEBUG_SEVERITY_MEDIUM_ARB: return "Medium"; case GL_DEBUG_SEVERITY_LOW_ARB: return "Low"; default: return "INVALID_SEVERITY"; } } static void GLAPIENTRY messageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, // length, const GLchar* message, const void*) { // Determine log level bool error_ = false; bool warning = false; bool info = false; switch (type) { case GL_DEBUG_TYPE_ERROR_ARB: case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: error_ = true; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: case GL_DEBUG_TYPE_PORTABILITY: switch (severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: case GL_DEBUG_SEVERITY_MEDIUM_ARB: warning = true; break; case GL_DEBUG_SEVERITY_LOW_ARB: break; default: error_ = true; break; } break; case GL_DEBUG_TYPE_PERFORMANCE_ARB: switch (severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: warning = true; break; case GL_DEBUG_SEVERITY_MEDIUM_ARB: // shader recompiliation, buffer data read back. case GL_DEBUG_SEVERITY_LOW_ARB: break; // verbose: performance warnings from redundant state changes default: error_ = true; break; } break; case GL_DEBUG_TYPE_OTHER_ARB: switch (severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: error_ = true; break; case GL_DEBUG_SEVERITY_MEDIUM_ARB: warning = true; break; case GL_DEBUG_SEVERITY_LOW_ARB: case GL_DEBUG_SEVERITY_NOTIFICATION: break; // verbose default: error_ = true; break; } break; default: error_ = true; break; } std::string s = formatstr( "(id=[%d] source=[%s] type=[%s] severity=[%s]): %s\n%s", id, source2String(source), type2String(type), severity2String(severity), message, backtrace().c_str()); if (error_) RG_LOGE("[GL ERROR] %s", s.c_str()); else if (warning) RG_LOGW("[GL WARNING] %s", s.c_str()); else if (info) RG_LOGI("[GL INFO] %s", s.c_str()); } }; if (GLAD_GL_ARB_debug_output) { glDebugMessageCallbackARB(&OGLDebugOutput::messageCallback, nullptr); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageControlARB( GL_DONT_CARE, // source GL_DONT_CARE, // type GL_DONT_CARE, // severity 0, // count nullptr, // ids GL_TRUE); } } // ----------------------------------------------------------------------------- /// Split a string into token list static void getTokens(std::vector<std::string> & tokens, const char* str) { if (!str || !*str) return; const char* p1 = str; const char* p2 = p1; while (*p1) { while (*p2 && *p2 != ' ') ++p2; tokens.push_back({ p1, p2 }); while (*p2 && *p2 == ' ') ++p2; p1 = p2; } } // ----------------------------------------------------------------------------- // std::string rg::opengl::printGLInfo(bool printExtensionList) { std::stringstream info; // vendor and version info. const char* vendor = (const char*)glGetString(GL_VENDOR); const char* version = (const char*)glGetString(GL_VERSION); const char* renderer = (const char*)glGetString(GL_RENDERER); const char* glsl = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); GLint maxsls = -1, maxslsFast = -1; if (GLAD_GL_EXT_shader_pixel_local_storage) { glGetIntegerv(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT, &maxsls); glGetIntegerv(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_FAST_SIZE_EXT, &maxslsFast); } info << "\n\n" "===================================================\n" " OpenGL Implementation Information\n" "---------------------------------------------------\n" " OpenGL vendor : " << vendor << "\n" " OpenGL version : " << version << "\n" " OpenGL renderer : " << renderer << "\n" " GLSL version : " << glsl << "\n" " Max FS uniform blocks : " << getInt(GL_MAX_FRAGMENT_UNIFORM_BLOCKS) << "\n" " Max uniform block size : " << getInt(GL_MAX_UNIFORM_BLOCK_SIZE) * 4 << " bytes\n" " Max texture units : " << getInt(GL_MAX_TEXTURE_IMAGE_UNITS) << "\n" " Max array texture layers : " << getInt(GL_MAX_ARRAY_TEXTURE_LAYERS) << "\n" " Max color attachments : " << getInt(GL_MAX_COLOR_ATTACHMENTS) << "\n" " Max SSBO binding : " << getInt(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS) << "\n" " Max SSBO FS blocks : " << getInt(GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS) << "\n" " Max SSBO block size : " << getInt(GL_MAX_SHADER_STORAGE_BLOCK_SIZE) * 4 << " bytes\n" " Max CS WorkGroup size : " << getInt(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0) << "," << getInt(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1) << "," << getInt(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2) << "\n" " Max CS WorkGroup count : " << getInt(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0) << "," << getInt(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1) << "," << getInt(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2) << "\n" " Max shader local storage : total=" << maxsls << ", fast=" << maxslsFast << "\n" ; if (printExtensionList) { // get GL extensions std::vector<std::string> extensions; getTokens(extensions, (const char *)glGetString(GL_EXTENSIONS)); #if RG_MSWIN if (GLAD_WGL_EXT_extensions_string) { getTokens(extensions, wglGetExtensionsStringEXT()); } #endif // TODO: get EGL/GLX extensions std::sort(extensions.begin(), extensions.end()); info << "---------------------------------------------------\n"; for(auto e : extensions) { info << " " << e << "\n"; } } info << "===================================================\n"; // done return info.str(); } // ----------------------------------------------------------------------------- // #if RG_HAS_EGL const char * rg::opengl::eglError2String(EGLint err) { switch(err) { case EGL_SUCCESS: return "The last function succeeded without error."; case EGL_NOT_INITIALIZED: return "EGL is not initialized, or could not be initialized, for the specified EGL display connection."; case EGL_BAD_ACCESS: return "EGL cannot access a requested resource (for example a context is bound in another thread)."; case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation."; case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list."; case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context."; case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration."; case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid."; case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection."; case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering."; case EGL_BAD_MATCH: return "Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface)."; case EGL_BAD_PARAMETER: return "One or more argument values are invalid."; case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap."; case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window."; case EGL_CONTEXT_LOST: return "A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering."; default: return "unknown error"; } } #endif // ----------------------------------------------------------------------------- // void rg::opengl::TextureObject::attach(GLenum target, GLuint id) { cleanup(); _owned = false; _desc.target = target; _desc.id = id; bind(0); glGetTexLevelParameteriv(_desc.target, 0, GL_TEXTURE_WIDTH, (GLint*)&_desc.width); RG_ASSERT(_desc.width); glGetTexLevelParameteriv(target, 0, GL_TEXTURE_HEIGHT, (GLint*)&_desc.height); RG_ASSERT(_desc.height); // determine depth switch(target) { case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_3D: glGetTexLevelParameteriv(target, 0, GL_TEXTURE_DEPTH, (GLint*)&_desc.depth); RG_ASSERT(_desc.depth); break; case GL_TEXTURE_CUBE_MAP: _desc.depth = 6; break; default: _desc.depth = 1; break; } GLint maxLevel; glGetTexParameteriv(target, GL_TEXTURE_MAX_LEVEL, &maxLevel); _desc.mips = (uint32_t)maxLevel + 1; glGetTexLevelParameteriv(target, 0, GL_TEXTURE_INTERNAL_FORMAT, (GLint*)&_desc.format); unbind(); } // ----------------------------------------------------------------------------- // void rg::opengl::TextureObject::allocate2D(GLenum f, size_t w, size_t h, size_t m) { cleanup(); _desc.target = GL_TEXTURE_2D; _desc.format = f; _desc.width = (uint32_t)w; _desc.height = (uint32_t)h; _desc.depth = (uint32_t)1; _desc.mips = (uint32_t)m; _owned = true; glGenTextures(1, &_desc.id); glBindTexture(_desc.target, _desc.id); applyDefaultParameters(); glTexStorage2D(_desc.target, (GLsizei)_desc.mips, f, (GLsizei)_desc.width, (GLsizei)_desc.height); glBindTexture(_desc.target, 0); } // ----------------------------------------------------------------------------- // void rg::opengl::TextureObject::allocate2DArray(GLenum f, size_t w, size_t h, size_t l, size_t m) { cleanup(); _desc.target = GL_TEXTURE_2D_ARRAY; _desc.format = f; _desc.width = (uint32_t)w; _desc.height = (uint32_t)h; _desc.depth = (uint32_t)l; _desc.mips = (uint32_t)m; _owned = true; glGenTextures(1, &_desc.id); glBindTexture(_desc.target, _desc.id); applyDefaultParameters(); glTexStorage3D(_desc.target, (GLsizei)_desc.mips, f, (GLsizei)_desc.width, (GLsizei)_desc.height, (GLsizei)_desc.depth); glBindTexture(_desc.target, 0); } // ----------------------------------------------------------------------------- // void rg::opengl::TextureObject::allocateCube(GLenum f, size_t w, size_t m) { cleanup(); _desc.target = GL_TEXTURE_CUBE_MAP; _desc.format = f; _desc.width = (uint32_t)w; _desc.height = (uint32_t)w; _desc.depth = 6; _desc.mips = (uint32_t)m; _owned = true; glGenTextures(1, &_desc.id); glBindTexture(GL_TEXTURE_CUBE_MAP, _desc.id); applyDefaultParameters(); glTexStorage2D(GL_TEXTURE_CUBE_MAP, (GLsizei)_desc.mips, f, (GLsizei)_desc.width, (GLsizei)_desc.width); glBindTexture(_desc.target, 0); } void rg::opengl::TextureObject::applyDefaultParameters() { RG_ASSERT(_desc.width > 0); RG_ASSERT(_desc.height > 0); RG_ASSERT(_desc.depth > 0); RG_ASSERT(_desc.mips > 0); glTexParameteri(_desc.target, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(_desc.target, GL_TEXTURE_MAX_LEVEL, _desc.mips - 1); glTexParameteri(_desc.target, GL_TEXTURE_MIN_FILTER, _desc.mips > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTexParameteri(_desc.target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(_desc.target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(_desc.target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } // // ----------------------------------------------------------------------------- // // // void rg::opengl::TextureObject::setPixels( // size_t level, // size_t x, size_t y, // size_t w, size_t h, // size_t rowPitchInBytes, // const void * pixels) const { // if (empty()) return; // glBindTexture(_desc.target, _desc.id); // auto & cf = getGLenumDesc(_desc.format); // glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // RG_ASSERT(0 == (rowPitchInBytes * 8 % cf.bits)); // glPixelStorei(GL_UNPACK_ROW_LENGTH, rowPitchInBytes * 8 / cf.bits)); // RG_GLCHKDBG(glTexSubImage2D( // _desc.target, // (GLint)level, (GLint)x, (GLint)y, (GLsizei)w, (GLsizei)h, // cf.glFormat, cf.glType, pixels)); // glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // ;; // } // void rg::opengl::TextureObject::setPixels(size_t layer, size_t level, size_t x, size_t y, size_t w, size_t h, size_t rowPitchInBytes, const void* pixels) const // { // if (empty()) return; // glBindTexture(_desc.target, _desc.id); // auto& cf = getGLenumDesc(_desc.format); // RG_ASSERT(0 == (rowPitchInBytes * 8 % cf.bits)); // glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // glPixelStorei(GL_UNPACK_ROW_LENGTH, (int)(rowPitchInBytes * 8 / cf.bits)); // glTexSubImage3D(_desc.target, (GLint)level, (GLint)x, (GLint)y, (GLint)layer, (GLsizei)w, (GLsizei)h, 1, cf.glFormat, cf.glType, pixels); // glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // ;; // } // // ----------------------------------------------------------------------------- // // // ManagedRawImage rg::opengl::TextureObject::getBaseLevelPixels() const { // if (empty()) return {}; // ManagedRawImage image(ImageDesc(_desc.format, _desc.width, _desc.height, _desc.depth)); // #ifdef __ANDROID__ // if (_desc.target == GL_TEXTURE_2D) { // GLuint _frameBuffer = 0; // glGenFramebuffers(1, &_frameBuffer); // glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer); // glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _desc.target, _desc.id, 0); // glReadBuffer(GL_COLOR_ATTACHMENT0); // glReadPixels(0, 0, _desc.width, _desc.height, GL_RGBA, GL_UNSIGNED_BYTE, image.data()); // ;; // } else { // RG_LOGE("read texture 2D array pixels is not implemented on android yet."); // } // #else // auto& cf = getGLenumDesc(_desc.format); // glPixelStorei(GL_UNPACK_ALIGNMENT, image.alignment()); // glPixelStorei(GL_UNPACK_ROW_LENGTH, (int)image.pitch() * 8 / (int)cf.bits); // glBindTexture(_desc.target, _desc.id); // glGetTexImage(_desc.target, 0, cf.glFormat, cf.glType, image.data()); // glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // ;; // #endif // return image; // } // ----------------------------------------------------------------------------- // std::string rg::opengl::DebugSSBO::printLastResult() const { if (!counter) return {}; auto count = std::min<size_t>((*counter), buffer.size() - 1); auto dataSize = sizeof(float) * (count + 1); if (0 != memcmp(buffer.data(), printed.data(), dataSize)) { memcpy(printed.data(), buffer.data(), dataSize); std::stringstream ss; ss << "count = " << *counter << " ["; for (size_t i = 0; i < count; ++i) { auto value = printed[i + 1]; if (std::isnan(value)) ss << std::endl; else ss << value << ", "; } ss << "]"; return ss.str(); } return {}; } // ----------------------------------------------------------------------------- // void rg::opengl::FullScreenQuad::allocate() { const float vertices[] = { -1.f, -1.f, 0.f, 1.f, 3.f, -1.f, 0.f, 1.f, -1.f, 3.f, 0.f, 1.f, }; //Cleanup previous array if any. cleanup(); //Create new array. glGenVertexArrays(1, &va); glBindVertexArray(va); vb.allocate(sizeof(vertices), vertices); vb.bind(); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 4, (const void*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); // unbind } // ----------------------------------------------------------------------------- // void rg::opengl::FullScreenQuad::cleanup() { vb.cleanup(); //If we actually have a vertex array to cleanup. if (va) { //Delete the vertex array. glDeleteVertexArrays(1, &va); //Reset this to mark it as cleaned up. va = 0; } //;; } // ----------------------------------------------------------------------------- // static const char* shaderType2String(GLenum shaderType) { switch (shaderType) { case GL_VERTEX_SHADER: return "vertex"; case GL_FRAGMENT_SHADER: return "fragment"; case GL_COMPUTE_SHADER: return "compute"; default: return ""; } } // ----------------------------------------------------------------------------- static std::string addLineCount(const std::string & in) { std::stringstream ss; ss << "( 1) : "; int line = 1; for (auto ch : in) { if ('\n' == ch) { ss << "\n(" << std::setw(3) << line << ") : "; ++line; } else ss << ch; } return ss.str(); } // ----------------------------------------------------------------------------- // GLuint rg::opengl::loadShaderFromString(const char* source, size_t length, GLenum shaderType, const char* optionalFilename) { if (!source) return 0; const char* sources[] = { source }; if (0 == length) length = strlen(source); GLint sizes[] = { (GLint)length }; auto shader = glCreateShader(shaderType); glShaderSource(shader, 1, sources, sizes); glCompileShader(shader); // check for shader compile errors GLint success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { char infoLog[512]; glGetShaderInfoLog(shader, 512, NULL, infoLog); glDeleteShader(shader); RG_LOGE( "\n================== Failed to compile %s shader '%s' ====================\n" "%s\n" "\n============================= GLSL shader source ===============================\n" "%s\n" "\n================================================================================\n", shaderType2String(shaderType), optionalFilename ? optionalFilename : "<no-name>", infoLog, addLineCount(source).c_str()); return 0; } // done RG_ASSERT(shader); return shader; } // ----------------------------------------------------------------------------- // GLuint rg::opengl::linkProgram(const std::vector<GLuint> & shaders, const char* optionalProgramName) { auto program = glCreateProgram(); for (auto s : shaders) if (s) glAttachShader(program, s); glLinkProgram(program); for (auto s : shaders) if (s) glDetachShader(program, s); GLint success; glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { char infoLog[512]; glGetProgramInfoLog(program, 512, NULL, infoLog); glDeleteProgram(program); RG_LOGE("Failed to link program %s:\n%s", optionalProgramName ? optionalProgramName : "", infoLog); return 0; } // Enable the following code to dump GL program binary to disk. #if 0 if (optionalProgramName) { std::string outfilename = std::string(optionalProgramName) + ".bin"; std::ofstream fs; fs.open(outfilename); if (fs.good()) { std::vector<uint8_t> buffer(1024 * 1024 * 1024); // allocate 1MB buffer. GLsizei len; GLenum dummyFormat; glGetProgramBinary(program, (GLsizei)buffer.size(), &len, &dummyFormat, buffer.data()); fs.write((const char*)buffer.data(), len); } } #endif // done RG_ASSERT(program); return program; } // ----------------------------------------------------------------------------- // bool rg::opengl::SimpleTextureCopy::init() { const char * vscode = R"(#version 320 es out vec2 v_uv; void main() { const vec4 v[] = vec4[]( vec4(-1., -1., 0., 0.), vec4( 3., -1., 2., 0.), vec4(-1., 3., 0., 2.)); gl_Position = vec4(v[gl_VertexID].xy, 0., 1.); v_uv = v[gl_VertexID].zw; } )"; const char * pscode = R"( #version 320 es precision mediump float; layout(binding = 0) uniform %s u_tex0; in vec2 v_uv; out vec4 o_color; void main() { o_color = texture(u_tex0, %s).xyzw; } )"; // tex2d program { auto & prog2d = _programs[GL_TEXTURE_2D]; auto ps2d = formatstr(pscode, "sampler2D", "u_uv"); if (!prog2d.program.loadVsPs(vscode, ps2d)) return false; prog2d.tex0Binding = prog2d.program.getUniformBinding("u_tex0"); } // tex2d array program { auto & prog2darray = _programs[GL_TEXTURE_2D_ARRAY]; auto ps2darray = formatstr(pscode, "sampler2DArray", "vec3(u_uv, 0.)"); if (!prog2darray.program.loadVsPs(vscode, ps2darray)) return false; prog2darray.tex0Binding = prog2darray.program.getUniformBinding("u_tex0"); } // create sampler object glGenSamplers(1, &_sampler); glSamplerParameteri(_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glSamplerParameteri(_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameterf(_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameterf(_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glSamplerParameterf(_sampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); _quad.allocate(); glGenFramebuffers(1, &_fbo); // make sure we have no errors. RG_GLCHK(, return false); return true; } // ----------------------------------------------------------------------------- // void rg::opengl::SimpleTextureCopy::cleanup() { _programs.clear(); _quad.cleanup(); if (_fbo) glDeleteFramebuffers(1, &_fbo), _fbo = 0; if (_sampler) glDeleteSamplers(1, &_sampler), _sampler = 0; } // ----------------------------------------------------------------------------- // void rg::opengl::SimpleTextureCopy::copy(const TextureSubResource & src, const TextureSubResource & dst) { // get destination texture size uint32_t dstw = 0, dsth = 0; glBindTexture(dst.target, dst.id); glGetTexLevelParameteriv(dst.target, dst.level, GL_TEXTURE_WIDTH, (GLint*)&dstw); glGetTexLevelParameteriv(dst.target, dst.level, GL_TEXTURE_HEIGHT, (GLint*)&dsth); // attach FBO to the destination texture glBindFramebuffer(GL_FRAMEBUFFER, _fbo); switch(dst.target) { case GL_TEXTURE_2D: glFramebufferTexture1D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst.id, dst.level); break; case GL_TEXTURE_2D_ARRAY: glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, dst.id, dst.level, dst.z); break; default: // 3D or cube texture RG_LOGE("unsupported destination texture target."); return; } constexpr GLenum drawbuffer = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &drawbuffer); if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus(GL_FRAMEBUFFER)) { RG_LOGE("the frame buffer is not complete."); return; } // get the porgram based on source target auto & prog = _programs[src.target]; if (0 == prog.program) { RG_LOGE("unsupported source texture target."); return; } // do the copy prog.program.use(); glActiveTexture(GL_TEXTURE0 + prog.tex0Binding); glBindTexture(src.target, src.id); glBindSampler(prog.tex0Binding, _sampler); glViewport(0, 0, dstw, dsth); _quad.draw(); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); } // ----------------------------------------------------------------------------- // void rg::opengl::GpuTimeElapsedQuery::stop() { if (_q.running()) { _q.end(); } else { _q.getResult(_result); } } // ----------------------------------------------------------------------------- // std::string rg::opengl::GpuTimeElapsedQuery::print() const { return name + " : " + ns2str(duration()); } // ----------------------------------------------------------------------------- // std::string rg::opengl::GpuTimestamps::print(const char * ident) const { if (_marks.size() < 2) return {}; std::stringstream ss; GLuint64 startTime = _marks[0].result; GLuint64 prevTime = startTime; if (!ident) ident = ""; if (0 == startTime) { ss << ident << "all timestamp queries are pending...\n"; } else { auto getDuration = [](uint64_t a, uint64_t b) { return b >= a ? ns2str(b - a) : " <n/a>"; }; size_t maxlen = 0; for (size_t i = 1; i < _marks.size(); ++i) { maxlen = std::max(_marks[i].name.size(), maxlen); } for (size_t i = 1; i < _marks.size(); ++i) { auto current = _marks[i].result; if (0 == current) { ss << ident << "pending...\n"; break; } //auto fromStart = current > startTime ? (current - startTime) : 0; auto delta = getDuration(prevTime, current); ss << ident << std::setw((int)maxlen) << std::left << _marks[i].name << std::setw(0) << " : " << delta << std::endl; prevTime = current; } ss << ident << "total = " << getDuration(_marks.front().result, _marks.back().result) << std::endl; } return ss.str(); } #if RG_HAS_EGL #define RG_EGLCHK(x, failed_action) if (!(x)) { RG_LOGE(#x " failed: %s", ::rg::opengl::eglError2String(eglGetError())); failed_action; } else void(0) class rg::opengl::PBufferRenderContext::Impl { public: Impl(const CreationParameters & cp) : _cp(cp) { if (!init()) destroy(); } ~Impl() { destroy(); } bool good() const { return !!_rc; } void makeCurrent() { if (!eglMakeCurrent(_disp, _surf, _surf, _rc)) { RG_LOGE("Failed to set current EGL context."); } } void swapBuffers() { if (!eglSwapBuffers(_disp, _surf)) { int error = eglGetError(); RG_LOGE("Post record render swap fail. ERROR: %x", error); } } private: //The context represented by this object. const CreationParameters _cp; bool _new_disp = false; EGLDisplay _disp = 0; EGLContext _rc = 0; EGLSurface _surf = 0; /// cleanup everything void destroy() { if (_surf) eglDestroySurface(_disp, _surf), _surf = 0; if (_rc) eglDestroyContext(_disp, _rc), _rc = 0; if (_new_disp) eglTerminate(_disp), _new_disp = false; _disp = 0; } template <class... Args> static bool failed(Args&&... args) { RG_LOGE(args...); return false; } bool init() { // search for shared display and config first EGLContext currentRC = 0; EGLConfig config = 0; if (_cp.shared) { _disp = eglGetCurrentDisplay(); if (_disp) { currentRC = eglGetCurrentContext(); if (currentRC) { config = getCurrentConfig(_disp, currentRC); } } } // _cp.shared flag is just a hint. so it is possible that there's nothing on current thread to share with. In that case, // we'll just create a standalone context. if (!_disp) { _disp = findBestHardwareDisplay(); if (!_disp) { // no hardware diplay found. use the default one instead. RG_EGLCHK(_disp = eglGetDisplay(EGL_DEFAULT_DISPLAY), return false); } if (!_disp) return failed("no display found."); EGLint major, minor; RG_EGLCHK(eglInitialize(_disp, &major, &minor), return false); RG_LOGI("EGL version = %d.%d", major, minor); } RG_EGLCHK(eglBindAPI(EGL_OPENGL_API), return false); // { // // test code: iterate through all configs // EGLint numConfigs; // RG_EGLCHK(eglGetConfigs(_disp, nullptr, 0, &numConfigs), return false); // std::vector<EGLConfig> configs((size_t)numConfigs); // RG_EGLCHK(eglGetConfigs(_disp, configs.data(), numConfigs, &numConfigs), return false); // const EGLint attribs[] = { // EGL_RENDERABLE_TYPE, // EGL_SURFACE_TYPE, // }; // std::stringstream ss; // for(auto c : configs) { // EGLint v; // ss << "config " << c << "\n"; // for(auto a : attribs) { // RG_EGLCHK(eglGetConfigAttrib(_disp, c, a, &v), return false); // ss << formatstr(" attr 0x%X = 0x%X\n", a, v); // } // } // RG_LOGI(ss); // } if (!config) { const EGLint configAttribs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_NONE }; EGLint numConfigs; EGLConfig configs[10]; RG_EGLCHK(eglChooseConfig(_disp, configAttribs, configs, std::size(configs), &numConfigs), return false); RG_CHK(numConfigs > 0, return false); config = configs[0]; } // create surface EGLint surfAttribs[] = { EGL_WIDTH, (EGLint)_cp.width, EGL_HEIGHT, (EGLint)_cp.height, EGL_NONE, }; RG_EGLCHK(_surf = eglCreatePbufferSurface(_disp, config, surfAttribs), return false); // create context EGLint contextAttribs[] = { EGL_CONTEXT_FLAGS_KHR, _cp.debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0, EGL_NONE, }; RG_EGLCHK(_rc = eglCreateContext(_disp, config, currentRC, contextAttribs), return false); makeCurrent(); // initialize extentions if (!gladLoadGL() || !gladLoadEGL()) { return false; } if (_cp.debug) { enableDebugRuntime(); } // done return true; } static EGLConfig getCurrentConfig(EGLDisplay d, EGLContext c) { EGLint currentConfigID = 0; RG_EGLCHK(eglQueryContext(d, c, EGL_CONFIG_ID, &currentConfigID), return 0); EGLint numConfigs; RG_EGLCHK(eglGetConfigs(d, nullptr, 0, &numConfigs), return 0); std::vector<EGLConfig> configs(numConfigs); RG_EGLCHK(eglGetConfigs(d, configs.data(), numConfigs, &numConfigs), return 0); for(auto config : configs) { EGLint id; eglGetConfigAttrib(d, config, EGL_CONFIG_ID, &id); if (id == currentConfigID) { return config; } } RG_LOGE("Couldn't find current EGL config."); return 0; } // Return the display that represents the best GPU hardware available on current system. static EGLDisplay findBestHardwareDisplay() { // query required extension auto eglQueryDevicesEXT = reinterpret_cast<PFNEGLQUERYDEVICESEXTPROC>(eglGetProcAddress("eglQueryDevicesEXT")); auto eglGetPlatformDisplayExt = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!eglQueryDevicesEXT || !eglGetPlatformDisplayExt) { RG_LOGW("Can't query GPU devices, since required EGL extension(s) are missing. Fallback to default display."); return 0; } EGLDeviceEXT devices[32]; EGLint num_devices; RG_EGLCHK(eglQueryDevicesEXT(32, devices, &num_devices), return 0); if (num_devices == 0) { RG_LOGE("No EGL devices found."); return 0; } // try find the NVIDIA device EGLDisplay nvidia = 0; std::stringstream ss; ss << "Total " << num_devices <<" EGL devices found.\n"; for (int i = 0; i < num_devices; ++i) { auto display = eglGetPlatformDisplayExt(EGL_PLATFORM_DEVICE_EXT, devices[i], nullptr); EGLint major, minor; eglInitialize(display, &major, &minor); const char * s = eglQueryString(display, EGL_VENDOR); std::string vendor = s ? s : "<unknown vendor>"; ss << " "; if (vendor == "NVIDIA") { ss << "*"; nvidia = display; } else { ss << " "; } ss << vendor << "\n"; eglTerminate(display); } RG_LOGI(ss); return nvidia; } }; #else #include <windows.h> static inline const char * getLastErrorString() { int err__ = GetLastError(); static char info[4096]; int n = ::FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err__, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), info, 4096, NULL ); info[4095] = 0; while (n > 0 && '\n' != info[n-1] ) --n; info[n] = 0; return info; } #pragma warning(disable: 4706) // assignment within conditional expression #define CHK_MSW(x, y) if (!(x)) { RG_LOGE(#x " failed: %s", getLastErrorString()); y; } else void(0) class rg::opengl::PBufferRenderContext::Impl { public: Impl(const CreationParameters & cp) : _cp(cp) { bool ok = create(); if (!ok) destroy(); } ~Impl() { destroy(); } bool good() const { return _effectiveDC && _rc; } void makeCurrent() { if (!good()) { RG_LOGE("GL context is not properly initialized."); return; } if (!wglMakeCurrent(_effectiveDC, _rc)) { RG_LOGE("wglMakeCurrent() failed."); } } void swapBuffers() { CHK_MSW(::SwapBuffers(_effectiveDC),); } private: bool create() { if (!_dw.init()) return false; if (!_windowDC.init(_dw)) return false; // create a temporary context TempContext tc; if (!tc.init(_windowDC)) return false; // TODO: only do it once. if (!gladLoadGL() || !gladLoadWGL(_windowDC)) { RG_LOGE("fail to load GL/WGL extensions."); return false; } if (!GLAD_WGL_ARB_pbuffer) { RG_LOGE("WGL_ARB_pbuffer is reuqired to create pbuffer context."); return false; } // RG_LOGI(printGLInfo(true)); // determin pixel format auto pf = determinePixelFormat(); if (0 == pf) return false; // determine effective DC // create pbuffer CHK_MSW(_pbuffer = wglCreatePbufferARB(_windowDC, pf, (int)_cp.width, (int)_cp.height, nullptr), return false); CHK_MSW(_pbufferDC = wglGetPbufferDCARB(_pbuffer), return false); _effectiveDC = _pbufferDC; // Try creating a formal context using wglCreateContextAttribsARB const GLint attributes[] = { WGL_CONTEXT_FLAGS_ARB, _cp.debug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0, 0, }; _rc = wglCreateContextAttribsARB(_effectiveDC, NULL, attributes); if (!_rc) return failed("wglCreateContextAttribsARB failed."); if (_cp.shared) { auto rc = wglGetCurrentContext(); if (rc) CHK_MSW( wglShareLists(rc, _rc), return false); } // switch to the formal context tc.quit(); makeCurrent(); if (_cp.debug) { enableDebugRuntime(); } // done return true; } class AutoDC { HWND _w = 0; HDC _dc = 0; public: ~AutoDC() { destroy(); } bool init(HWND w) { if (!IsWindow(w)) { return false; } CHK_MSW(_dc = ::GetDC(w), return false); _w = w; return true; } void destroy() { if (_dc) ::ReleaseDC(_w, _dc), _dc = 0; } operator HDC() const { return _dc; } }; class TempContext { HGLRC hrc; public: TempContext() : hrc(0) {} ~TempContext() { quit(); } bool init(HDC hdc) { PIXELFORMATDESCRIPTOR pd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Flags PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. 32, // Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, // Number of bits for the depthbuffer 8, // Number of bits for the stencilbuffer 0, // Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = ::ChoosePixelFormat(hdc, &pd); CHK_MSW(::SetPixelFormat(hdc, pf, &pd), return false); CHK_MSW(hrc = ::wglCreateContext( hdc ), return false); CHK_MSW(::wglMakeCurrent(hdc, hrc), return false); return true; } void quit() { if (hrc) { ::wglMakeCurrent(0, 0); ::wglDeleteContext(hrc); hrc = 0; } } }; struct DummyWindow { HWND wnd = 0; ~DummyWindow() { destroy(); } bool init() { destroy(); auto className = L"Random Graphics Dummy Window Class"; WNDCLASSW wc = {}; wc.lpfnWndProc = (WNDPROC)&DefWindowProcW; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = (HINSTANCE)GetModuleHandleW(nullptr); wc.hIcon = LoadIcon (0, IDI_APPLICATION); wc.hCursor = LoadCursor (0,IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = 0; wc.lpszClassName = className; wc.hIcon = LoadIcon(0, IDI_APPLICATION); CHK_MSW(RegisterClassW(&wc), return false); CHK_MSW(wnd = CreateWindowW(className, L"dummy window", 0, CW_USEDEFAULT, CW_USEDEFAULT, 1, 1, nullptr, 0, wc.hInstance, 0), return false); return true; } void destroy() { if (wnd) ::DestroyWindow(wnd), wnd = 0; } operator HWND() const { return wnd; } }; template <class... Args> static bool failed(Args&&... args) { RG_LOGE(args...); return false; } int determinePixelFormat() { // create attribute list std::map<GLint, GLint> attribs = { { WGL_SUPPORT_OPENGL_ARB, GL_TRUE }, { WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB }, { WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB }, { WGL_COLOR_BITS_ARB, 32 }, { WGL_DEPTH_BITS_ARB, 24 }, { WGL_STENCIL_BITS_ARB, 8 }, }; // if (_cp.window) { // attribs[WGL_DRAW_TO_WINDOW_ARB] = GL_TRUE; // attribs[WGL_DOUBLE_BUFFER_ARB] = GL_TRUE; // } else { attribs[WGL_DRAW_TO_PBUFFER_ARB] = GL_TRUE; // } // choose the pixel format std::vector<GLint> attribList; attribList.reserve(attribs.size() + 1); for(auto [k, v]: attribs) { attribList.push_back(k); attribList.push_back(v); } attribList.push_back(0); int pf = 0; uint32_t count = 0; CHK_MSW(wglChoosePixelFormatARB(_windowDC, attribList.data(), nullptr, 1, &pf, &count), return false); if (0 == count || 0 == pf) { RG_LOGE("can't find appropriate pixel format."); return 0; } // done return pf; } void destroy() { if (_rc) wglDeleteContext(_rc), _rc = 0; if (_pbufferDC) wglReleasePbufferDCARB(_pbuffer, _pbufferDC), _pbufferDC = 0; if (_pbuffer) wglDestroyPbufferARB(_pbuffer), _pbuffer = 0; _windowDC.destroy(); _dw.destroy(); } private: const CreationParameters _cp; DummyWindow _dw; AutoDC _windowDC; HPBUFFERARB _pbuffer = 0; HDC _pbufferDC = 0; HDC _effectiveDC = 0; HGLRC _rc = 0; }; #endif rg::opengl::PBufferRenderContext::PBufferRenderContext(const CreationParameters & cp) { RenderContextStack rcs; rcs.push(); _impl = new Impl(cp); rcs.pop(); } rg::opengl::PBufferRenderContext::~PBufferRenderContext() { delete _impl; _impl = nullptr; } rg::opengl::PBufferRenderContext & rg::opengl::PBufferRenderContext::operator=(PBufferRenderContext && that) { if (this != &that) { delete _impl; _impl = that._impl; that._impl = nullptr; } return *this; } bool rg::opengl::PBufferRenderContext::good() const { return _impl ? _impl->good() : false; } void rg::opengl::PBufferRenderContext::makeCurrent() { if(_impl) _impl->makeCurrent(); } void rg::opengl::PBufferRenderContext::swapBuffers() { if(_impl) _impl->swapBuffers(); } class rg::opengl::RenderContextStack::Impl { struct OpenGLRC { #if RG_HAS_EGL EGLDisplay display; EGLSurface drawSurface; EGLSurface readSurface; EGLContext context; void store() { display = eglGetCurrentDisplay(); drawSurface = eglGetCurrentSurface(EGL_DRAW); readSurface = eglGetCurrentSurface(EGL_READ); context = eglGetCurrentContext(); } void restore() const { if (display && context) { if (!eglMakeCurrent(display, drawSurface, readSurface, context)) { EGLint error = eglGetError(); RG_LOGE("Failed to restore EGL context. ERROR: %x", error); } } } #else HGLRC rc; HDC dc; void store() { rc = wglGetCurrentContext(); dc = wglGetCurrentDC(); } void restore() { wglMakeCurrent(dc, rc); } #endif }; std::stack<OpenGLRC> _stack; public: ~Impl() { while(_stack.size() > 1) _stack.pop(); if (1 == _stack.size()) pop(); RG_ASSERT(_stack.empty()); } void push() { _stack.push({}); _stack.top().store(); } void apply() { if (!_stack.empty()) { _stack.top().restore(); } } void pop() { if (!_stack.empty()) { _stack.top().restore(); _stack.pop(); } } }; rg::opengl::RenderContextStack::RenderContextStack() : _impl(new Impl()) {} rg::opengl::RenderContextStack::~RenderContextStack() { delete _impl; } void rg::opengl::RenderContextStack::push() { _impl->push(); } void rg::opengl::RenderContextStack::apply() { _impl->apply(); } void rg::opengl::RenderContextStack::pop() { _impl->pop(); }
34.578832
170
0.542756
randomgraphics
3905da1532e747288a197b30583b11b0e1db2165
1,539
cpp
C++
Source/Riff/Riff_Chunks_AVI__JUNK.cpp
ablwr/AVIMetaEdit
72cdf628fa90ce36e17c8e8f66247e74567b41aa
[ "CC0-1.0" ]
9
2017-05-30T19:21:11.000Z
2020-03-21T03:41:08.000Z
Source/Riff/Riff_Chunks_AVI__JUNK.cpp
fooloomanzoo/AVIMetaEdit
2839eca2075ae071a59db9e7b8e0daf7287c8a2f
[ "CC0-1.0" ]
1
2020-04-08T21:43:29.000Z
2020-04-08T21:43:29.000Z
Source/Riff/Riff_Chunks_AVI__JUNK.cpp
fooloomanzoo/AVIMetaEdit
2839eca2075ae071a59db9e7b8e0daf7287c8a2f
[ "CC0-1.0" ]
11
2015-03-23T14:36:06.000Z
2021-01-11T12:30:12.000Z
// AVI MetaEdit Riff - RIFF stuff for AVI MetaEdit // // This code was created in 2010 for the Library of Congress and the // other federal government agencies participating in the Federal Agencies // Digitization Guidelines Initiative and it is in the public domain. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- #include "Riff/Riff_Chunks.h" #include <cstring> //--------------------------------------------------------------------------- //*************************************************************************** // Read //*************************************************************************** //--------------------------------------------------------------------------- void Riff_AVI__JUNK::Read_Internal () { } //*************************************************************************** // Modify //*************************************************************************** //--------------------------------------------------------------------------- void Riff_AVI__JUNK::Modify_Internal () { } //*************************************************************************** // Write //*************************************************************************** //--------------------------------------------------------------------------- void Riff_AVI__JUNK::Write_Internal () { }
36.642857
78
0.232619
ablwr
39174a4318f008611b5eb2dd7685516b807f1b09
1,645
cpp
C++
src/flapGame/flapGame/Sweat.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
239
2020-11-26T12:53:51.000Z
2022-03-24T01:02:49.000Z
src/flapGame/flapGame/Sweat.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
6
2020-11-27T04:00:44.000Z
2021-07-07T03:02:57.000Z
src/flapGame/flapGame/Sweat.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
24
2020-11-26T22:59:27.000Z
2022-02-06T04:02:50.000Z
#include <flapGame/Core.h> #include <flapGame/Sweat.h> #include <flapGame/DrawContext.h> namespace flap { bool Sweat::update(float dt) { this->time = min(2.f, this->time + dt * 2.f); return this->time < 1.4f; }; void Sweat::addInstances(const Float4x4& birdToViewport, Array<StarShader::InstanceData>& instances) const { Random r{this->seed}; auto addAtAngle = [&](float a, float d, float lag) { float t = min(1.f, this->time + DrawContext::instance()->fracTime * 2.f) + lag; if (t < 0 || t > 1.f) return; float distance = interpolateCubic(1.3f, 1.8f, 2.3f, 2.3f, t); float alpha = clamp(mix(1.25f, 0.f, t), 0.f, 1.f); float size = clamp(mix(0.f, 2.f, t), 0.f, 1.f); float c = 4.f * t - 6.f * t * t - 0.8f; StarShader::InstanceData& inst = instances.append(); inst.color = {1, 1, 1, alpha}; Float2 ofs = Complex::fromAngle(a) * distance * d; inst.modelToViewport = birdToViewport * Float4x4::makeTranslation({ofs.x + 0.02f, 0, ofs.y + c}) * Float4x4::makeRotation({1, 0, 0}, Pi / 2.f) * Float4x4::makeScale(0.2f * size); }; for (u32 j = 0; j < 2; j++) { float sideLag = r.nextFloat() * 0.2f; for (u32 i = 0; i < 3; i++) { float a = i * 0.2f + 0.4f + mix(-0.04f, 0.04f, r.nextFloat()); float d = (i == 1 ? 1.15f : 1.f) + mix(-0.05f, 0.05f, r.nextFloat());; float lag = sideLag + r.nextFloat() * 0.1f; addAtAngle(j ? Pi - a : a, d, lag); } } } } // namespace flap
39.166667
106
0.516717
KnyazQasan
391c341b71ea84b78aa6619b5517f442cd3ec51b
158
cpp
C++
tests/gtest/dummy.cpp
vtta/cpp-bootstrap
43094ed73d323e2165bbdd36e87440e70bdcfb15
[ "WTFPL" ]
1
2020-07-29T14:28:00.000Z
2020-07-29T14:28:00.000Z
tests/gtest/dummy.cpp
vtta/cpp-bootstrap
43094ed73d323e2165bbdd36e87440e70bdcfb15
[ "WTFPL" ]
null
null
null
tests/gtest/dummy.cpp
vtta/cpp-bootstrap
43094ed73d323e2165bbdd36e87440e70bdcfb15
[ "WTFPL" ]
null
null
null
#include "dummy.hpp" #include "gtest/gtest.h" TEST(DummyTests, SampleTest) { for (auto i = 0; i < 10; ++i) { EXPECT_EQ(dummy(i), i + i); } }
17.555556
35
0.550633
vtta
3923070727ad24e35fcda42f48c4b56318f70938
612
cpp
C++
computergraphics/exp1.cpp
samarth70/Computer-Graphics-Course
1b90d953465b537870bb70a33e654b7f72004381
[ "Apache-2.0" ]
null
null
null
computergraphics/exp1.cpp
samarth70/Computer-Graphics-Course
1b90d953465b537870bb70a33e654b7f72004381
[ "Apache-2.0" ]
null
null
null
computergraphics/exp1.cpp
samarth70/Computer-Graphics-Course
1b90d953465b537870bb70a33e654b7f72004381
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; #include<graphics.h> void wait_for_char() { //Wait for a key press int in = 0; while (in == 0) { in = getchar(); } } int main() { int gd = DETECT, gm; int left = 100, right = 200, top = 100, bottom = 200; // printf("\nLet's build a sample rectangle using Graphics in C\n"); initgraph(&gd, &gm, NULL); rectangle(left, top, right, bottom); // getch(); wait_for_char(); closegraph(); return 0; } // g++ -g -o exp1 exp1.cpp -lgraph
17.485714
74
0.542484
samarth70
3923f378dae4aaf75bf5b1d44104585773357a80
2,825
hpp
C++
src/AWEngine/Packet/ToServer/Login/Init.hpp
graymadness/AWEngine_Packet
5a00aa954edf5bc5d496746cfdeab1511d5633b1
[ "MIT" ]
null
null
null
src/AWEngine/Packet/ToServer/Login/Init.hpp
graymadness/AWEngine_Packet
5a00aa954edf5bc5d496746cfdeab1511d5633b1
[ "MIT" ]
null
null
null
src/AWEngine/Packet/ToServer/Login/Init.hpp
graymadness/AWEngine_Packet
5a00aa954edf5bc5d496746cfdeab1511d5633b1
[ "MIT" ]
null
null
null
#pragma once #include <chrono> #include <AWEngine/Packet/IPacket.hpp> namespace AWEngine::Packet::ToServer::Login { /// Initial packet send by client after the connection is created. /// If other packet is sent or no packet is sent in a short period of time (depends on server), server should terminate the connection. /// Tells server what game (and network version) the client is and whenever is just requesting info about the server or wants to join. /// Server may ignore Protocol Version and even Game Name when receiving request for info. /// If sent from outside of a game client, use correct Game Name (when looking for a specific game, otherwise 8 '\0' characters) and Protocol Version 0. /// Possible responses: /// - `ServerInfo` - the info client requested /// - `Kick` - no access to the info or no space for the client to join the server (maximum players online) /// - game-specific init packet - what server needs to tell you (auth info?) /// - (future idea) wait-in-line packet - keep-alive packet telling the client its position in queue AWE_PACKET(Init, ToServer, 0x00) { public: AWE_ENUM(NextStep, uint8_t) { ServerInfo = 0, Join = 1 }; inline static std::string to_string(NextStep value) { switch(value) { case NextStep::ServerInfo: return "ServerInfo"; case NextStep::Join: return "Join"; default: throw std::runtime_error("Unexpected value"); } } public: explicit Init( std::array<char, 8> gameName, uint32_t protocolVersion, NextStep next ) : GameName(gameName), ProtocolVersion(protocolVersion), Next(next) { } explicit Init(NextStep next) : GameName(ProtocolInfo::GameName), ProtocolVersion(ProtocolInfo::ProtocolVersion), Next(next) { } explicit Init(PacketBuffer& in) // NOLINT(cppcoreguidelines-pro-type-member-init) { in >> GameName >> ProtocolVersion >> reinterpret_cast<uint8_t&>(Next); } public: std::array<char, 8> GameName; uint32_t ProtocolVersion; NextStep Next; public: inline void Write(PacketBuffer& out) const override; }; inline static PacketBuffer& operator<<(PacketBuffer& out, Init::NextStep value) { return out << static_cast<uint8_t>(value); } void Init::Write(PacketBuffer& out) const { out << GameName << ProtocolVersion << Next; } }
34.45122
156
0.581593
graymadness
392833cf1592dc6636516baa78069993bbc4f2c8
1,941
cc
C++
absl/strings/internal/string_constant_test.cc
AlexOrion1/abseil-cpp
99a3ea575bc98cfcd9057d7acf16c7831375cecc
[ "Apache-2.0" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
absl/strings/internal/string_constant_test.cc
iWYZ-666/abseil-cpp
aad2c8a3966424bbaa2f26027d104d17f9c1c1ae
[ "Apache-2.0" ]
860
2017-09-26T03:38:59.000Z
2022-03-31T18:28:28.000Z
absl/strings/internal/string_constant_test.cc
iWYZ-666/abseil-cpp
aad2c8a3966424bbaa2f26027d104d17f9c1c1ae
[ "Apache-2.0" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Abseil Authors. // // 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 "absl/strings/internal/string_constant.h" #include "absl/meta/type_traits.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using absl::strings_internal::MakeStringConstant; struct Callable { constexpr absl::string_view operator()() const { return absl::string_view("Callable", 8); } }; TEST(StringConstant, Traits) { constexpr auto str = MakeStringConstant(Callable{}); using T = decltype(str); EXPECT_TRUE(std::is_empty<T>::value); EXPECT_TRUE(std::is_trivial<T>::value); EXPECT_TRUE(absl::is_trivially_default_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_copy_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_move_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_destructible<T>::value); } TEST(StringConstant, MakeFromCallable) { constexpr auto str = MakeStringConstant(Callable{}); using T = decltype(str); EXPECT_EQ(Callable{}(), T::value); EXPECT_EQ(Callable{}(), str()); } TEST(StringConstant, MakeFromStringConstant) { // We want to make sure the StringConstant itself is a valid input to the // factory function. constexpr auto str = MakeStringConstant(Callable{}); constexpr auto str2 = MakeStringConstant(str); using T = decltype(str2); EXPECT_EQ(Callable{}(), T::value); EXPECT_EQ(Callable{}(), str2()); } } // namespace
31.819672
75
0.736218
AlexOrion1
392bbb4665fa36f9dbc5399984082518b8c0801c
32,051
cpp
C++
Extern/JUCE/extras/Introjucer/Source/Project/jucer_Project.cpp
vinniefalco/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
27
2015-05-07T02:10:39.000Z
2021-06-22T14:52:50.000Z
Extern/JUCE/extras/Introjucer/Source/Project/jucer_Project.cpp
JoseDiazRohena/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
null
null
null
Extern/JUCE/extras/Introjucer/Source/Project/jucer_Project.cpp
JoseDiazRohena/SimpleDJ
30cf1929eaaf0906a1056a33378e8b330062c691
[ "MIT" ]
14
2015-09-12T12:00:22.000Z
2022-03-08T22:24:24.000Z
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #include "jucer_Project.h" #include "jucer_ProjectType.h" #include "../Project Saving/jucer_ProjectExporter.h" #include "../Project Saving/jucer_ProjectSaver.h" #include "../Application/jucer_OpenDocumentManager.h" #include "../Application/jucer_Application.h" //============================================================================== namespace Tags { const Identifier projectRoot ("JUCERPROJECT"); const Identifier projectMainGroup ("MAINGROUP"); const Identifier group ("GROUP"); const Identifier file ("FILE"); const Identifier exporters ("EXPORTFORMATS"); const Identifier configGroup ("JUCEOPTIONS"); const Identifier modulesGroup ("MODULES"); const Identifier module ("MODULE"); } const char* Project::projectFileExtension = ".jucer"; //============================================================================== Project::Project (const File& f) : FileBasedDocument (projectFileExtension, String ("*") + projectFileExtension, "Choose a Jucer project to load", "Save Jucer project"), projectRoot (Tags::projectRoot) { Logger::writeToLog ("Loading project: " + f.getFullPathName()); setFile (f); removeDefunctExporters(); setMissingDefaultValues(); setChangedFlag (false); projectRoot.addListener (this); } Project::~Project() { projectRoot.removeListener (this); IntrojucerApp::getApp().openDocumentManager.closeAllDocumentsUsingProject (*this, false); } //============================================================================== void Project::setTitle (const String& newTitle) { projectRoot.setProperty (Ids::name, newTitle, getUndoManagerFor (projectRoot)); getMainGroup().getNameValue() = newTitle; } String Project::getTitle() const { return projectRoot.getChildWithName (Tags::projectMainGroup) [Ids::name]; } String Project::getDocumentTitle() { return getTitle(); } void Project::updateProjectSettings() { projectRoot.setProperty (Ids::jucerVersion, ProjectInfo::versionString, nullptr); projectRoot.setProperty (Ids::name, getDocumentTitle(), nullptr); } void Project::setMissingDefaultValues() { if (! projectRoot.hasProperty (Ids::ID)) projectRoot.setProperty (Ids::ID, createAlphaNumericUID(), nullptr); // Create main file group if missing if (! projectRoot.getChildWithName (Tags::projectMainGroup).isValid()) { Item mainGroup (*this, ValueTree (Tags::projectMainGroup)); projectRoot.addChild (mainGroup.state, 0, 0); } getMainGroup().initialiseMissingProperties(); if (getDocumentTitle().isEmpty()) setTitle ("JUCE Project"); if (! projectRoot.hasProperty (Ids::projectType)) getProjectTypeValue() = ProjectType::getGUIAppTypeName(); if (! projectRoot.hasProperty (Ids::version)) getVersionValue() = "1.0.0"; updateOldStyleConfigList(); moveOldPropertyFromProjectToAllExporters (Ids::bigIcon); moveOldPropertyFromProjectToAllExporters (Ids::smallIcon); getProjectType().setMissingProjectProperties (*this); if (! projectRoot.getChildWithName (Tags::modulesGroup).isValid()) addDefaultModules (false); if (getBundleIdentifier().toString().isEmpty()) getBundleIdentifier() = getDefaultBundleIdentifier(); IntrojucerApp::getApp().updateNewlyOpenedProject (*this); } void Project::updateOldStyleConfigList() { ValueTree deprecatedConfigsList (projectRoot.getChildWithName (ProjectExporter::configurations)); if (deprecatedConfigsList.isValid()) { projectRoot.removeChild (deprecatedConfigsList, nullptr); for (Project::ExporterIterator exporter (*this); exporter.next();) { if (exporter->getNumConfigurations() == 0) { ValueTree newConfigs (deprecatedConfigsList.createCopy()); if (! exporter->isXcode()) { for (int j = newConfigs.getNumChildren(); --j >= 0;) { ValueTree config (newConfigs.getChild(j)); config.removeProperty (Ids::osxSDK, nullptr); config.removeProperty (Ids::osxCompatibility, nullptr); config.removeProperty (Ids::osxArchitecture, nullptr); } } exporter->settings.addChild (newConfigs, 0, nullptr); } } } } void Project::moveOldPropertyFromProjectToAllExporters (Identifier name) { if (projectRoot.hasProperty (name)) { for (Project::ExporterIterator exporter (*this); exporter.next();) exporter->settings.setProperty (name, projectRoot [name], nullptr); projectRoot.removeProperty (name, nullptr); } } void Project::removeDefunctExporters() { ValueTree exporters (projectRoot.getChildWithName (Tags::exporters)); for (;;) { ValueTree oldVC6Exporter (exporters.getChildWithName ("MSVC6")); if (oldVC6Exporter.isValid()) exporters.removeChild (oldVC6Exporter, nullptr); else break; } } void Project::addDefaultModules (bool shouldCopyFilesLocally) { addModule ("juce_core", shouldCopyFilesLocally); if (! isConfigFlagEnabled ("JUCE_ONLY_BUILD_CORE_LIBRARY")) { addModule ("juce_events", shouldCopyFilesLocally); addModule ("juce_graphics", shouldCopyFilesLocally); addModule ("juce_data_structures", shouldCopyFilesLocally); addModule ("juce_gui_basics", shouldCopyFilesLocally); addModule ("juce_gui_extra", shouldCopyFilesLocally); addModule ("juce_gui_audio", shouldCopyFilesLocally); addModule ("juce_cryptography", shouldCopyFilesLocally); addModule ("juce_video", shouldCopyFilesLocally); addModule ("juce_opengl", shouldCopyFilesLocally); addModule ("juce_audio_basics", shouldCopyFilesLocally); addModule ("juce_audio_devices", shouldCopyFilesLocally); addModule ("juce_audio_formats", shouldCopyFilesLocally); addModule ("juce_audio_processors", shouldCopyFilesLocally); } } bool Project::isAudioPluginModuleMissing() const { return getProjectType().isAudioPlugin() && ! isModuleEnabled ("juce_audio_plugin_client"); } //============================================================================== static void registerRecentFile (const File& file) { RecentlyOpenedFilesList::registerRecentFileNatively (file); getAppSettings().recentFiles.addFile (file); getAppSettings().flush(); } Result Project::loadDocument (const File& file) { ScopedPointer <XmlElement> xml (XmlDocument::parse (file)); if (xml == nullptr || ! xml->hasTagName (Tags::projectRoot.toString())) return Result::fail ("Not a valid Jucer project!"); ValueTree newTree (ValueTree::fromXml (*xml)); if (! newTree.hasType (Tags::projectRoot)) return Result::fail ("The document contains errors and couldn't be parsed!"); registerRecentFile (file); projectRoot = newTree; removeDefunctExporters(); setMissingDefaultValues(); setChangedFlag (false); return Result::ok(); } Result Project::saveDocument (const File& file) { return saveProject (file, false); } Result Project::saveProject (const File& file, bool isCommandLineApp) { updateProjectSettings(); sanitiseConfigFlags(); if (! isCommandLineApp) registerRecentFile (file); ProjectSaver saver (*this, file); return saver.save (! isCommandLineApp); } Result Project::saveResourcesOnly (const File& file) { ProjectSaver saver (*this, file); return saver.saveResourcesOnly(); } //============================================================================== static File lastDocumentOpened; File Project::getLastDocumentOpened() { return lastDocumentOpened; } void Project::setLastDocumentOpened (const File& file) { lastDocumentOpened = file; } //============================================================================== void Project::valueTreePropertyChanged (ValueTree& tree, const Identifier& property) { if (property == Ids::projectType) setMissingDefaultValues(); changed(); } void Project::valueTreeChildAdded (ValueTree&, ValueTree&) { changed(); } void Project::valueTreeChildRemoved (ValueTree&, ValueTree&) { changed(); } void Project::valueTreeChildOrderChanged (ValueTree&) { changed(); } void Project::valueTreeParentChanged (ValueTree&) {} //============================================================================== File Project::resolveFilename (String filename) const { if (filename.isEmpty()) return File::nonexistent; filename = replacePreprocessorDefs (getPreprocessorDefs(), filename); if (FileHelpers::isAbsolutePath (filename)) return File::createFileWithoutCheckingPath (FileHelpers::currentOSStylePath (filename)); // (avoid assertions for windows-style paths) return getFile().getSiblingFile (FileHelpers::currentOSStylePath (filename)); } String Project::getRelativePathForFile (const File& file) const { String filename (file.getFullPathName()); File relativePathBase (getFile().getParentDirectory()); String p1 (relativePathBase.getFullPathName()); String p2 (file.getFullPathName()); while (p1.startsWithChar (File::separator)) p1 = p1.substring (1); while (p2.startsWithChar (File::separator)) p2 = p2.substring (1); if (p1.upToFirstOccurrenceOf (File::separatorString, true, false) .equalsIgnoreCase (p2.upToFirstOccurrenceOf (File::separatorString, true, false))) { filename = FileHelpers::getRelativePathFrom (file, relativePathBase); } return filename; } //============================================================================== const ProjectType& Project::getProjectType() const { if (const ProjectType* type = ProjectType::findType (getProjectTypeString())) return *type; const ProjectType* guiType = ProjectType::findType (ProjectType::getGUIAppTypeName()); jassert (guiType != nullptr); return *guiType; } //============================================================================== void Project::createPropertyEditors (PropertyListBuilder& props) { props.add (new TextPropertyComponent (getProjectNameValue(), "Project Name", 256, false), "The name of the project."); props.add (new TextPropertyComponent (getVersionValue(), "Project Version", 16, false), "The project's version number, This should be in the format major.minor.point"); props.add (new TextPropertyComponent (getCompanyName(), "Company Name", 256, false), "Your company name, which will be added to the properties of the binary where possible"); { StringArray projectTypeNames; Array<var> projectTypeCodes; const Array<ProjectType*>& types = ProjectType::getAllTypes(); for (int i = 0; i < types.size(); ++i) { projectTypeNames.add (types.getUnchecked(i)->getDescription()); projectTypeCodes.add (types.getUnchecked(i)->getType()); } props.add (new ChoicePropertyComponent (getProjectTypeValue(), "Project Type", projectTypeNames, projectTypeCodes)); } props.add (new TextPropertyComponent (getBundleIdentifier(), "Bundle Identifier", 256, false), "A unique identifier for this product, mainly for use in OSX/iOS builds. It should be something like 'com.yourcompanyname.yourproductname'"); getProjectType().createPropertyEditors (*this, props); props.add (new TextPropertyComponent (getProjectPreprocessorDefs(), "Preprocessor definitions", 32768, false), "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace or commas to separate the items - to include a space or comma in a definition, precede it with a backslash."); props.add (new TextPropertyComponent (getProjectUserNotes(), "Notes", 32768, true), "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts."); } static StringArray getConfigs (const Project& p) { StringArray configs; configs.addTokens (p.getVersionString(), ",.", String::empty); configs.trim(); configs.removeEmptyStrings(); return configs; } String Project::getVersionAsHex() const { const StringArray configs (getConfigs (*this)); int value = (configs[0].getIntValue() << 16) + (configs[1].getIntValue() << 8) + configs[2].getIntValue(); if (configs.size() >= 4) value = (value << 8) + configs[3].getIntValue(); return "0x" + String::toHexString (value); } StringPairArray Project::getPreprocessorDefs() const { return parsePreprocessorDefs (projectRoot [Ids::defines]); } //============================================================================== Project::Item Project::getMainGroup() { return Item (*this, projectRoot.getChildWithName (Tags::projectMainGroup)); } static void findImages (const Project::Item& item, OwnedArray<Project::Item>& found) { if (item.isImageFile()) { found.add (new Project::Item (item)); } else if (item.isGroup()) { for (int i = 0; i < item.getNumChildren(); ++i) findImages (item.getChild (i), found); } } void Project::findAllImageItems (OwnedArray<Project::Item>& items) { findImages (getMainGroup(), items); } //============================================================================== Project::Item::Item (Project& project_, const ValueTree& state_) : project (project_), state (state_) { } Project::Item::Item (const Item& other) : project (other.project), state (other.state) { } Project::Item Project::Item::createCopy() { Item i (*this); i.state = i.state.createCopy(); return i; } String Project::Item::getID() const { return state [Ids::ID]; } void Project::Item::setID (const String& newID) { state.setProperty (Ids::ID, newID, nullptr); } Image Project::Item::loadAsImageFile() const { return isValid() ? ImageCache::getFromFile (getFile()) : Image::null; } Project::Item Project::Item::createGroup (Project& project, const String& name, const String& uid) { Item group (project, ValueTree (Tags::group)); group.setID (uid); group.initialiseMissingProperties(); group.getNameValue() = name; return group; } bool Project::Item::isFile() const { return state.hasType (Tags::file); } bool Project::Item::isGroup() const { return state.hasType (Tags::group) || isMainGroup(); } bool Project::Item::isMainGroup() const { return state.hasType (Tags::projectMainGroup); } bool Project::Item::isImageFile() const { return isFile() && ImageFileFormat::findImageFormatForFileExtension (getFile()) != nullptr; } Project::Item Project::Item::findItemWithID (const String& targetId) const { if (state [Ids::ID] == targetId) return *this; if (isGroup()) { for (int i = getNumChildren(); --i >= 0;) { Item found (getChild(i).findItemWithID (targetId)); if (found.isValid()) return found; } } return Item (project, ValueTree::invalid); } bool Project::Item::canContain (const Item& child) const { if (isFile()) return false; if (isGroup()) return child.isFile() || child.isGroup(); jassertfalse return false; } bool Project::Item::shouldBeAddedToTargetProject() const { return isFile(); } Value Project::Item::getShouldCompileValue() { return state.getPropertyAsValue (Ids::compile, getUndoManager()); } bool Project::Item::shouldBeCompiled() const { return state [Ids::compile]; } Value Project::Item::getShouldAddToResourceValue() { return state.getPropertyAsValue (Ids::resource, getUndoManager()); } bool Project::Item::shouldBeAddedToBinaryResources() const { return state [Ids::resource]; } Value Project::Item::getShouldInhibitWarningsValue() { return state.getPropertyAsValue (Ids::noWarnings, getUndoManager()); } bool Project::Item::shouldInhibitWarnings() const { return state [Ids::noWarnings]; } Value Project::Item::getShouldUseStdCallValue() { return state.getPropertyAsValue (Ids::useStdCall, nullptr); } bool Project::Item::shouldUseStdCall() const { return state [Ids::useStdCall]; } String Project::Item::getFilePath() const { if (isFile()) return state [Ids::file].toString(); else return String::empty; } File Project::Item::getFile() const { if (isFile()) return project.resolveFilename (state [Ids::file].toString()); else return File::nonexistent; } void Project::Item::setFile (const File& file) { setFile (RelativePath (project.getRelativePathForFile (file), RelativePath::projectFolder)); jassert (getFile() == file); } void Project::Item::setFile (const RelativePath& file) { jassert (file.getRoot() == RelativePath::projectFolder); jassert (isFile()); state.setProperty (Ids::file, file.toUnixStyle(), getUndoManager()); state.setProperty (Ids::name, file.getFileName(), getUndoManager()); } bool Project::Item::renameFile (const File& newFile) { const File oldFile (getFile()); if (oldFile.moveFileTo (newFile) || (newFile.exists() && ! oldFile.exists())) { setFile (newFile); IntrojucerApp::getApp().openDocumentManager.fileHasBeenRenamed (oldFile, newFile); return true; } return false; } bool Project::Item::containsChildForFile (const RelativePath& file) const { return state.getChildWithProperty (Ids::file, file.toUnixStyle()).isValid(); } Project::Item Project::Item::findItemForFile (const File& file) const { if (getFile() == file) return *this; if (isGroup()) { for (int i = getNumChildren(); --i >= 0;) { Item found (getChild(i).findItemForFile (file)); if (found.isValid()) return found; } } return Item (project, ValueTree::invalid); } File Project::Item::determineGroupFolder() const { jassert (isGroup()); File f; for (int i = 0; i < getNumChildren(); ++i) { f = getChild(i).getFile(); if (f.exists()) return f.getParentDirectory(); } Item parent (getParent()); if (parent != *this) { f = parent.determineGroupFolder(); if (f.getChildFile (getName()).isDirectory()) f = f.getChildFile (getName()); } else { f = project.getFile().getParentDirectory(); if (f.getChildFile ("Source").isDirectory()) f = f.getChildFile ("Source"); } return f; } void Project::Item::initialiseMissingProperties() { if (! state.hasProperty (Ids::ID)) setID (createAlphaNumericUID()); if (isFile()) { state.setProperty (Ids::name, getFile().getFileName(), nullptr); } else if (isGroup()) { for (int i = getNumChildren(); --i >= 0;) getChild(i).initialiseMissingProperties(); } } Value Project::Item::getNameValue() { return state.getPropertyAsValue (Ids::name, getUndoManager()); } String Project::Item::getName() const { return state [Ids::name]; } void Project::Item::addChild (const Item& newChild, int insertIndex) { state.addChild (newChild.state, insertIndex, getUndoManager()); } void Project::Item::removeItemFromProject() { state.getParent().removeChild (state, getUndoManager()); } Project::Item Project::Item::getParent() const { if (isMainGroup() || ! isGroup()) return *this; return Item (project, state.getParent()); } struct ItemSorter { static int compareElements (const ValueTree& first, const ValueTree& second) { return first [Ids::name].toString().compareIgnoreCase (second [Ids::name].toString()); } }; struct ItemSorterWithGroupsAtStart { static int compareElements (const ValueTree& first, const ValueTree& second) { const bool firstIsGroup = first.hasType (Tags::group); const bool secondIsGroup = second.hasType (Tags::group); if (firstIsGroup == secondIsGroup) return first [Ids::name].toString().compareIgnoreCase (second [Ids::name].toString()); else return firstIsGroup ? -1 : 1; } }; void Project::Item::sortAlphabetically (bool keepGroupsAtStart) { if (keepGroupsAtStart) { ItemSorterWithGroupsAtStart sorter; state.sort (sorter, getUndoManager(), true); } else { ItemSorter sorter; state.sort (sorter, getUndoManager(), true); } } Project::Item Project::Item::getOrCreateSubGroup (const String& name) { for (int i = state.getNumChildren(); --i >= 0;) { const ValueTree child (state.getChild (i)); if (child.getProperty (Ids::name) == name && child.hasType (Tags::group)) return Item (project, child); } return addNewSubGroup (name, -1); } Project::Item Project::Item::addNewSubGroup (const String& name, int insertIndex) { String newID (createGUID (getID() + name + String (getNumChildren()))); int n = 0; while (findItemWithID (newID).isValid()) newID = createGUID (newID + String (++n)); Item group (createGroup (project, name, newID)); jassert (canContain (group)); addChild (group, insertIndex); return group; } bool Project::Item::addFile (const File& file, int insertIndex, const bool shouldCompile) { if (file == File::nonexistent || file.isHidden() || file.getFileName().startsWithChar ('.')) return false; if (file.isDirectory()) { Item group (addNewSubGroup (file.getFileNameWithoutExtension(), insertIndex)); DirectoryIterator iter (file, false, "*", File::findFilesAndDirectories); while (iter.next()) { if (! project.getMainGroup().findItemForFile (iter.getFile()).isValid()) group.addFile (iter.getFile(), -1, shouldCompile); } group.sortAlphabetically (false); } else if (file.existsAsFile()) { if (! project.getMainGroup().findItemForFile (file).isValid()) addFileUnchecked (file, insertIndex, shouldCompile); } else { jassertfalse; } return true; } void Project::Item::addFileUnchecked (const File& file, int insertIndex, const bool shouldCompile) { Item item (project, ValueTree (Tags::file)); item.initialiseMissingProperties(); item.getNameValue() = file.getFileName(); item.getShouldCompileValue() = shouldCompile && file.hasFileExtension ("cpp;mm;c;m;cc;cxx;r"); item.getShouldAddToResourceValue() = project.shouldBeAddedToBinaryResourcesByDefault (file); if (canContain (item)) { item.setFile (file); addChild (item, insertIndex); } } bool Project::Item::addRelativeFile (const RelativePath& file, int insertIndex, bool shouldCompile) { Item item (project, ValueTree (Tags::file)); item.initialiseMissingProperties(); item.getNameValue() = file.getFileName(); item.getShouldCompileValue() = shouldCompile; item.getShouldAddToResourceValue() = project.shouldBeAddedToBinaryResourcesByDefault (file); if (canContain (item)) { item.setFile (file); addChild (item, insertIndex); return true; } return false; } Icon Project::Item::getIcon() const { const Icons& icons = getIcons(); if (isFile()) { if (isImageFile()) return Icon (icons.imageDoc, Colours::blue); return Icon (icons.document, Colours::yellow); } if (isMainGroup()) return Icon (icons.juceLogo, Colours::orange); return Icon (icons.folder, Colours::darkgrey); } bool Project::Item::isIconCrossedOut() const { return isFile() && ! (shouldBeCompiled() || shouldBeAddedToBinaryResources() || getFile().hasFileExtension (headerFileExtensions)); } //============================================================================== ValueTree Project::getConfigNode() { return projectRoot.getOrCreateChildWithName (Tags::configGroup, nullptr); } const char* const Project::configFlagDefault = "default"; const char* const Project::configFlagEnabled = "enabled"; const char* const Project::configFlagDisabled = "disabled"; Value Project::getConfigFlag (const String& name) { ValueTree configNode (getConfigNode()); Value v (configNode.getPropertyAsValue (name, getUndoManagerFor (configNode))); if (v.getValue().toString().isEmpty()) v = configFlagDefault; return v; } bool Project::isConfigFlagEnabled (const String& name) const { return projectRoot.getChildWithName (Tags::configGroup).getProperty (name) == configFlagEnabled; } void Project::sanitiseConfigFlags() { ValueTree configNode (getConfigNode()); for (int i = configNode.getNumProperties(); --i >= 0;) { const var value (configNode [configNode.getPropertyName(i)]); if (value != configFlagEnabled && value != configFlagDisabled) configNode.removeProperty (configNode.getPropertyName(i), getUndoManagerFor (configNode)); } } //============================================================================== ValueTree Project::getModulesNode() { return projectRoot.getOrCreateChildWithName (Tags::modulesGroup, nullptr); } bool Project::isModuleEnabled (const String& moduleID) const { ValueTree modules (projectRoot.getChildWithName (Tags::modulesGroup)); for (int i = 0; i < modules.getNumChildren(); ++i) if (modules.getChild(i) [Ids::ID] == moduleID) return true; return false; } Value Project::shouldShowAllModuleFilesInProject (const String& moduleID) { return getModulesNode().getChildWithProperty (Ids::ID, moduleID) .getPropertyAsValue (Ids::showAllCode, getUndoManagerFor (getModulesNode())); } Value Project::shouldCopyModuleFilesLocally (const String& moduleID) { return getModulesNode().getChildWithProperty (Ids::ID, moduleID) .getPropertyAsValue (Ids::useLocalCopy, getUndoManagerFor (getModulesNode())); } void Project::addModule (const String& moduleID, bool shouldCopyFilesLocally) { if (! isModuleEnabled (moduleID)) { ValueTree module (Tags::module); module.setProperty (Ids::ID, moduleID, nullptr); ValueTree modules (getModulesNode()); modules.addChild (module, -1, getUndoManagerFor (modules)); shouldShowAllModuleFilesInProject (moduleID) = true; } if (shouldCopyFilesLocally) shouldCopyModuleFilesLocally (moduleID) = true; } void Project::removeModule (const String& moduleID) { ValueTree modules (getModulesNode()); for (int i = 0; i < modules.getNumChildren(); ++i) if (modules.getChild(i) [Ids::ID] == moduleID) modules.removeChild (i, getUndoManagerFor (modules)); } void Project::createRequiredModules (const ModuleList& availableModules, OwnedArray<LibraryModule>& modules) const { for (int i = 0; i < availableModules.modules.size(); ++i) if (isModuleEnabled (availableModules.modules.getUnchecked(i)->uid)) modules.add (availableModules.modules.getUnchecked(i)->create()); } int Project::getNumModules() const { return projectRoot.getChildWithName (Tags::modulesGroup).getNumChildren(); } String Project::getModuleID (int index) const { return projectRoot.getChildWithName (Tags::modulesGroup).getChild (index) [Ids::ID].toString(); } //============================================================================== ValueTree Project::getExporters() { return projectRoot.getOrCreateChildWithName (Tags::exporters, nullptr); } int Project::getNumExporters() { return getExporters().getNumChildren(); } ProjectExporter* Project::createExporter (int index) { jassert (index >= 0 && index < getNumExporters()); return ProjectExporter::createExporter (*this, getExporters().getChild (index)); } void Project::addNewExporter (const String& exporterName) { ScopedPointer<ProjectExporter> exp (ProjectExporter::createNewExporter (*this, exporterName)); ValueTree exporters (getExporters()); exporters.addChild (exp->settings, -1, getUndoManagerFor (exporters)); } void Project::createExporterForCurrentPlatform() { addNewExporter (ProjectExporter::getCurrentPlatformExporterName()); } //============================================================================== String Project::getFileTemplate (const String& templateName) { int dataSize; const char* data = BinaryData::getNamedResource (templateName.toUTF8(), dataSize); if (data == nullptr) { jassertfalse; return String::empty; } return String::fromUTF8 (data, dataSize); } //============================================================================== Project::ExporterIterator::ExporterIterator (Project& project_) : index (-1), project (project_) {} Project::ExporterIterator::~ExporterIterator() {} bool Project::ExporterIterator::next() { if (++index >= project.getNumExporters()) return false; exporter = project.createExporter (index); if (exporter == nullptr) { jassertfalse; // corrupted project file? return next(); } return true; } PropertiesFile& Project::getStoredProperties() const { return getAppSettings().getProjectProperties (getProjectUID()); }
32.407482
218
0.615145
vinniefalco
39457244a39358cc7495ecb0cd23528b98ba93c3
353
cpp
C++
CHEFDETE.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
CHEFDETE.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
CHEFDETE.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; unordered_set<int> st; for (int i = 0; i < n; ++i) { int tmp; cin>>tmp; st.insert(tmp); } if (n==1) { printf("0\n"); return 0; } for (int i = 1; i <= n; ++i) { if (st.find(i)==st.end()) { printf("%d ",i ); } } return 0; }
13.074074
30
0.450425
trehanarsh
3945ce9ea4197b4f904a27cf4c946b204bcb92c6
6,641
cpp
C++
src/graphics/Animation.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
src/graphics/Animation.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
src/graphics/Animation.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
#include "graphics/Animation.h" #include <fstream> Animation::Animation(){ currentAnimElemIndex = 0; currentAnimElemTimePassed = 0; animationTime = 0; animationTimePassed = 0; animFrame = 0; } Animation::~Animation(){ } AnimationStateObj* Animation::saveState(){ animObj.animFrame = animFrame; animObj.animationTimePassed = animationTimePassed; animObj.currentAnimElemIndex = currentAnimElemIndex; animObj.currentAnimElemTimePassed = currentAnimElemTimePassed; return &animObj; } void Animation::loadState(AnimationStateObj stateObj){ animFrame = stateObj.animFrame; animationTimePassed = stateObj.animationTimePassed; currentAnimElemIndex = stateObj.currentAnimElemIndex; currentAnimElemTimePassed = stateObj.currentAnimElemTimePassed; } void Animation::loadAnimEvents(nlohmann::json json){ loadAnimEvents(4, json); } void Animation::loadAnimEvents(float defaultScale, nlohmann::json json) { for (auto i : json.items()) { int animTime = i.value().at("time"); float scale = defaultScale; int offsetX = 0; int offsetY = 0; if(i.value().count("offsetY")){ offsetY = i.value().at("offsetY"); } if(i.value().count("scale")){ std::string animScaleStr = i.value().at("scale"); scale = std::stof(animScaleStr); printf("the scale %f\n", scale); } if(i.value().count("offsetX")){ offsetX = i.value().at("offsetX"); } AnimationElement element(animTime, offsetX*scale, offsetY); if (i.value().count("color")) { element.isYellow = true; } GameTexture* text = &element.gameTexture; text->cartesian = true; std::string path(i.value().at("file").get<std::string>()); size_t found = path.find("\%CHARNAME\%"); if (found != std::string::npos) { path = path.replace(found, 10, charName); printf("path:%s\n", path.c_str()); } const char* pathPointer = path.c_str(); std::pair realDimensions = getDimensions(pathPointer); if(i.value().count("width")){ realDimensions.first = i.value().at("width"); } if(i.value().count("height")){ realDimensions.second = i.value().at("height"); } if (animTime == -1) { element.infiniteFrame = true; } text->loadTexture(pathPointer); // TODO: fix scale text->setDimensions(0, 0, realDimensions.first*scale, realDimensions.second*scale); // text->setColor(255, 0, 0); if (offsetX == -1) { element.offsetX = ((realDimensions.first * scale)/2); } if (offsetX == -2) { element.offsetX = ((realDimensions.first * scale)); } if (offsetX == -3) { element.offsetX = ((realDimensions.first * scale)); } if (offsetY == -1) { element.offsetY = ((realDimensions.second * scale)/2); } animationTime += animTime; element.endTime = animationTime; animationElements.push_back(element); if (element.infiniteFrame) { frames.push_back(animationElements.size() - 1); } else { for (int i = 1; i <= animTime; ++i) { frames.push_back(animationElements.size() - 1); } } } } void Animation::drawRect(SDL_Rect rect) { Camera* cam = graphics->getCamera(); SDL_SetRenderDrawColor(graphics->getRenderer(), 128, 0, 128, 0xFF); rect.x = (rect.x - cam->cameraRect.x); rect.y = (rect.y + (graphics->getWindowHeight() - rect.h) - 60) + cam->cameraRect.y; SDL_RenderFillRect(graphics->getRenderer(), &rect); SDL_SetRenderDrawColor(graphics->getRenderer(), 0xFF, 0xFF, 0xFF, 0xFF); } void Animation::render(int x, int y, bool faceRight, int stateTime) { int camOffset = graphics->getCamera()->cameraRect.x; int frameIndex = 0; if (stateTime >= frames.size()) { frameIndex = frames[frames.size() - 1]; } else { frameIndex = frames[stateTime]; } AnimationElement* elem = &animationElements.at(frameIndex); GameTexture* currentText = &elem->gameTexture; int width = currentText->getDimensions().first; int offsetX = elem->offsetX; int offsetY = elem->offsetY; faceRight ? currentText->setCords(x-offsetX, ((y - 60) + offsetY)) : currentText->setCords((x+offsetX)-width, ((y - 60) + offsetY)); if (hitShake) { if (hitShakeToggler == 3) { faceRight ? currentText->setCords((x-offsetX) + 10, ((y - 60) + offsetY)) : currentText->setCords(((x+offsetX)-width) - 10, ((y - 60) + offsetY)); } else if (hitShakeToggler == 6) { faceRight ? currentText->setCords((x-offsetX) - 10, ((y - 60) + offsetY)) : currentText->setCords(((x+offsetX)-width) + 10, ((y - 60) + offsetY)); } hitShakeToggler++; if (hitShakeToggler == 7) { hitShakeToggler = 0; } } if (isRed) { currentText->setColor(255, 0, 0); } if (isGreen) { currentText->setColor(0, 128, 0); } if (elem->isYellow) { currentText->setColor(255, 255, 0); } if (isLight) { currentText->setColor(173,216,230); } currentText->render(faceRight); if (isRed || isLight || isGreen || elem->isYellow) { currentText->setColor(255, 255, 255); } } void Animation::renderHitspark(int x, int y, bool faceRight) { int camOffset = graphics->getCamera()->cameraRect.x; AnimationElement* elem = &animationElements.at(currentAnimElemIndex); GameTexture* currentText = &elem->gameTexture; int width = currentText->getDimensions().first; int offsetX = elem->offsetX; int offsetY = elem->offsetY; faceRight ? currentText->setCords(x+offsetX, ((y - 60) + offsetY)) : currentText->setCords(x-offsetX, ((y - 60) + offsetY)); currentText->render(faceRight); currentAnimElemTimePassed++; animationTimePassed++; if(animationTimePassed == elem->endTime){ if (currentAnimElemIndex+1 != animationElements.size()) { currentAnimElemIndex++; } } } void Animation::setAnimTime(int time) { animationTimePassed = time; } void Animation::shake(int duration) { } void Animation::setAnimElemIndex(int index) { currentAnimElemIndex = index; } void Animation::resetAnimEvents() { animFrame = 0; animationTimePassed = 0; currentAnimElemIndex = 0; currentAnimElemTimePassed = 0; } int Animation::timeRemaining() { return animationTime - animationTimePassed; } std::pair<int, int> Animation::getDimensions(const char* path) { std::pair<int, int> returnPair; unsigned int width, height; std::ifstream img(path); // width and height are offset by 16 bytes // ty TCP training, everything has a TLV img.seekg(16); img.read((char *)&width, 4); img.read((char *)&height, 4); returnPair.first = ntohl(width); returnPair.second = ntohl(height); img.close(); return returnPair; }
29.255507
150
0.655624
MicahMartin
3945fa1d2b3b7684190c31d8b0f27fede76a3d95
1,531
hh
C++
perl/inc/com/centreon/connector/perl/pipe_handle.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
perl/inc/com/centreon/connector/perl/pipe_handle.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
perl/inc/com/centreon/connector/perl/pipe_handle.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
6
2016-02-05T15:12:03.000Z
2021-09-02T19:40:35.000Z
/* ** Copyright 2012-2014 Centreon ** ** 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 information : contact@centreon.com */ #ifndef CCCP_PIPE_HANDLE_HH #define CCCP_PIPE_HANDLE_HH #include "com/centreon/connector/perl/namespace.hh" #include "com/centreon/handle.hh" CCCP_BEGIN() /** * @class pipe_handle pipe_handle.hh * "com/centreon/connector/perl/pipe_handle.hh" * @brief Wrap a pipe FD. * * Wrap a pipe file descriptor within a class. */ class pipe_handle : public handle { int _fd; public: pipe_handle(int fd = -1); ~pipe_handle() noexcept override; pipe_handle(pipe_handle const& ph) = delete; pipe_handle& operator=(pipe_handle const& ph) = delete; void close() noexcept override; static void close_all_handles(); native_handle get_native_handle() noexcept override; unsigned long read(void* data, unsigned long size) override; void set_fd(int fd); unsigned long write(void const* data, unsigned long size) override; }; CCCP_END() #endif // !CCCP_PIPE_HANDLE_HH
28.886792
75
0.738733
centreon-lab
394af68a0a7eac6e9dd3d4783e1b85b66eef4c8b
1,167
cpp
C++
src/DlgRotateSlider.cpp
SVGEditors/QtSVGEditor
90194f281f284a747d6250ff73aa42e931834869
[ "MIT" ]
1
2022-03-31T02:28:18.000Z
2022-03-31T02:28:18.000Z
src/DlgRotateSlider.cpp
SVGEditors/QtSVGEditor
90194f281f284a747d6250ff73aa42e931834869
[ "MIT" ]
null
null
null
src/DlgRotateSlider.cpp
SVGEditors/QtSVGEditor
90194f281f284a747d6250ff73aa42e931834869
[ "MIT" ]
null
null
null
/** * * @license MIT * * @copyright: 2022 LinJi * * @technical support: www.svgsvg.cn * * @email: 93681992@qq.com * * @module: QtSVGEditor * * 版权申明: * * 本源码开源基于MIT协议。 * * 该软件及其相关文档对所有人免费,可以任意处置,包括使用,复制,修改,合并,发表,分发,再授权,或者销售。 * * 唯一的限制是需要保留我们的许可申明。 * */ #include "DlgRotateSlider.h" #include <QLineEdit> CDlgRotateSlider::CDlgRotateSlider(QWidget *parent) :QDialog(parent) { m_nValue = 0; m_ui.setupUi(this); QSize sz = size(); setFixedSize(sz); m_ui.spinBox->setRange(-360, 360); m_ui.spinBox->setValue(0); m_ui.horizontalSlider->setRange(0, 360); connect(m_ui.horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(OnvalueChanged(int))); connect(m_ui.spinBox, SIGNAL(valueChanged(int)), this, SLOT(OnSpinvalueChanged(int))); m_ui.spinBox->setFocus(); } CDlgRotateSlider::~CDlgRotateSlider() { } void CDlgRotateSlider::OnvalueChanged(int value) { if (value != m_nValue) { m_nValue = value; m_ui.spinBox->setValue(value); emit RotatevalueChanged(value); } } void CDlgRotateSlider::OnSpinvalueChanged(int value) { if (value != m_nValue) { m_nValue = value; m_ui.horizontalSlider->setValue(value); emit RotatevalueChanged(value); } }
17.953846
92
0.71551
SVGEditors
394f37c0ff51298c401fb267a2c9bcdbd3d36792
1,988
cc
C++
gazebo/physics/roki/RokiPhysics_TEST.cc
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiPhysics_TEST.cc
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiPhysics_TEST.cc
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include "gazebo/physics/physics.hh" #include "gazebo/physics/PhysicsEngine.hh" #include "gazebo/physics/roki/RokiPhysics.hh" #include "gazebo/test/ServerFixture.hh" using namespace gazebo; using namespace physics; class RokiPhysics_TEST : public ServerFixture { public: void PhysicsMsgParam(); public: void OnPhysicsMsgResponse(ConstResponsePtr &_msg); public: static msgs::Physics physicsPubMsg; public: static msgs::Physics physicsResponseMsg; }; msgs::Physics RokiPhysics_TEST::physicsPubMsg; msgs::Physics RokiPhysics_TEST::physicsResponseMsg; TEST_F(RokiPhysics_TEST, PhysicsParam) { std::string physicsEngineStr = "roki"; Load("worlds/empty.world", true, physicsEngineStr); WorldPtr world = get_world("default"); ASSERT_TRUE(world != NULL); PhysicsEnginePtr physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), physicsEngineStr); RokiPhysicsPtr rokiPhysics = boost::static_pointer_cast<RokiPhysics>(physics); ASSERT_TRUE(odePhysics != NULL); } void RokiPhysics_TEST::OnPhysicsMsgResponse(ConstResponsePtr &_msg) { if (_msg->type() == physicsPubMsg.GetTypeName()) physicsResponseMsg.ParseFromString(_msg->serialized_data()); } void RokiPhysics_TEST::PhysicsMsgParam() { physicsPubMsg.Clear(); physicsResponseMsg.Clear(); std::string physicsEngineStr = "roki"; Load("worlds/empty.world", false, physicsEngineStr); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); physics::PhysicsEnginePtr engine = world->GetPhysicsEngine(); ASSERT_TRUE(engine != NULL); transport::NodePtr phyNode; phyNode = transport::NodePtr(new transport::Node()); phyNode->Init(); phyNode->Fini(); } TEST_F(RokiPhysics_TEST, PhysicsMsgParam) { PhysicsMsgParam(); } ///////////////////////////////////////////////// /// Main int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26.157895
67
0.731388
nyxrobotics
39538a3c3b852ad8cedabbfe89d16c5178be0e3f
1,375
cpp
C++
Atropos/source/renderer/resource/CTexture.cpp
redagito/Atropos
eaf926d5826fd5d5d38a7f8e6aceda64808ba27d
[ "MIT" ]
null
null
null
Atropos/source/renderer/resource/CTexture.cpp
redagito/Atropos
eaf926d5826fd5d5d38a7f8e6aceda64808ba27d
[ "MIT" ]
null
null
null
Atropos/source/renderer/resource/CTexture.cpp
redagito/Atropos
eaf926d5826fd5d5d38a7f8e6aceda64808ba27d
[ "MIT" ]
null
null
null
#include "CTexture.h" #include "debug/Log.h" #include "io/TgaLoader.h" #include <stdexcept> #include <fstream> #include <vector> CTexture::CTexture() : d_mipMapLevel(0), d_texId(0), d_height(0), d_width(0) { // Create texture id glGenTextures(1, &d_texId); } bool CTexture::init(const CImage& image) { // Bind texture glBindTexture(GL_TEXTURE_2D, d_texId); // Texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); // Load data to vram glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getData()); // Mip maps glGenerateMipmap(GL_TEXTURE_2D); // Unbind glBindTexture(GL_TEXTURE_2D, 0); return true; } // Clean up texture vram CTexture::~CTexture() { glDeleteTextures(1, &d_texId); return; } // Binds texture to texture unit void CTexture::setActive(unsigned int unit) const { // Set active texture unit glActiveTexture(GL_TEXTURE0 + unit); // Bind glBindTexture(GL_TEXTURE_2D, d_texId); return; } GLuint CTexture::getId() const { return d_texId; } GLint CTexture::getMipMapLevel() const { return d_mipMapLevel; }
19.366197
125
0.751273
redagito
39583c8c5c1308a92a82591c11eb116d35baf125
257
hpp
C++
library/ATF/LPPARAMDATA.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/LPPARAMDATA.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/LPPARAMDATA.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <tagPARAMDATA.hpp> START_ATF_NAMESPACE typedef tagPARAMDATA *LPPARAMDATA; END_ATF_NAMESPACE
23.363636
108
0.789883
lemkova
395bf1dbbed76561675905b89e2b94b195078e3c
18,518
cpp
C++
libstm/algs/swissht.cpp
riclas/rstm
a72c861c1b68f5fd516b2293ebdc58c2b62849b4
[ "BSD-3-Clause" ]
null
null
null
libstm/algs/swissht.cpp
riclas/rstm
a72c861c1b68f5fd516b2293ebdc58c2b62849b4
[ "BSD-3-Clause" ]
null
null
null
libstm/algs/swissht.cpp
riclas/rstm
a72c861c1b68f5fd516b2293ebdc58c2b62849b4
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) 2011 * University of Rochester Department of Computer Science * and * Lehigh University Department of Computer Science and Engineering * * License: Modified BSD * Please see the file LICENSE.RSTM for licensing information */ #include "../profiling.hpp" #include "algs.hpp" #include "RedoRAWUtils.hpp" using stm::UNRECOVERABLE; using stm::TxThread; using stm::ABORTED; using stm::ACTIVE; using stm::WriteSet; using stm::WriteSetEntry; using stm::timestamp; using stm::timestamp_max; using stm::threads; using stm::threadcount; using stm::greedy_ts; using stm::SWISS_PHASE2; using stm::orec_t; using stm::get_orec; using stm::id_version_t; using stm::nanorec_t; using stm::NanorecList; using stm::OrecList; using wlpdstm::Log; /** * This is a good-faith implementation of SwissTM. * * What that means, precisely, has to do with how we translate the SwissTM * algorithm to allow /algorithmic/ comparisons with OrecEager and LLT. * Specifically, we decided in the past that OrecEager and LLT would not use * any of the clever 'lock is a pointer into my writeset' tricks that were * proposed in the TinySTM paper, and so we don't use those tricks here, * either. The cost is minimal (actually, with the RSTM WriteSet hash, the * tricks are typically not profitable anyway), but it is worth stating, up * front, that we do not adhere to this design point. * * Additionally, orec management differs slightly here from in OrecEager and * LLT. In those systems, we use "2-word" orecs, where the acquirer writes * the old orec value in the second word after acquiring the first word. * This halves the cost of logging, as the list of held locks only gives * orec addresses, not the old values. However, in SwissTM, there is a * tradeoff where on one hand, having rlocks separate from wlocks can * decrease cache misses for read-only transactions, but on the other hand * doing so doubles logging overhead for read locking by writers at commit * time. It would be odd to use the 2-word orecs for read locks and not for * write locks, but a more efficient technique is to use the second word of * 2-word orecs as the rlock, and then use traditional 2-word lock logging, * where the old lock value is also stored. * * Other changes are typically small. The biggest deals with adding * detection of remote aborts, which wasn't discussed in the paper. * * NB: we could factor some CM code out of the RO codepath. We could also * make the phase2 switch cause a thread to use different function pointers. */ namespace { const uintptr_t SUCCESS = 0; const uintptr_t VALIDATION_FAILED = 1; struct SwissHT { static TM_FASTCALL bool begin(TxThread*); static TM_FASTCALL void* read(STM_READ_SIG(,,)); static TM_FASTCALL void write(STM_WRITE_SIG(,,,)); static TM_FASTCALL void local_write(STM_WRITE_SIG(,,,)); static TM_FASTCALL void commit(STM_COMMIT_SIG(,)); static uintptr_t commit_ht(STM_COMMIT_SIG(,)); static void end(STM_COMMIT_SIG(tx,)); static stm::scope_t* rollback(STM_ROLLBACK_SIG(,,,)); static bool irrevoc(STM_IRREVOC_SIG(,)); static void onSwitchTo(); static void cm_start(TxThread*); static void cm_on_rollback(TxThread*); static void cm_on_write(TxThread*); static bool cm_should_abort(TxThread*, uintptr_t owner_id); static NOINLINE uintptr_t validate_commit(TxThread*); static NOINLINE intptr_t validate_inflight(TxThread*); }; void* helper(void* data){ TxThread *tx; uintptr_t validate_ts_ht = 0; bool abort = false; while (!(tx = stm::threads[(intptr_t)data].data)) { CFENCE; } while(tx->running){ //sem_wait(&tlstm::TxMixinv::prog_thread[ptid].semaphore); //while (tlstm::TxMixinv::prog_thread[ptid].requires_validation == false) { //_mm_monitor(&tlstm::TxMixinv::prog_thread[ptid].requires_validation, 0, 0); //if(tlstm::TxMixinv::prog_thread[ptid].requires_validation == false) { // _mm_mwait(0, 0); //} //tlstm::TxMixinv::prog_thread[ptid].validated = false; //tlstm::TxMixinv::prog_thread[ptid].requires_validation = false; //if(!tlstm::TxMixinv::ExtendTx(ptid)){ // for (int i = 0; i < tlstm::TxMixinv::specdepth; i++) { // tlstm::TxMixinv::prog_thread[ptid].owners[i]->abort_transaction = true; // } //} //tlstm::TxMixinv::prog_thread[ptid].validated = true; //} if(tx->commits_done.val == tx->commits_requested.val){ //wait if the worker thread is explicitly aborting a transaction while(tx->abort_required.val){ CFENCE; } } bool should_commit = tx->commits_done.val < tx->commits_requested.val; if(!should_commit){ if(!abort){ if(tx->validate_ts > validate_ts_ht){ uintptr_t newts = timestamp.val; validate_ts_ht = tx->validate_ts; if (SwissHT::validate_inflight(tx) == VALIDATION_FAILED){ abort = true; continue; } tx->start_time = newts; } } } else { if(!abort){ //before committing a read only transaction we need to check if it is valid if(!tx->writesets[tx->tx_first_index].data->size()){ if(tx->validate_ts > validate_ts_ht){ if (SwissHT::validate_inflight(tx) == VALIDATION_FAILED){ abort = true; } } } if(!abort) abort = tx->commit_ht(tx); } if(abort) { if (tx->nanorecs_v[tx->tx_first_index]->size()) { foreach_ptr(NanorecList, i, tx->nanorecs_v[tx->tx_first_index]) { i->o->v.all = i->v; } } tx->num_aborts++; abort = false; } tx->writesets[tx->tx_first_index].data->reset(); tx->r_orecs_v[tx->tx_first_index]->clear(); tx->nanorecs_v[tx->tx_first_index]->reset(); tx->commits_done.val++; tx->tx_first_index = tx->commits_done.val % TxThread::SPECULATIVE_TXS; } CFENCE; } return 0; } /** * begin swiss transaction: set to active, notify allocator, get start * time, and notify CM */ bool SwissHT::begin(TxThread* tx) { tx->tx_last_index = tx->commits_requested.val % TxThread::SPECULATIVE_TXS; //tx->scopes[tx->tx_last_index] = tx->scope; //assert(tx->writesets[tx->tx_last_index].data->size() == 0); //assert(tx->nanorecs_v[tx->tx_last_index]->size() == 0); tx->alive = ACTIVE; tx->allocator.onTxBegin(); tx->start_time = timestamp.val; cm_start(tx); return false; } // word based transactional read void* SwissHT::read(STM_READ_SIG(tx,addr,mask)) { //if (tx->alive == ABORTED) // tx->tmabort(tx); //if((uintptr_t)addr < 0xffff){ // tx->tmabort(tx); //} // get orec address orec_t* o = get_orec(addr); // do I own the orec? if (o->v.all == tx->my_lock_v[tx->tx_last_index].all) { CFENCE; // order orec check before possible read of *addr // if this address is in my writeset, return looked-up value, else // do a direct read from memory WriteSetEntry log(STM_WRITE_SET_ENTRY(addr, NULL, mask)); bool found = tx->writesets[tx->tx_last_index].data->find(log); REDO_RAW_CHECK(found, log, mask); void* val = *addr; REDO_RAW_CLEANUP(val, found, log, mask); return val; } while (true) { // get a consistent read of the value, during a period where the // read version is unchanging and not locked uintptr_t rver1 = o->p; CFENCE; void* tmp = *addr; CFENCE; uintptr_t rver2 = o->p; // deal with inconsistent reads if ((rver1 != rver2) || (rver1 == UINT_MAX)) { // bad read: we'll go back to top, but first make sure we didn't // get aborted if (tx->alive == ABORTED) tx->tmabort(tx); continue; } // the read was good: log the orec tx->r_orecs_v[tx->tx_last_index]->insert(o); // do we need to extend our timestamp? if (rver1 > tx->start_time) { /*uintptr_t newts = timestamp.val; CFENCE; if(validate_inflight(tx) == VALIDATION_FAILED) tx->tmabort(tx); CFENCE; tx->start_time = newts;*/ tx->validate_ts = timestamp.val; } return tmp; } } /** * SwissTM write */ void SwissHT::write(STM_WRITE_SIG(tx,addr,val,mask)) { // put value in redo log tx->writesets[tx->tx_last_index].data->insert(WriteSetEntry(STM_WRITE_SET_ENTRY(addr, val, mask))); // get the orec addr orec_t* o = get_orec(addr); // if I'm already the lock holder, we're done! if (o->v.all == tx->my_lock_v[tx->tx_last_index].all) return; while(o->v.fields.lock && o->v.fields.id/TxThread::SPECULATIVE_TXS == tx->my_lock_v[tx->tx_last_index].fields.id/TxThread::SPECULATIVE_TXS){ if(tx->alive == ABORTED) tx->tmabort(tx); CFENCE; } while (true) { // look at write lock id_version_t ivt; ivt.all = o->v.all; // if locked, CM will either tell us to self-abort, or to continue if (ivt.fields.lock) { if (cm_should_abort(tx, ivt.fields.id/TxThread::SPECULATIVE_TXS)) tx->tmabort(tx); // check liveness before continuing if (tx->alive == ABORTED) tx->tmabort(tx); continue; } // if I can't lock it, start over if (!bcasptr(&o->v.all, ivt.all, tx->my_lock_v[tx->tx_last_index].all)) { // check liveness before continuing if (tx->alive == ABORTED) tx->tmabort(tx); continue; } // log this lock acquire tx->nanorecs_v[tx->tx_last_index]->insert(nanorec_t(o, o->p)); // if read version too high, validate and extend ts if (o->p > tx->start_time) { tx->validate_ts = timestamp.val; /*uintptr_t newts = timestamp.val; CFENCE; if(validate_inflight(tx) == VALIDATION_FAILED) tx->tmabort(tx); CFENCE; tx->start_time = newts;*/ } // notify CM & return cm_on_write(tx); return; } } void SwissHT::local_write(STM_WRITE_SIG(tx,addr,val,mask)) { *addr = val; } void SwissHT::commit(STM_COMMIT_SIG(tx,)) { tx->commits_requested.val++; bool waited = false; //if (tx->alive == ABORTED) // tx->tmabort(tx); //if(tx->abort_transaction){ // tx->tmabort(tx); //} while(tx->commits_requested.val - tx->commits_done.val == TxThread::SPECULATIVE_TXS){ if(!waited){ tx->wait_commit++; waited = true; } /* if(tx->abort_transaction){ tx->tmabort(tx); }*/ CFENCE; } /* while(tx->dirty_commit != tx->commits_done){ tx->writesets[tx->dirty_commit % TxThread::SPECULATIVE_TXS]->reset(); tx->local_writesets[tx->dirty_commit % TxThread::SPECULATIVE_TXS]->reset(); // tx->r_orecs_v[tx->dirty_commit % TxThread::SPECULATIVE_TXS]->clear(); // tx->nanorecs_v[tx->dirty_commit % TxThread::SPECULATIVE_TXS]->clear(); tx->dirty_commit++; }*/ } /** * commit a read-write transaction * * Note: we don't check if we've been remote aborted here, because there * are no while/continue patterns in this code. If someone asked us to * abort, we can ignore them... either we commit and zero our state, * or we abort anyway. */ uintptr_t SwissHT::commit_ht(STM_COMMIT_SIG(tx,upper_stack_bound)) { // read-only case if (!tx->writesets[tx->tx_first_index].data->size()) { //tx->r_orecs_v[tx->tx_first_index]->clear(); OnReadOnlyCommit(tx); return SUCCESS; } // writing case: // first, grab all read locks covering the write set foreach_ptr(NanorecList, i, tx->nanorecs_v[tx->tx_first_index]) { i->o->p = UINT_MAX; } // increment the global timestamp, and maybe validate tx->end_time = 1 + faiptr(&timestamp.val); if (tx->end_time > (tx->start_time + 1)){ uintptr_t ret = validate_commit(tx); if(ret == VALIDATION_FAILED){ return VALIDATION_FAILED; } } // run the redo log tx->writesets[tx->tx_first_index].data->writeback(STM_WHEN_PROTECT_STACK(upper_stack_bound)); // now release all read and write locks covering the writeset foreach_ptr(NanorecList, i, tx->nanorecs_v[tx->tx_first_index]) { i->o->p = tx->end_time; CFENCE; i->o->v.all = tx->end_time; } // clean up //it's easier to cleanup writesets on the worker threads // tx->writesets[tx->tx_first_index].data->reset(); //tx->r_orecs_v[tx->tx_first_index]->clear(); //tx->nanorecs_v[tx->tx_first_index]->reset(); OnReadWriteCommit(tx); return SUCCESS; } // rollback a transaction stm::scope_t* SwissHT::rollback(STM_ROLLBACK_SIG(tx, upper_stack_bound, except, len)) { tx->abort_required.val = 1; //while(tx->abort_transaction == false){ // CFENCE; //} stm::PreRollback(tx); // Perform writes to the exception object if there were any... taking the // branch overhead without concern because we're not worried about // rollback overheads. //STM_ROLLBACK(tx->writesets[tx->tx_last_index], upper_stack_bound, except, len); //pthread_mutex_lock(&tx->mutex); //for(int i = tx->commits_requested; i >= tx->commits_done; i--){ //int index = i % TxThread::SPECULATIVE_TXS; //tx->local_writesets[tx->tx_last_index]->writeback(); //tx->local_writesets[tx->tx_last_index]->reset(); //ValueListEntry entry(0,0); //while(tx->read_queues[i]->try_dequeue(entry)); tx->writesets[tx->tx_last_index].data->rollback(); // now release all read and write locks covering the writeset... often, // we didn't acquire the read locks, but it's harmless to do it like // this if (tx->nanorecs_v[tx->tx_last_index]->size()) { foreach_ptr(NanorecList, i, tx->nanorecs_v[tx->tx_last_index]) { i->o->v.all = i->v; } } tx->writesets[tx->tx_last_index].data->reset(); tx->r_orecs_v[tx->tx_last_index]->clear(); tx->nanorecs_v[tx->tx_last_index]->reset(); // } //printf("aborting %d\n", tx->commits_requested); tx->commits_requested.val = tx->commits_done.val; // contention management on rollback cm_on_rollback(tx); tx->abort_required.val = 0; // tx->abort_transaction = false; CFENCE; return PostRollback(tx); //return tx->scopes[tx->tx_first_index]; } // Validate a transaction's read set // // for in-flight transactions, write locks don't provide a fallback when // read-lock validation fails intptr_t SwissHT::validate_inflight(TxThread* tx) { foreach_log_ptr(wlpdstm::Log<orec_t*>, i, tx->r_orecs_v[tx->tx_last_index]) { if ((*i)->p > tx->start_time) return VALIDATION_FAILED; } return SUCCESS; } // validate a transaction's write set // // for committing transactions, there is a backup plan wh read-lock // validation fails uintptr_t SwissHT::validate_commit(TxThread* tx) { foreach_log_ptr(wlpdstm::Log<orec_t*>, i, tx->r_orecs_v[tx->tx_first_index]) { if ((*i)->p > tx->start_time) { if ((*i)->v.all != tx->my_lock_v[tx->tx_first_index].all) { foreach_ptr(NanorecList, i, tx->nanorecs_v[tx->tx_first_index]) { i->o->p = i->v; } return VALIDATION_FAILED; } } } return SUCCESS; } // cotention managers void SwissHT::cm_start(TxThread* tx) { if (!tx->consec_aborts) tx->cm_ts = UINT_MAX; } void SwissHT::cm_on_write(TxThread* tx) { if ((tx->cm_ts == UINT_MAX) && (tx->writesets[tx->tx_last_index].data->size() == SWISS_PHASE2)) tx->cm_ts = 1 + faiptr(&greedy_ts.val); } bool SwissHT::cm_should_abort(TxThread* tx, uintptr_t owner_id) { // if caller has MAX priority, it should self-abort if (tx->cm_ts == UINT_MAX) return true; // self-abort if owner's priority lower than mine TxThread* owner = threads[owner_id - 1].data; if (owner->cm_ts < tx->cm_ts) return true; // request owner to remote abort owner->alive = ABORTED; return false; } void SwissHT::cm_on_rollback(TxThread* tx) { exp_backoff(tx); } /*** Become irrevocable via abort-and-restart */ bool SwissHT::irrevoc(STM_IRREVOC_SIG(,)) { return false; } /*** Keep SwissTM metadata healthy */ void SwissHT::onSwitchTo() { timestamp.val = MAXIMUM(timestamp.val, timestamp_max.val); } void SwissHT::end(STM_COMMIT_SIG(tx,)){ while(tx->commits_done.val < tx->commits_requested.val){ //if(tx->alive == stm::ABORTED){ // tx->tmabort(tx); //} CFENCE; } } } namespace stm { /** * Every STM must provide an 'initialize' function that specifies how the * algorithm is to be used when adaptivity is off. * * Some of this is a bit ugly right now, but when we fix the way adaptive * policies work it will clean itself. */ template<> void initTM<SwissHT>() { // set the name stms[SwissHT].name = "SwissHT"; // set the pointers stms[SwissHT].begin = ::SwissHT::begin; stms[SwissHT].commit = ::SwissHT::commit; stms[SwissHT].read = ::SwissHT::read; stms[SwissHT].write = ::SwissHT::write; stms[SwissHT].local_write = ::SwissHT::local_write; stms[SwissHT].rollback = ::SwissHT::rollback; stms[SwissHT].irrevoc = ::SwissHT::irrevoc; stms[SwissHT].switcher = ::SwissHT::onSwitchTo; stms[SwissHT].privatization_safe = false; stms[SwissHT].helper = helper; stms[SwissHT].helperThreads = TxThread::numThreads; stms[SwissHT].commit_ht = SwissHT::commit_ht; stms[SwissHT].end = SwissHT::end; } }
31.280405
146
0.613403
riclas
39666554e538cb91e9d7b586d8af803415c9e241
2,240
cpp
C++
Core/VideoFrame.cpp
st0ne77/balsampear
0740ad229187d8c68c83a9ef34a6df80774e817b
[ "BSD-3-Clause" ]
6
2019-07-22T15:37:12.000Z
2019-12-09T03:49:17.000Z
Core/VideoFrame.cpp
st0ne77/balsampear
0740ad229187d8c68c83a9ef34a6df80774e817b
[ "BSD-3-Clause" ]
null
null
null
Core/VideoFrame.cpp
st0ne77/balsampear
0740ad229187d8c68c83a9ef34a6df80774e817b
[ "BSD-3-Clause" ]
null
null
null
#include "VideoFrame.h" extern "C" { #include "libavutil/frame.h" } namespace balsampear { VideoFrame::VideoFrame() :Frame(), width_(0), height_(0) { } VideoFrame::VideoFrame(AVFrame* avframe) :VideoFrame() { if (avframe) { width_ = avframe->width; height_ = avframe->height; fmt_ = VideoFormat(avframe->format); } if (width_ > 0 && height_ > 0) { size_t size = calcFrameSize(); allocMemory(size); fill(avframe); } } VideoFrame::~VideoFrame() { } int VideoFrame::width() const { return width_; } int VideoFrame::height() const { return height_; } VideoFormat VideoFrame::Format() const { return fmt_; } VideoFormat::PixelFormat VideoFrame::pixelFoemat() { return fmt_.pixelFormat(); } size_t VideoFrame::calcFrameSize() { size_t result = 0; VideoFormat::PixelFormat pixelfmt = fmt_.pixelFormat(); switch (pixelfmt) { case balsampear::VideoFormat::PixelFormat::Format_Invalid: break; case balsampear::VideoFormat::PixelFormat::Format_RGB24: result = (size_t)height_ * width_ * 3; break; case balsampear::VideoFormat::PixelFormat::Format_RGBA32: result = (size_t)height_ * width_ * 4; break; case balsampear::VideoFormat::PixelFormat::Format_YUV420P: result = (size_t)height_ * width_ * 3 / 2; break; case balsampear::VideoFormat::PixelFormat::Format_YUV420: result = (size_t)height_ * width_ * 3 / 2; break; default: break; } return result; } void VideoFrame::fill(AVFrame* avframe) { Byte* ptr = (Byte*)data(); VideoFormat::PixelFormat pixelfmt = fmt_.pixelFormat(); size_t redSize = (size_t)width_ * height_; switch (pixelfmt) { case balsampear::VideoFormat::PixelFormat::Format_Invalid: break; case balsampear::VideoFormat::PixelFormat::Format_RGB24: // break; case balsampear::VideoFormat::PixelFormat::Format_RGBA32: break; case balsampear::VideoFormat::PixelFormat::Format_YUV420P: memcpy(ptr, avframe->data[0], redSize); memcpy(ptr + redSize, avframe->data[1], redSize / 4); memcpy(ptr + redSize * 5 / 4, avframe->data[2], redSize / 4); break; case balsampear::VideoFormat::PixelFormat::Format_YUV420: break; default: break; } } }
18.983051
64
0.675893
st0ne77
3969e4ad57cd7679297bbc5cce21695d972e7490
1,164
cpp
C++
AtCoder/ABC073/abc073D.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
1
2020-05-24T02:27:05.000Z
2020-05-24T02:27:05.000Z
AtCoder/ABC073/abc073D.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
AtCoder/ABC073/abc073D.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <algorithm> using namespace std; #define REP(i, n) for (int i = 0; i < n; ++i) int main() { int N; // 200 int M; // N * (N - 1) / 2 int R; // min(8, N) scanf("%d %d %d", &N, &M, &R); vector<int> r; REP(i, R) { int ri = 0; scanf("%d", &ri); ri--; r.push_back(ri); } sort(r.begin(), r.end()); int d[N][N]; REP(i, N) REP(j, N) { d[i][j] = 1e9; } REP(i, M) { int A, B; int C; // 町 Ai と町 Bi の間の距離, 1e5 scanf("%d %d %d", &A, &B, &C); A--; B--; if (d[A][B] > C) d[A][B] = d[B][A] = C; } REP(k, N) REP(i, N) REP(j, N) { if (d[i][j] > d[i][k] + d[k][j]) { d[i][j] = d[i][k] + d[k][j]; } } int ans = 1e9; do { // REP(i, R - 1) { // printf("%d, ", r[i]); // } // printf("%d\n", r[R - 1]); int temp = 0; REP(i, R - 1) { temp += d[r[i]][r[i + 1]]; } ans = min(ans, temp); } while(next_permutation(r.begin(), r.end())); printf("%d\n", ans); return 0; }
19.081967
50
0.356529
t-mochizuki
3969ee9adabe298632095808d5468875063dd0a2
1,231
cpp
C++
Projects/bouncesim/Shape.cpp
ZetaFuntime/MenuEditor
4953cb675fc99047c186e3147402732a1dd955ce
[ "MIT" ]
null
null
null
Projects/bouncesim/Shape.cpp
ZetaFuntime/MenuEditor
4953cb675fc99047c186e3147402732a1dd955ce
[ "MIT" ]
null
null
null
Projects/bouncesim/Shape.cpp
ZetaFuntime/MenuEditor
4953cb675fc99047c186e3147402732a1dd955ce
[ "MIT" ]
null
null
null
#include "Shape.h" #include <Texture.h> #include "SpriteNode.h" #include "Input.h" Shape::Shape() { //Put the textures here m_angryTex = new aie::Texture("./textures/angery.png"); //m_turretTexture = new aie::Texture("./sceneGraph/textures/barrelGreen.png"); //m_turret = new SpriteNode(m_turretTexture); //m_turret->Translate(Vector2(0, 0)); //m_turret->SetOrigin(Vector2(0.0f, 0.5f)); // Circle Texture + Node rotation m_ball = new SpriteNode(m_angryTex); m_ball->Rotate(3.14159f / 4.0f); // 90 degrees //Parent setups //m_turret->SetParent(m_base); //m_base->SetParent(this); } Shape::~Shape() { delete m_ball; delete m_angryTex; } void Shape::Update(float deltaTime) { aie::Input* input = aie::Input::getInstance(); } void Shape::Render(aie::Renderer2D *renderer) { m_ball->Render(renderer); m_turret->Render(renderer); } //void Shape::SetTurretRotate(float p_radians) //{ // float bRads = m_base->GetLocalRotation(); // m_turret->setLocalMatrix(p_radians - bRads); //} void Shape::SetBaseRotate(float p_radians) { m_ball->setLocalMatrix(p_radians); } void Shape::SetBaseTranslate(Vector2 p_move) { m_ball->Translate(p_move); } float Shape::GetBaseRotate() { return m_ball->GetLocalRotation(); }
19.854839
79
0.711617
ZetaFuntime
396e87583ecf14610b1b0caf0587d4cd566840d3
4,976
cc
C++
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/DeleteCustomizations.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/DeleteCustomizations.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/DeleteCustomizations.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* Copyright(c) Sophist Solutions Inc. 1991-1992. All rights reserved */ /* * $Header: /fuji/lewis/RCS/DeleteCustomizations.cc,v 1.6 1992/09/08 16:40:43 lewis Exp $ * * Description: * * To Do: * * $Log: DeleteCustomizations.cc,v $ * Revision 1.6 1992/09/08 16:40:43 lewis * Renamed NULL -> Nil. * * Revision 1.5 1992/09/01 17:25:44 sterling * Lots of Foundation changes. * * Revision 1.4 1992/07/21 18:28:39 sterling * hi * * Revision 1.3 1992/07/16 15:24:40 sterling * hi * * Revision 1.2 1992/06/25 10:15:58 sterling * *** empty log message *** * * Revision 1.9 1992/05/19 11:35:43 sterling * hi * * Revision 1.8 92/05/13 18:47:01 18:47:01 lewis (Lewis Pringle) * STERL. * * Revision 1.3 1992/03/06 21:52:58 sterling * motif * * */ // text before here will be retained: Do not remove or modify this line!!! #include "Language.hh" #include "Shape.hh" #include "DeleteCustomizations.hh" DeleteCustomizationsX::DeleteCustomizationsX () : fField1 (), fCustomizations () { #if qMacUI BuildForMacUI (); #elif qMotifUI BuildForMotifUI (); #else BuildForUnknownGUI (); #endif /* GUI */ } DeleteCustomizationsX::~DeleteCustomizationsX () { RemoveSubView (&fField1); RemoveSubView (&fCustomizations); } #if qMacUI void DeleteCustomizationsX::BuildForMacUI () { SetSize (Point (184, 230), eNoUpdate); fField1.SetExtent (2, -1, 35, 229, eNoUpdate); fField1.SetFont (&kSystemFont); fField1.SetEditMode (AbstractTextEdit::eDisplayOnly); fField1.SetBorder (0, 0, eNoUpdate); fField1.SetMargin (0, 0, eNoUpdate); fField1.SetText ("Which customizations would you like to delete?"); AddSubView (&fField1); fCustomizations.SetExtent (37, 1, 143, 226, eNoUpdate); fCustomizations.SetAllowMultipleSelections (True); fCustomizations.SetController (this); AddSubView (&fCustomizations); } #elif qMotifUI void DeleteCustomizationsX::BuildForMotifUI () { SetSize (Point (184, 230), eNoUpdate); fField1.SetExtent (2, -1, 35, 229, eNoUpdate); fField1.SetFont (&kSystemFont); fField1.SetEditMode (AbstractTextEdit::eDisplayOnly); fField1.SetBorder (0, 0, eNoUpdate); fField1.SetMargin (0, 0, eNoUpdate); fField1.SetText ("Which customizations would you like to delete?"); AddSubView (&fField1); fCustomizations.SetExtent (37, 1, 143, 226, eNoUpdate); fCustomizations.SetAllowMultipleSelections (True); fCustomizations.SetController (this); AddSubView (&fCustomizations); AddFocus (&fCustomizations); } #else void DeleteCustomizationsX::BuildForUnknownGUI (); { SetSize (Point (184, 230), eNoUpdate); fField1.SetExtent (2, -1, 35, 229, eNoUpdate); fField1.SetFont (&kSystemFont); fField1.SetEditMode (AbstractTextEdit::eDisplayOnly); fField1.SetBorder (0, 0, eNoUpdate); fField1.SetMargin (0, 0, eNoUpdate); fField1.SetText ("Which customizations would you like to delete?"); AddSubView (&fField1); fCustomizations.SetExtent (37, 1, 143, 226, eNoUpdate); fCustomizations.SetAllowMultipleSelections (True); fCustomizations.SetController (this); AddSubView (&fCustomizations); } #endif /* GUI */ Point DeleteCustomizationsX::CalcDefaultSize_ (const Point& /*defaultSize*/) const { #if qMacUI return (Point (184, 230)); #elif qMotifUI return (Point (184, 230)); #else return (Point (184, 230)); #endif /* GUI */ } void DeleteCustomizationsX::Layout () { const Point kSizeDelta = CalcDefaultSize () - GetSize (); static const Point kOriginalfField1Size = fField1.GetSize (); fField1.SetSize (kOriginalfField1Size - Point (kSizeDelta.GetV (), kSizeDelta.GetH ())); static const Point kOriginalfCustomizationsSize = fCustomizations.GetSize (); fCustomizations.SetSize (kOriginalfCustomizationsSize - Point (kSizeDelta.GetV (), kSizeDelta.GetH ())); View::Layout (); } // text past here will be retained: Do not remove or modify this line!!! #include "Dialog.hh" #include "Shell.hh" #include "PushButton.hh" DeleteCustomizations::DeleteCustomizations () { } DeleteCustomizationsDialog::DeleteCustomizationsDialog () : Dialog (new StandardDialogWindowShell ()), fDeleteCustomizations (Nil), fDialogMainView (Nil) { fDeleteCustomizations = new DeleteCustomizations (); fDeleteCustomizations->SetController (this); SetMainView (fDialogMainView = new DialogMainView (*this, *fDeleteCustomizations, "Delete", AbstractPushButton::kCancelLabel)); SetDefaultButton (GetOKButton ()); GetOKButton ()->SetEnabled (False); } DeleteCustomizationsDialog::~DeleteCustomizationsDialog () { SetMainView (Nil); delete fDialogMainView; delete fDeleteCustomizations; } StringPickList& DeleteCustomizationsDialog::GetCustomizationList () const { AssertNotNil (fDeleteCustomizations); return (fDeleteCustomizations->GetCustomizationList ()); } void DeleteCustomizationsDialog::ButtonPressed (AbstractButton* button) { GetOKButton ()->SetEnabled (Boolean (GetCustomizationList ().CountSelected () > 0)); Dialog::ButtonPressed (button); }
25.649485
128
0.7291
SophistSolutions
397796bbf49125430b647a8a05314d62ee8fdb4e
370,346
cc
C++
bindings/CPP-Kramer/source/PrimitivesClasses.cc
QualityInformationFramework/qif-community
d1ee5fbe6c126ef7f25ab5f8653b35d7daa4c0b4
[ "BSL-1.0" ]
23
2017-10-26T22:51:59.000Z
2022-01-12T04:05:58.000Z
bindings/CPP-Kramer/source/PrimitivesClasses.cc
QualityInformationFramework/qif-community
d1ee5fbe6c126ef7f25ab5f8653b35d7daa4c0b4
[ "BSL-1.0" ]
11
2018-03-23T08:49:44.000Z
2022-02-03T20:50:34.000Z
bindings/CPP-Kramer/source/PrimitivesClasses.cc
QualityInformationFramework/qif-community
d1ee5fbe6c126ef7f25ab5f8653b35d7daa4c0b4
[ "BSL-1.0" ]
15
2017-09-25T12:10:20.000Z
2021-05-17T10:01:13.000Z
/* ***************************************************************** */ #include <stdio.h> // for printf, etc. #include <string.h> // for strdup #include <stdlib.h> // for exit #include <list> #include <boost/regex.hpp> #include <xmlSchemaInstance.hh> #include "PrimitivesClasses.hh" #define INDENT 2 /* ***************************************************************** */ /* ***************************************************************** */ /* class AngleRangeType */ AngleRangeType::AngleRangeType() : D2Type() { angularUnit = 0; } AngleRangeType::AngleRangeType( XmlDouble * aXmlDouble) : D2Type(aXmlDouble) { angularUnit = 0; } AngleRangeType::AngleRangeType( XmlToken * angularUnitIn, XmlDouble * aXmlDouble) : D2Type(aXmlDouble) { angularUnit = angularUnitIn; } AngleRangeType::~AngleRangeType() { #ifndef NODESTRUCT delete angularUnit; #endif } void AngleRangeType::printName(FILE * outFile) { fprintf(outFile, "AngleRangeType"); } void AngleRangeType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; AngleRangeTypeCheck(); if (bad) { fprintf(stderr, "AngleRangeTypeCheck failed\n"); exit(1); } if (angularUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "angularUnit=\""); angularUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool AngleRangeType::AngleRangeTypeCheck() { D2TypeCheck(); return bad; } bool AngleRangeType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "angularUnit") { XmlToken * angularUnitVal; if (angularUnit) { fprintf(stderr, "two values for angularUnit in AngleRangeType\n"); returnValue = true; break; } angularUnitVal = new XmlToken(decl->val.c_str()); if (angularUnitVal->bad) { delete angularUnitVal; fprintf(stderr, "bad value %s for angularUnit in AngleRangeType\n", decl->val.c_str()); returnValue = true; break; } else angularUnit = angularUnitVal; } else { fprintf(stderr, "bad attribute in AngleRangeType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete angularUnit; angularUnit = 0; } return returnValue; } XmlToken * AngleRangeType::getangularUnit() {return angularUnit;} void AngleRangeType::setangularUnit(XmlToken * angularUnitIn) {angularUnit = angularUnitIn;} /* ***************************************************************** */ /* class ArrayBinaryQIFReferenceFullType */ ArrayBinaryQIFReferenceFullType::ArrayBinaryQIFReferenceFullType() : ArrayBinaryQIFReferenceType() { asmPathId = 0; asmPathXId = 0; } ArrayBinaryQIFReferenceFullType::ArrayBinaryQIFReferenceFullType( ArrayBinaryQIFReferenceTypeChoicePair * ArrayBinaryQIFReferenceTypePairIn) : ArrayBinaryQIFReferenceType( ArrayBinaryQIFReferenceTypePairIn) { asmPathId = 0; asmPathXId = 0; } ArrayBinaryQIFReferenceFullType::ArrayBinaryQIFReferenceFullType( ArrayBinaryQIFReferenceTypeChoicePair * ArrayBinaryQIFReferenceTypePairIn, QIFReferenceSimpleType * asmPathIdIn, QIFReferenceSimpleType * asmPathXIdIn) : ArrayBinaryQIFReferenceType( ArrayBinaryQIFReferenceTypePairIn) { asmPathId = asmPathIdIn; asmPathXId = asmPathXIdIn; } ArrayBinaryQIFReferenceFullType::~ArrayBinaryQIFReferenceFullType() { #ifndef NODESTRUCT delete asmPathId; delete asmPathXId; #endif } void ArrayBinaryQIFReferenceFullType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (asmPathId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathId=\""); asmPathId->oPrintSelf(outFile); fprintf(outFile, "\""); } if (asmPathXId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathXId=\""); asmPathXId->oPrintSelf(outFile); fprintf(outFile, "\""); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); ArrayBinaryQIFReferenceTypePair->printSelf(outFile); doSpaces(-INDENT, outFile); } bool ArrayBinaryQIFReferenceFullType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "asmPathId") { QIFReferenceSimpleType * asmPathIdVal; if (asmPathId) { fprintf(stderr, "two values for asmPathId in ArrayBinaryQIFReferenceFullType\n"); returnValue = true; break; } asmPathIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathIdVal->bad) { delete asmPathIdVal; fprintf(stderr, "bad value %s for asmPathId in ArrayBinaryQIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathId = asmPathIdVal; } else if (decl->name == "asmPathXId") { QIFReferenceSimpleType * asmPathXIdVal; if (asmPathXId) { fprintf(stderr, "two values for asmPathXId in ArrayBinaryQIFReferenceFullType\n"); returnValue = true; break; } asmPathXIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathXIdVal->bad) { delete asmPathXIdVal; fprintf(stderr, "bad value %s for asmPathXId in ArrayBinaryQIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathXId = asmPathXIdVal; } else { fprintf(stderr, "bad attribute in ArrayBinaryQIFReferenceFullType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete asmPathId; asmPathId = 0; delete asmPathXId; asmPathXId = 0; } return returnValue; } QIFReferenceSimpleType * ArrayBinaryQIFReferenceFullType::getasmPathId() {return asmPathId;} void ArrayBinaryQIFReferenceFullType::setasmPathId(QIFReferenceSimpleType * asmPathIdIn) {asmPathId = asmPathIdIn;} QIFReferenceSimpleType * ArrayBinaryQIFReferenceFullType::getasmPathXId() {return asmPathXId;} void ArrayBinaryQIFReferenceFullType::setasmPathXId(QIFReferenceSimpleType * asmPathXIdIn) {asmPathXId = asmPathXIdIn;} /* ***************************************************************** */ /* class ArrayBinaryQIFReferenceType */ ArrayBinaryQIFReferenceType::ArrayBinaryQIFReferenceType() { ArrayBinaryQIFReferenceTypePair = 0; } ArrayBinaryQIFReferenceType::ArrayBinaryQIFReferenceType( ArrayBinaryQIFReferenceTypeChoicePair * ArrayBinaryQIFReferenceTypePairIn) { ArrayBinaryQIFReferenceTypePair = ArrayBinaryQIFReferenceTypePairIn; } ArrayBinaryQIFReferenceType::~ArrayBinaryQIFReferenceType() { #ifndef NODESTRUCT delete ArrayBinaryQIFReferenceTypePair; #endif } void ArrayBinaryQIFReferenceType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); ArrayBinaryQIFReferenceTypePair->printSelf(outFile); doSpaces(-INDENT, outFile); } ArrayBinaryQIFReferenceTypeChoicePair * ArrayBinaryQIFReferenceType::getArrayBinaryQIFReferenceTypePair() {return ArrayBinaryQIFReferenceTypePair;} void ArrayBinaryQIFReferenceType::setArrayBinaryQIFReferenceTypePair(ArrayBinaryQIFReferenceTypeChoicePair * ArrayBinaryQIFReferenceTypePairIn) {ArrayBinaryQIFReferenceTypePair = ArrayBinaryQIFReferenceTypePairIn;} /* ***************************************************************** */ /* class ArrayBinaryQIFReferenceTypeChoicePair */ ArrayBinaryQIFReferenceTypeChoicePair::ArrayBinaryQIFReferenceTypeChoicePair() {} ArrayBinaryQIFReferenceTypeChoicePair::ArrayBinaryQIFReferenceTypeChoicePair( whichOne ArrayBinaryQIFReferenceTypeTypeIn, ArrayBinaryQIFReferenceTypeVal ArrayBinaryQIFReferenceTypeValueIn) { ArrayBinaryQIFReferenceTypeType = ArrayBinaryQIFReferenceTypeTypeIn; ArrayBinaryQIFReferenceTypeValue = ArrayBinaryQIFReferenceTypeValueIn; } ArrayBinaryQIFReferenceTypeChoicePair::~ArrayBinaryQIFReferenceTypeChoicePair() { #ifndef NODESTRUCT if (ArrayBinaryQIFReferenceTypeType == IdsE) delete ArrayBinaryQIFReferenceTypeValue.Ids; else if (ArrayBinaryQIFReferenceTypeType == ArrayBinaryQIFR_1001E) delete ArrayBinaryQIFReferenceTypeValue.ArrayBinaryQIFR_1001; #endif } void ArrayBinaryQIFReferenceTypeChoicePair::printSelf(FILE * outFile) { if (ArrayBinaryQIFReferenceTypeType == IdsE) { doSpaces(0, outFile); fprintf(outFile, "<Ids"); ArrayBinaryQIFReferenceTypeValue.Ids->printSelf(outFile); fprintf(outFile, "</Ids>\n"); } else if (ArrayBinaryQIFReferenceTypeType == ArrayBinaryQIFR_1001E) { ArrayBinaryQIFReferenceTypeValue.ArrayBinaryQIFR_1001->printSelf(outFile); } } /* ***************************************************************** */ /* class ArrayBinaryType */ ArrayBinaryType::ArrayBinaryType() { count = 0; sizeElement = 0; val = ""; } ArrayBinaryType::ArrayBinaryType( const char * valStringIn) : XmlBase64Binary(valStringIn) { count = 0; sizeElement = 0; } ArrayBinaryType::ArrayBinaryType( NaturalType * countIn, XmlUnsignedInt * sizeElementIn, const char * valStringIn) : XmlBase64Binary(valStringIn) { count = countIn; sizeElement = sizeElementIn; } ArrayBinaryType::~ArrayBinaryType() { #ifndef NODESTRUCT delete count; delete sizeElement; #endif } void ArrayBinaryType::printName(FILE * outFile) { fprintf(outFile, "ArrayBinaryType"); } void ArrayBinaryType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } if (sizeElement) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "sizeElement=\""); sizeElement->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"sizeElement\" missing\n"); exit(1); } XmlBase64Binary::printSelf(outFile); } bool ArrayBinaryType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayBinaryType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayBinaryType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else if (decl->name == "sizeElement") { XmlUnsignedInt * sizeElementVal; if (sizeElement) { fprintf(stderr, "two values for sizeElement in ArrayBinaryType\n"); returnValue = true; break; } sizeElementVal = new XmlUnsignedInt(decl->val.c_str()); if (sizeElementVal->bad) { delete sizeElementVal; fprintf(stderr, "bad value %s for sizeElement in ArrayBinaryType\n", decl->val.c_str()); returnValue = true; break; } else sizeElement = sizeElementVal; } else { fprintf(stderr, "bad attribute in ArrayBinaryType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayBinaryType\n"); returnValue = true; } if (sizeElement == 0) { fprintf(stderr, "required attribute \"sizeElement\" missing in ArrayBinaryType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; delete sizeElement; sizeElement = 0; } return returnValue; } NaturalType * ArrayBinaryType::getcount() {return count;} void ArrayBinaryType::setcount(NaturalType * countIn) {count = countIn;} XmlUnsignedInt * ArrayBinaryType::getsizeElement() {return sizeElement;} void ArrayBinaryType::setsizeElement(XmlUnsignedInt * sizeElementIn) {sizeElement = sizeElementIn;} /* ***************************************************************** */ /* class ArrayDoubleType */ ArrayDoubleType::ArrayDoubleType() : ListDoubleType() { count = 0; } ArrayDoubleType::ArrayDoubleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = 0; } ArrayDoubleType::ArrayDoubleType( NaturalType * countIn, XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = countIn; } ArrayDoubleType::~ArrayDoubleType() { #ifndef NODESTRUCT delete count; #endif } void ArrayDoubleType::printName(FILE * outFile) { fprintf(outFile, "ArrayDoubleType"); } void ArrayDoubleType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListDoubleType::printSelf(outFile); } bool ArrayDoubleType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayDoubleType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayDoubleType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayDoubleType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayDoubleType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayDoubleType::getcount() {return count;} void ArrayDoubleType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayI2Type */ ArrayI2Type::ArrayI2Type() : ListIntType() { count = 0; } ArrayI2Type::ArrayI2Type( XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = 0; } ArrayI2Type::ArrayI2Type( NaturalType * countIn, XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = countIn; } ArrayI2Type::~ArrayI2Type() { #ifndef NODESTRUCT delete count; #endif } void ArrayI2Type::printName(FILE * outFile) { fprintf(outFile, "ArrayI2Type"); } void ArrayI2Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListIntType::printSelf(outFile); } bool ArrayI2Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayI2Type\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayI2Type\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayI2Type\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayI2Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayI2Type::getcount() {return count;} void ArrayI2Type::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayI3Type */ ArrayI3Type::ArrayI3Type() : ListIntType() { count = 0; } ArrayI3Type::ArrayI3Type( XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = 0; } ArrayI3Type::ArrayI3Type( NaturalType * countIn, XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = countIn; } ArrayI3Type::~ArrayI3Type() { #ifndef NODESTRUCT delete count; #endif } void ArrayI3Type::printName(FILE * outFile) { fprintf(outFile, "ArrayI3Type"); } void ArrayI3Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListIntType::printSelf(outFile); } bool ArrayI3Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayI3Type\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayI3Type\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayI3Type\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayI3Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayI3Type::getcount() {return count;} void ArrayI3Type::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayIntType */ ArrayIntType::ArrayIntType() : ListIntType() { count = 0; } ArrayIntType::ArrayIntType( XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = 0; } ArrayIntType::ArrayIntType( NaturalType * countIn, XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { count = countIn; } ArrayIntType::~ArrayIntType() { #ifndef NODESTRUCT delete count; #endif } void ArrayIntType::printName(FILE * outFile) { fprintf(outFile, "ArrayIntType"); } void ArrayIntType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListIntType::printSelf(outFile); } bool ArrayIntType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayIntType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayIntType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayIntType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayIntType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayIntType::getcount() {return count;} void ArrayIntType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayNaturalType */ ArrayNaturalType::ArrayNaturalType() : ListNaturalType() { count = 0; } ArrayNaturalType::ArrayNaturalType( NaturalType * aNaturalType) : ListNaturalType(aNaturalType) { count = 0; } ArrayNaturalType::ArrayNaturalType( NaturalType * countIn, NaturalType * aNaturalType) : ListNaturalType(aNaturalType) { count = countIn; } ArrayNaturalType::~ArrayNaturalType() { #ifndef NODESTRUCT delete count; #endif } void ArrayNaturalType::printName(FILE * outFile) { fprintf(outFile, "ArrayNaturalType"); } void ArrayNaturalType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListNaturalType::printSelf(outFile); } bool ArrayNaturalType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayNaturalType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayNaturalType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayNaturalType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayNaturalType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayNaturalType::getcount() {return count;} void ArrayNaturalType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayPairReferenceFullType */ ArrayPairReferenceFullType::ArrayPairReferenceFullType() { n = 0; FeaturePair = 0; } ArrayPairReferenceFullType::ArrayPairReferenceFullType( QIFFeaturePairTypeLisd * FeaturePairIn) { n = 0; FeaturePair = FeaturePairIn; } ArrayPairReferenceFullType::ArrayPairReferenceFullType( NaturalType * nIn, QIFFeaturePairTypeLisd * FeaturePairIn) { n = nIn; FeaturePair = FeaturePairIn; } ArrayPairReferenceFullType::~ArrayPairReferenceFullType() { #ifndef NODESTRUCT delete n; delete FeaturePair; #endif } void ArrayPairReferenceFullType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!FeaturePair) { fprintf(stderr, "FeaturePair list is missing\n"); exit(1); } if (FeaturePair->size() == 0) { fprintf(stderr, "FeaturePair list is empty\n"); exit(1); } std::list<QIFFeaturePairType *>::iterator iter; for (iter = FeaturePair->begin(); iter != FeaturePair->end(); iter++) { doSpaces(0, outFile); fprintf(outFile, "<FeaturePair"); (*iter)->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</FeaturePair>\n"); } } doSpaces(-INDENT, outFile); } bool ArrayPairReferenceFullType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ArrayPairReferenceFullType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ArrayPairReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ArrayPairReferenceFullType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ArrayPairReferenceFullType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ArrayPairReferenceFullType::getn() {return n;} void ArrayPairReferenceFullType::setn(NaturalType * nIn) {n = nIn;} QIFFeaturePairTypeLisd * ArrayPairReferenceFullType::getFeaturePair() {return FeaturePair;} void ArrayPairReferenceFullType::setFeaturePair(QIFFeaturePairTypeLisd * FeaturePairIn) {FeaturePair = FeaturePairIn;} /* ***************************************************************** */ /* class ArrayPoint2dType */ ArrayPoint2dType::ArrayPoint2dType() : ListDoubleType() { count = 0; } ArrayPoint2dType::ArrayPoint2dType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = 0; } ArrayPoint2dType::ArrayPoint2dType( NaturalType * countIn, XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = countIn; } ArrayPoint2dType::~ArrayPoint2dType() { #ifndef NODESTRUCT delete count; #endif } void ArrayPoint2dType::printName(FILE * outFile) { fprintf(outFile, "ArrayPoint2dType"); } void ArrayPoint2dType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListDoubleType::printSelf(outFile); } bool ArrayPoint2dType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayPoint2dType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayPoint2dType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayPoint2dType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayPoint2dType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayPoint2dType::getcount() {return count;} void ArrayPoint2dType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class ArrayPointType */ ArrayPointType::ArrayPointType() : ListDoubleType() { count = 0; decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } ArrayPointType::ArrayPointType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = 0; decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } ArrayPointType::ArrayPointType( NaturalType * countIn, XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = countIn; decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } ArrayPointType::~ArrayPointType() { #ifndef NODESTRUCT delete count; delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void ArrayPointType::printName(FILE * outFile) { fprintf(outFile, "ArrayPointType"); } void ArrayPointType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool ArrayPointType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayPointType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in ArrayPointType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in ArrayPointType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in ArrayPointType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in ArrayPointType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in ArrayPointType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in ArrayPointType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in ArrayPointType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in ArrayPointType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in ArrayPointType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in ArrayPointType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in ArrayPointType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in ArrayPointType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in ArrayPointType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in ArrayPointType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in ArrayPointType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayPointType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } NaturalType * ArrayPointType::getcount() {return count;} void ArrayPointType::setcount(NaturalType * countIn) {count = countIn;} XmlNonNegativeInteger * ArrayPointType::getdecimalPlaces() {return decimalPlaces;} void ArrayPointType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * ArrayPointType::getlinearUnit() {return linearUnit;} void ArrayPointType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * ArrayPointType::getsignificantFigures() {return significantFigures;} void ArrayPointType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * ArrayPointType::getvalidity() {return validity;} void ArrayPointType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * ArrayPointType::getxDecimalPlaces() {return xDecimalPlaces;} void ArrayPointType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * ArrayPointType::getxSignificantFigures() {return xSignificantFigures;} void ArrayPointType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * ArrayPointType::getxValidity() {return xValidity;} void ArrayPointType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * ArrayPointType::getyDecimalPlaces() {return yDecimalPlaces;} void ArrayPointType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * ArrayPointType::getySignificantFigures() {return ySignificantFigures;} void ArrayPointType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * ArrayPointType::getyValidity() {return yValidity;} void ArrayPointType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * ArrayPointType::getzDecimalPlaces() {return zDecimalPlaces;} void ArrayPointType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * ArrayPointType::getzSignificantFigures() {return zSignificantFigures;} void ArrayPointType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * ArrayPointType::getzValidity() {return zValidity;} void ArrayPointType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class ArrayQPIdFullReferenceType */ ArrayQPIdFullReferenceType::ArrayQPIdFullReferenceType() { n = 0; QPId = 0; } ArrayQPIdFullReferenceType::ArrayQPIdFullReferenceType( QPIdFullReferenceTypeLisd * QPIdIn) { n = 0; QPId = QPIdIn; } ArrayQPIdFullReferenceType::ArrayQPIdFullReferenceType( NaturalType * nIn, QPIdFullReferenceTypeLisd * QPIdIn) { n = nIn; QPId = QPIdIn; } ArrayQPIdFullReferenceType::~ArrayQPIdFullReferenceType() { #ifndef NODESTRUCT delete n; delete QPId; #endif } void ArrayQPIdFullReferenceType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!QPId) { fprintf(stderr, "QPId list is missing\n"); exit(1); } if (QPId->size() == 0) { fprintf(stderr, "QPId list is empty\n"); exit(1); } std::list<QPIdFullReferenceType *>::iterator iter; for (iter = QPId->begin(); iter != QPId->end(); iter++) { doSpaces(0, outFile); fprintf(outFile, "<QPId"); (*iter)->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</QPId>\n"); } } doSpaces(-INDENT, outFile); } bool ArrayQPIdFullReferenceType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ArrayQPIdFullReferenceType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ArrayQPIdFullReferenceType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ArrayQPIdFullReferenceType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ArrayQPIdFullReferenceType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ArrayQPIdFullReferenceType::getn() {return n;} void ArrayQPIdFullReferenceType::setn(NaturalType * nIn) {n = nIn;} QPIdFullReferenceTypeLisd * ArrayQPIdFullReferenceType::getQPId() {return QPId;} void ArrayQPIdFullReferenceType::setQPId(QPIdFullReferenceTypeLisd * QPIdIn) {QPId = QPIdIn;} /* ***************************************************************** */ /* class ArrayQPIdFullReferenceTypeLisd */ ArrayQPIdFullReferenceTypeLisd::ArrayQPIdFullReferenceTypeLisd() {} ArrayQPIdFullReferenceTypeLisd::ArrayQPIdFullReferenceTypeLisd(ArrayQPIdFullReferenceType * aArrayQPIdFullReferenceType) { push_back(aArrayQPIdFullReferenceType); } ArrayQPIdFullReferenceTypeLisd::~ArrayQPIdFullReferenceTypeLisd() { #ifndef NODESTRUCT std::list<ArrayQPIdFullReferenceType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void ArrayQPIdFullReferenceTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class ArrayReferenceActiveType */ ArrayReferenceActiveType::ArrayReferenceActiveType() { n = 0; Id = 0; } ArrayReferenceActiveType::ArrayReferenceActiveType( QIFReferenceActiveTypeLisd * IdIn) { n = 0; Id = IdIn; } ArrayReferenceActiveType::ArrayReferenceActiveType( NaturalType * nIn, QIFReferenceActiveTypeLisd * IdIn) { n = nIn; Id = IdIn; } ArrayReferenceActiveType::~ArrayReferenceActiveType() { #ifndef NODESTRUCT delete n; delete Id; #endif } void ArrayReferenceActiveType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!Id) { fprintf(stderr, "Id list is missing\n"); exit(1); } if (Id->size() == 0) { fprintf(stderr, "Id list is empty\n"); exit(1); } std::list<QIFReferenceActiveType *>::iterator iter; for (iter = Id->begin(); iter != Id->end(); iter++) { doSpaces(0, outFile); fprintf(outFile, "<Id"); (*iter)->printSelf(outFile); fprintf(outFile, "</Id>\n"); } } doSpaces(-INDENT, outFile); } bool ArrayReferenceActiveType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ArrayReferenceActiveType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ArrayReferenceActiveType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ArrayReferenceActiveType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ArrayReferenceActiveType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ArrayReferenceActiveType::getn() {return n;} void ArrayReferenceActiveType::setn(NaturalType * nIn) {n = nIn;} QIFReferenceActiveTypeLisd * ArrayReferenceActiveType::getId() {return Id;} void ArrayReferenceActiveType::setId(QIFReferenceActiveTypeLisd * IdIn) {Id = IdIn;} /* ***************************************************************** */ /* class ArrayReferenceFullType */ ArrayReferenceFullType::ArrayReferenceFullType() { n = 0; Id = 0; } ArrayReferenceFullType::ArrayReferenceFullType( QIFReferenceFullTypeLisd * IdIn) { n = 0; Id = IdIn; } ArrayReferenceFullType::ArrayReferenceFullType( NaturalType * nIn, QIFReferenceFullTypeLisd * IdIn) { n = nIn; Id = IdIn; } ArrayReferenceFullType::~ArrayReferenceFullType() { #ifndef NODESTRUCT delete n; delete Id; #endif } void ArrayReferenceFullType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!Id) { fprintf(stderr, "Id list is missing\n"); exit(1); } if (Id->size() == 0) { fprintf(stderr, "Id list is empty\n"); exit(1); } std::list<QIFReferenceFullType *>::iterator iter; for (iter = Id->begin(); iter != Id->end(); iter++) { doSpaces(0, outFile); fprintf(outFile, "<Id"); (*iter)->printSelf(outFile); fprintf(outFile, "</Id>\n"); } } doSpaces(-INDENT, outFile); } bool ArrayReferenceFullType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ArrayReferenceFullType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ArrayReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ArrayReferenceFullType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ArrayReferenceFullType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ArrayReferenceFullType::getn() {return n;} void ArrayReferenceFullType::setn(NaturalType * nIn) {n = nIn;} QIFReferenceFullTypeLisd * ArrayReferenceFullType::getId() {return Id;} void ArrayReferenceFullType::setId(QIFReferenceFullTypeLisd * IdIn) {Id = IdIn;} /* ***************************************************************** */ /* class ArrayReferenceType */ ArrayReferenceType::ArrayReferenceType() { n = 0; Id = 0; } ArrayReferenceType::ArrayReferenceType( QIFReferenceTypeLisd * IdIn) { n = 0; Id = IdIn; } ArrayReferenceType::ArrayReferenceType( NaturalType * nIn, QIFReferenceTypeLisd * IdIn) { n = nIn; Id = IdIn; } ArrayReferenceType::~ArrayReferenceType() { #ifndef NODESTRUCT delete n; delete Id; #endif } void ArrayReferenceType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!Id) { fprintf(stderr, "Id list is missing\n"); exit(1); } if (Id->size() == 0) { fprintf(stderr, "Id list is empty\n"); exit(1); } std::list<QIFReferenceType *>::iterator iter; for (iter = Id->begin(); iter != Id->end(); iter++) { doSpaces(0, outFile); fprintf(outFile, "<Id"); (*iter)->printSelf(outFile); fprintf(outFile, "</Id>\n"); } } doSpaces(-INDENT, outFile); } bool ArrayReferenceType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ArrayReferenceType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ArrayReferenceType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ArrayReferenceType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ArrayReferenceType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ArrayReferenceType::getn() {return n;} void ArrayReferenceType::setn(NaturalType * nIn) {n = nIn;} QIFReferenceTypeLisd * ArrayReferenceType::getId() {return Id;} void ArrayReferenceType::setId(QIFReferenceTypeLisd * IdIn) {Id = IdIn;} /* ***************************************************************** */ /* class ArrayUnitVectorType */ ArrayUnitVectorType::ArrayUnitVectorType() : ListDoubleType() { count = 0; decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } ArrayUnitVectorType::ArrayUnitVectorType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = 0; decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } ArrayUnitVectorType::ArrayUnitVectorType( NaturalType * countIn, XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { count = countIn; decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } ArrayUnitVectorType::~ArrayUnitVectorType() { #ifndef NODESTRUCT delete count; delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void ArrayUnitVectorType::printName(FILE * outFile) { fprintf(outFile, "ArrayUnitVectorType"); } void ArrayUnitVectorType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool ArrayUnitVectorType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayUnitVectorType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in ArrayUnitVectorType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in ArrayUnitVectorType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in ArrayUnitVectorType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in ArrayUnitVectorType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in ArrayUnitVectorType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in ArrayUnitVectorType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in ArrayUnitVectorType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in ArrayUnitVectorType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in ArrayUnitVectorType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in ArrayUnitVectorType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in ArrayUnitVectorType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in ArrayUnitVectorType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in ArrayUnitVectorType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in ArrayUnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in ArrayUnitVectorType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayUnitVectorType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } NaturalType * ArrayUnitVectorType::getcount() {return count;} void ArrayUnitVectorType::setcount(NaturalType * countIn) {count = countIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getdecimalPlaces() {return decimalPlaces;} void ArrayUnitVectorType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * ArrayUnitVectorType::getlinearUnit() {return linearUnit;} void ArrayUnitVectorType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getsignificantFigures() {return significantFigures;} void ArrayUnitVectorType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * ArrayUnitVectorType::getvalidity() {return validity;} void ArrayUnitVectorType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getxDecimalPlaces() {return xDecimalPlaces;} void ArrayUnitVectorType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getxSignificantFigures() {return xSignificantFigures;} void ArrayUnitVectorType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * ArrayUnitVectorType::getxValidity() {return xValidity;} void ArrayUnitVectorType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getyDecimalPlaces() {return yDecimalPlaces;} void ArrayUnitVectorType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getySignificantFigures() {return ySignificantFigures;} void ArrayUnitVectorType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * ArrayUnitVectorType::getyValidity() {return yValidity;} void ArrayUnitVectorType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getzDecimalPlaces() {return zDecimalPlaces;} void ArrayUnitVectorType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * ArrayUnitVectorType::getzSignificantFigures() {return zSignificantFigures;} void ArrayUnitVectorType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * ArrayUnitVectorType::getzValidity() {return zValidity;} void ArrayUnitVectorType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class ArrayUnsignedByteType */ ArrayUnsignedByteType::ArrayUnsignedByteType() : ListUnsignedByteType() { count = 0; } ArrayUnsignedByteType::ArrayUnsignedByteType( XmlUnsignedByte * aXmlUnsignedByte) : ListUnsignedByteType(aXmlUnsignedByte) { count = 0; } ArrayUnsignedByteType::ArrayUnsignedByteType( NaturalType * countIn, XmlUnsignedByte * aXmlUnsignedByte) : ListUnsignedByteType(aXmlUnsignedByte) { count = countIn; } ArrayUnsignedByteType::~ArrayUnsignedByteType() { #ifndef NODESTRUCT delete count; #endif } void ArrayUnsignedByteType::printName(FILE * outFile) { fprintf(outFile, "ArrayUnsignedByteType"); } void ArrayUnsignedByteType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } ListUnsignedByteType::printSelf(outFile); } bool ArrayUnsignedByteType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in ArrayUnsignedByteType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in ArrayUnsignedByteType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in ArrayUnsignedByteType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in ArrayUnsignedByteType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * ArrayUnsignedByteType::getcount() {return count;} void ArrayUnsignedByteType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class AttributeBaseType */ AttributeBaseType::AttributeBaseType() { name = 0; } AttributeBaseType::AttributeBaseType( XmlString * nameIn) { name = nameIn; } AttributeBaseType::~AttributeBaseType() { delete name; } void AttributeBaseType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeBaseType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeBaseType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeBaseType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else { fprintf(stderr, "bad attribute in AttributeBaseType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeBaseType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; } return returnValue; } XmlString * AttributeBaseType::getname() {return name;} void AttributeBaseType::setname(XmlString * nameIn) {name = nameIn;} /* ***************************************************************** */ /* class AttributeBaseTypeLisd */ AttributeBaseTypeLisd::AttributeBaseTypeLisd() {} AttributeBaseTypeLisd::AttributeBaseTypeLisd(AttributeBaseType * aAttributeBaseType) { push_back(aAttributeBaseType); } AttributeBaseTypeLisd::~AttributeBaseTypeLisd() { #ifndef NODESTRUCT std::list<AttributeBaseType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void AttributeBaseTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class AttributeBoolType */ AttributeBoolType::AttributeBoolType() : AttributeBaseType() { value = 0; } AttributeBoolType::AttributeBoolType( XmlString * nameIn, XmlBoolean * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeBoolType::~AttributeBoolType() { #ifndef NODESTRUCT delete value; #endif } void AttributeBoolType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeBoolType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeBoolType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeBoolType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { XmlBoolean * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeBoolType\n"); returnValue = true; break; } valueVal = new XmlBoolean(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeBoolType\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeBoolType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeBoolType\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeBoolType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } XmlBoolean * AttributeBoolType::getvalue() {return value;} void AttributeBoolType::setvalue(XmlBoolean * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeD1Type */ AttributeD1Type::AttributeD1Type() : AttributeBaseType() { value = 0; } AttributeD1Type::AttributeD1Type( XmlString * nameIn, XmlDouble * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeD1Type::~AttributeD1Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeD1Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeD1Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeD1Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeD1Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { XmlDouble * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeD1Type\n"); returnValue = true; break; } valueVal = new XmlDouble(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeD1Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeD1Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeD1Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeD1Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } XmlDouble * AttributeD1Type::getvalue() {return value;} void AttributeD1Type::setvalue(XmlDouble * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeD2Type */ AttributeD2Type::AttributeD2Type() : AttributeBaseType() { value = 0; } AttributeD2Type::AttributeD2Type( XmlString * nameIn, D2Type * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeD2Type::~AttributeD2Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeD2Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeD2Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeD2Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeD2Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { D2Type * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeD2Type\n"); returnValue = true; break; } valueVal = new D2Type(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeD2Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeD2Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeD2Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeD2Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } D2Type * AttributeD2Type::getvalue() {return value;} void AttributeD2Type::setvalue(D2Type * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeD3Type */ AttributeD3Type::AttributeD3Type() : AttributeBaseType() { value = 0; } AttributeD3Type::AttributeD3Type( XmlString * nameIn, D3Type * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeD3Type::~AttributeD3Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeD3Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeD3Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeD3Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeD3Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { D3Type * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeD3Type\n"); returnValue = true; break; } valueVal = new D3Type(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeD3Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeD3Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeD3Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeD3Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } D3Type * AttributeD3Type::getvalue() {return value;} void AttributeD3Type::setvalue(D3Type * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeI1Type */ AttributeI1Type::AttributeI1Type() : AttributeBaseType() { value = 0; } AttributeI1Type::AttributeI1Type( XmlString * nameIn, XmlInteger * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeI1Type::~AttributeI1Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeI1Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeI1Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeI1Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeI1Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { XmlInteger * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeI1Type\n"); returnValue = true; break; } valueVal = new XmlInteger(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeI1Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeI1Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeI1Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeI1Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } XmlInteger * AttributeI1Type::getvalue() {return value;} void AttributeI1Type::setvalue(XmlInteger * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeI2Type */ AttributeI2Type::AttributeI2Type() : AttributeBaseType() { value = 0; } AttributeI2Type::AttributeI2Type( XmlString * nameIn, I2Type * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeI2Type::~AttributeI2Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeI2Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeI2Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeI2Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeI2Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { I2Type * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeI2Type\n"); returnValue = true; break; } valueVal = new I2Type(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeI2Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeI2Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeI2Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeI2Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } I2Type * AttributeI2Type::getvalue() {return value;} void AttributeI2Type::setvalue(I2Type * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeI3Type */ AttributeI3Type::AttributeI3Type() : AttributeBaseType() { value = 0; } AttributeI3Type::AttributeI3Type( XmlString * nameIn, I3Type * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeI3Type::~AttributeI3Type() { #ifndef NODESTRUCT delete value; #endif } void AttributeI3Type::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeI3Type::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeI3Type\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeI3Type\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { I3Type * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeI3Type\n"); returnValue = true; break; } valueVal = new I3Type(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeI3Type\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeI3Type\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeI3Type\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeI3Type\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } I3Type * AttributeI3Type::getvalue() {return value;} void AttributeI3Type::setvalue(I3Type * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeQPIdType */ AttributeQPIdType::AttributeQPIdType() : AttributeBaseType() { Value = 0; } AttributeQPIdType::AttributeQPIdType( QPIdType * ValueIn) : AttributeBaseType() { Value = ValueIn; } AttributeQPIdType::AttributeQPIdType( XmlString * nameIn, QPIdType * ValueIn) : AttributeBaseType( nameIn) { Value = ValueIn; } AttributeQPIdType::~AttributeQPIdType() { #ifndef NODESTRUCT delete Value; #endif } void AttributeQPIdType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Value"); Value->printSelf(outFile); fprintf(outFile, "</Value>\n"); doSpaces(-INDENT, outFile); } bool AttributeQPIdType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeQPIdType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeQPIdType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else { fprintf(stderr, "bad attribute in AttributeQPIdType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeQPIdType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; } return returnValue; } QPIdType * AttributeQPIdType::getValue() {return Value;} void AttributeQPIdType::setValue(QPIdType * ValueIn) {Value = ValueIn;} /* ***************************************************************** */ /* class AttributeStrType */ AttributeStrType::AttributeStrType() : AttributeBaseType() { value = 0; } AttributeStrType::AttributeStrType( XmlString * nameIn, XmlString * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeStrType::~AttributeStrType() { #ifndef NODESTRUCT delete value; #endif } void AttributeStrType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeStrType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeStrType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeStrType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { XmlString * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeStrType\n"); returnValue = true; break; } valueVal = new XmlString(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeStrType\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeStrType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeStrType\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeStrType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } XmlString * AttributeStrType::getvalue() {return value;} void AttributeStrType::setvalue(XmlString * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeTimeType */ AttributeTimeType::AttributeTimeType() : AttributeBaseType() { value = 0; } AttributeTimeType::AttributeTimeType( XmlString * nameIn, XmlDateTime * valueIn) : AttributeBaseType( nameIn) { value = valueIn; } AttributeTimeType::~AttributeTimeType() { #ifndef NODESTRUCT delete value; #endif } void AttributeTimeType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (value) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "value=\""); value->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"value\" missing\n"); exit(1); } fprintf(outFile, "/>\n"); } bool AttributeTimeType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeTimeType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeTimeType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "value") { XmlDateTime * valueVal; if (value) { fprintf(stderr, "two values for value in AttributeTimeType\n"); returnValue = true; break; } valueVal = new XmlDateTime(decl->val.c_str()); if (valueVal->bad) { delete valueVal; fprintf(stderr, "bad value %s for value in AttributeTimeType\n", decl->val.c_str()); returnValue = true; break; } else value = valueVal; } else { fprintf(stderr, "bad attribute in AttributeTimeType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeTimeType\n"); returnValue = true; } if (value == 0) { fprintf(stderr, "required attribute \"value\" missing in AttributeTimeType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete value; value = 0; } return returnValue; } XmlDateTime * AttributeTimeType::getvalue() {return value;} void AttributeTimeType::setvalue(XmlDateTime * valueIn) {value = valueIn;} /* ***************************************************************** */ /* class AttributeUserType */ AttributeUserType::AttributeUserType() : AttributeBaseType() { nameUserAttribute = 0; AttributeUserTy_1002 = 0; } AttributeUserType::AttributeUserType( AttributeUserTy_1002_Type * AttributeUserTy_1002In) : AttributeBaseType() { nameUserAttribute = 0; AttributeUserTy_1002 = AttributeUserTy_1002In; } AttributeUserType::AttributeUserType( XmlString * nameIn, XmlString * nameUserAttributeIn, AttributeUserTy_1002_Type * AttributeUserTy_1002In) : AttributeBaseType( nameIn) { nameUserAttribute = nameUserAttributeIn; AttributeUserTy_1002 = AttributeUserTy_1002In; } AttributeUserType::~AttributeUserType() { #ifndef NODESTRUCT delete nameUserAttribute; delete AttributeUserTy_1002; #endif } void AttributeUserType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (name) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "name=\""); name->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"name\" missing\n"); exit(1); } if (nameUserAttribute) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "nameUserAttribute=\""); nameUserAttribute->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"nameUserAttribute\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); AttributeUserTy_1002->printSelf(outFile); doSpaces(-INDENT, outFile); } bool AttributeUserType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "name") { XmlString * nameVal; if (name) { fprintf(stderr, "two values for name in AttributeUserType\n"); returnValue = true; break; } nameVal = new XmlString(decl->val.c_str()); if (nameVal->bad) { delete nameVal; fprintf(stderr, "bad value %s for name in AttributeUserType\n", decl->val.c_str()); returnValue = true; break; } else name = nameVal; } else if (decl->name == "nameUserAttribute") { XmlString * nameUserAttributeVal; if (nameUserAttribute) { fprintf(stderr, "two values for nameUserAttribute in AttributeUserType\n"); returnValue = true; break; } nameUserAttributeVal = new XmlString(decl->val.c_str()); if (nameUserAttributeVal->bad) { delete nameUserAttributeVal; fprintf(stderr, "bad value %s for nameUserAttribute in AttributeUserType\n", decl->val.c_str()); returnValue = true; break; } else nameUserAttribute = nameUserAttributeVal; } else { fprintf(stderr, "bad attribute in AttributeUserType\n"); returnValue = true; break; } } if (name == 0) { fprintf(stderr, "required attribute \"name\" missing in AttributeUserType\n"); returnValue = true; } if (nameUserAttribute == 0) { fprintf(stderr, "required attribute \"nameUserAttribute\" missing in AttributeUserType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete name; name = 0; delete nameUserAttribute; nameUserAttribute = 0; } return returnValue; } XmlString * AttributeUserType::getnameUserAttribute() {return nameUserAttribute;} void AttributeUserType::setnameUserAttribute(XmlString * nameUserAttributeIn) {nameUserAttribute = nameUserAttributeIn;} AttributeUserTy_1002_Type * AttributeUserType::getAttributeUserTy_1002() {return AttributeUserTy_1002;} void AttributeUserType::setAttributeUserTy_1002(AttributeUserTy_1002_Type * AttributeUserTy_1002In) {AttributeUserTy_1002 = AttributeUserTy_1002In;} /* ***************************************************************** */ /* class AttributesType */ AttributesType::AttributesType() { n = 0; Attribute = 0; } AttributesType::AttributesType( AttributeBaseTypeLisd * AttributeIn) { n = 0; Attribute = AttributeIn; } AttributesType::AttributesType( NaturalType * nIn, AttributeBaseTypeLisd * AttributeIn) { n = nIn; Attribute = AttributeIn; } AttributesType::~AttributesType() { #ifndef NODESTRUCT delete n; delete Attribute; #endif } void AttributesType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); { if (!Attribute) { fprintf(stderr, "Attribute list is missing\n"); exit(1); } if (Attribute->size() == 0) { fprintf(stderr, "Attribute list is empty\n"); exit(1); } std::list<AttributeBaseType *>::iterator iter; for (iter = Attribute->begin(); iter != Attribute->end(); iter++) { AttributeBaseType * basie; basie = *iter; doSpaces(0, outFile); if (basie->printElement == 0) { fprintf(stderr, "element name missing\n"); exit(1); } else if (strcmp(basie->printElement, "AttributeBool") == 0) { AttributeBoolType * typ; if ((typ = dynamic_cast<AttributeBoolType *>(basie))) { fprintf(outFile, "<AttributeBool"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeBool element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeStr") == 0) { AttributeStrType * typ; if ((typ = dynamic_cast<AttributeStrType *>(basie))) { fprintf(outFile, "<AttributeStr"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeStr element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeTime") == 0) { AttributeTimeType * typ; if ((typ = dynamic_cast<AttributeTimeType *>(basie))) { fprintf(outFile, "<AttributeTime"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeTime element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeQPId") == 0) { AttributeQPIdType * typ; if ((typ = dynamic_cast<AttributeQPIdType *>(basie))) { fprintf(outFile, "<AttributeQPId"); typ->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</AttributeQPId>\n"); } else { fprintf(stderr, "bad AttributeQPId element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeI1") == 0) { AttributeI1Type * typ; if ((typ = dynamic_cast<AttributeI1Type *>(basie))) { fprintf(outFile, "<AttributeI1"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeI1 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeI2") == 0) { AttributeI2Type * typ; if ((typ = dynamic_cast<AttributeI2Type *>(basie))) { fprintf(outFile, "<AttributeI2"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeI2 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeI3") == 0) { AttributeI3Type * typ; if ((typ = dynamic_cast<AttributeI3Type *>(basie))) { fprintf(outFile, "<AttributeI3"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeI3 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeD1") == 0) { AttributeD1Type * typ; if ((typ = dynamic_cast<AttributeD1Type *>(basie))) { fprintf(outFile, "<AttributeD1"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeD1 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeD2") == 0) { AttributeD2Type * typ; if ((typ = dynamic_cast<AttributeD2Type *>(basie))) { fprintf(outFile, "<AttributeD2"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeD2 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeD3") == 0) { AttributeD3Type * typ; if ((typ = dynamic_cast<AttributeD3Type *>(basie))) { fprintf(outFile, "<AttributeD3"); typ->printSelf(outFile); } else { fprintf(stderr, "bad AttributeD3 element\n"); exit(1); } } else if (strcmp(basie->printElement, "AttributeUser") == 0) { AttributeUserType * typ; if ((typ = dynamic_cast<AttributeUserType *>(basie))) { fprintf(outFile, "<AttributeUser"); typ->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</AttributeUser>\n"); } else { fprintf(stderr, "bad AttributeUser element\n"); exit(1); } } else { fprintf(stderr, "bad Attribute type\n"); fprintf(stderr, " exiting\n"); exit(1); } } } doSpaces(-INDENT, outFile); } bool AttributesType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in AttributesType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in AttributesType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in AttributesType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in AttributesType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * AttributesType::getn() {return n;} void AttributesType::setn(NaturalType * nIn) {n = nIn;} AttributeBaseTypeLisd * AttributesType::getAttribute() {return Attribute;} void AttributesType::setAttribute(AttributeBaseTypeLisd * AttributeIn) {Attribute = AttributeIn;} /* ***************************************************************** */ /* class AxisType */ AxisType::AxisType() { AxisPoint = 0; Direction = 0; } AxisType::AxisType( PointType * AxisPointIn, UnitVectorType * DirectionIn) { AxisPoint = AxisPointIn; Direction = DirectionIn; } AxisType::~AxisType() { #ifndef NODESTRUCT delete AxisPoint; delete Direction; #endif } void AxisType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<AxisPoint"); AxisPoint->printSelf(outFile); fprintf(outFile, "</AxisPoint>\n"); doSpaces(0, outFile); fprintf(outFile, "<Direction"); Direction->printSelf(outFile); fprintf(outFile, "</Direction>\n"); doSpaces(-INDENT, outFile); } PointType * AxisType::getAxisPoint() {return AxisPoint;} void AxisType::setAxisPoint(PointType * AxisPointIn) {AxisPoint = AxisPointIn;} UnitVectorType * AxisType::getDirection() {return Direction;} void AxisType::setDirection(UnitVectorType * DirectionIn) {Direction = DirectionIn;} /* ***************************************************************** */ /* class BinaryDataType */ BinaryDataType::BinaryDataType() { count = 0; val = ""; } BinaryDataType::BinaryDataType( const char * valStringIn) : XmlBase64Binary(valStringIn) { count = 0; } BinaryDataType::BinaryDataType( NaturalType * countIn, const char * valStringIn) : XmlBase64Binary(valStringIn) { count = countIn; } BinaryDataType::~BinaryDataType() { #ifndef NODESTRUCT delete count; #endif } void BinaryDataType::printName(FILE * outFile) { fprintf(outFile, "BinaryDataType"); } void BinaryDataType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } XmlBase64Binary::printSelf(outFile); } bool BinaryDataType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in BinaryDataType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in BinaryDataType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else { fprintf(stderr, "bad attribute in BinaryDataType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in BinaryDataType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; } return returnValue; } NaturalType * BinaryDataType::getcount() {return count;} void BinaryDataType::setcount(NaturalType * countIn) {count = countIn;} /* ***************************************************************** */ /* class BoundingBoxAxisAlignedType */ BoundingBoxAxisAlignedType::BoundingBoxAxisAlignedType() { PointMin = 0; PointMax = 0; } BoundingBoxAxisAlignedType::BoundingBoxAxisAlignedType( PointSimpleType * PointMinIn, PointSimpleType * PointMaxIn) { PointMin = PointMinIn; PointMax = PointMaxIn; } BoundingBoxAxisAlignedType::~BoundingBoxAxisAlignedType() { #ifndef NODESTRUCT delete PointMin; delete PointMax; #endif } void BoundingBoxAxisAlignedType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<PointMin"); PointMin->printSelf(outFile); fprintf(outFile, "</PointMin>\n"); doSpaces(0, outFile); fprintf(outFile, "<PointMax"); PointMax->printSelf(outFile); fprintf(outFile, "</PointMax>\n"); doSpaces(-INDENT, outFile); } PointSimpleType * BoundingBoxAxisAlignedType::getPointMin() {return PointMin;} void BoundingBoxAxisAlignedType::setPointMin(PointSimpleType * PointMinIn) {PointMin = PointMinIn;} PointSimpleType * BoundingBoxAxisAlignedType::getPointMax() {return PointMax;} void BoundingBoxAxisAlignedType::setPointMax(PointSimpleType * PointMaxIn) {PointMax = PointMaxIn;} /* ***************************************************************** */ /* class CoordinateSystemCoreType */ CoordinateSystemCoreType::CoordinateSystemCoreType() { Rotation = 0; Origin = 0; } CoordinateSystemCoreType::CoordinateSystemCoreType( TransformRotationType * RotationIn, PointSimpleType * OriginIn) { Rotation = RotationIn; Origin = OriginIn; } CoordinateSystemCoreType::~CoordinateSystemCoreType() { #ifndef NODESTRUCT delete Rotation; delete Origin; #endif } void CoordinateSystemCoreType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); if (Rotation) { doSpaces(0, outFile); fprintf(outFile, "<Rotation"); Rotation->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</Rotation>\n"); } if (Origin) { doSpaces(0, outFile); fprintf(outFile, "<Origin"); Origin->printSelf(outFile); fprintf(outFile, "</Origin>\n"); } doSpaces(-INDENT, outFile); } TransformRotationType * CoordinateSystemCoreType::getRotation() {return Rotation;} void CoordinateSystemCoreType::setRotation(TransformRotationType * RotationIn) {Rotation = RotationIn;} PointSimpleType * CoordinateSystemCoreType::getOrigin() {return Origin;} void CoordinateSystemCoreType::setOrigin(PointSimpleType * OriginIn) {Origin = OriginIn;} /* ***************************************************************** */ /* class D2Type */ D2Type::D2Type() : ListDoubleType() { } D2Type::D2Type( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } D2Type::D2Type( const char * valueString) : ListDoubleType(valueString) { D2TypeCheck(); if (bad) { fprintf(stderr, "D2TypeCheck failed\n"); exit(1); } } D2Type::~D2Type() {} void D2Type::printName(FILE * outFile) { fprintf(outFile, "D2Type"); } void D2Type::printSelf(FILE * outFile) { D2TypeCheck(); if (bad) { fprintf(stderr, "D2TypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void D2Type::oPrintSelf(FILE * outFile) { D2TypeCheck(); if (bad) { fprintf(stderr, "D2TypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool D2Type::D2TypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class D3Type */ D3Type::D3Type() : ListDoubleType() { } D3Type::D3Type( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } D3Type::D3Type( const char * valueString) : ListDoubleType(valueString) { D3TypeCheck(); if (bad) { fprintf(stderr, "D3TypeCheck failed\n"); exit(1); } } D3Type::~D3Type() {} void D3Type::printName(FILE * outFile) { fprintf(outFile, "D3Type"); } void D3Type::printSelf(FILE * outFile) { D3TypeCheck(); if (bad) { fprintf(stderr, "D3TypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void D3Type::oPrintSelf(FILE * outFile) { D3TypeCheck(); if (bad) { fprintf(stderr, "D3TypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool D3Type::D3TypeCheck() { bad = ((size() != 3)); return bad; } /* ***************************************************************** */ /* class D4Type */ D4Type::D4Type() : ListDoubleType() { } D4Type::D4Type( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } D4Type::D4Type( const char * valueString) : ListDoubleType(valueString) { D4TypeCheck(); if (bad) { fprintf(stderr, "D4TypeCheck failed\n"); exit(1); } } D4Type::~D4Type() {} void D4Type::printName(FILE * outFile) { fprintf(outFile, "D4Type"); } void D4Type::printSelf(FILE * outFile) { D4TypeCheck(); if (bad) { fprintf(stderr, "D4TypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void D4Type::oPrintSelf(FILE * outFile) { D4TypeCheck(); if (bad) { fprintf(stderr, "D4TypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool D4Type::D4TypeCheck() { bad = ((size() != 4)); return bad; } /* ***************************************************************** */ /* class DoublePositiveType */ DoublePositiveType::DoublePositiveType() : XmlDouble() { } DoublePositiveType::DoublePositiveType( const char * valIn) : XmlDouble( valIn) { if (!bad) bad = ((val <= 0.0)); } DoublePositiveType::~DoublePositiveType() {} bool DoublePositiveType::DoublePositiveTypeIsBad() { if (XmlDoubleIsBad()) return true; return ((val <= 0.0)); } void DoublePositiveType::printName(FILE * outFile) { fprintf(outFile, "DoublePositiveType"); } void DoublePositiveType::printSelf(FILE * outFile) { if (DoublePositiveTypeIsBad()) { fprintf(stderr, "bad DoublePositiveType value, "); XmlDouble::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlDouble::printSelf(outFile); } void DoublePositiveType::oPrintSelf(FILE * outFile) { if (DoublePositiveTypeIsBad()) { fprintf(stderr, "bad DoublePositiveType value, "); XmlDouble::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlDouble::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ElementReferenceFullType */ ElementReferenceFullType::ElementReferenceFullType() { Id = 0; } ElementReferenceFullType::ElementReferenceFullType( QIFReferenceFullType * IdIn) { Id = IdIn; } ElementReferenceFullType::~ElementReferenceFullType() { #ifndef NODESTRUCT delete Id; #endif } void ElementReferenceFullType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Id"); Id->printSelf(outFile); fprintf(outFile, "</Id>\n"); doSpaces(-INDENT, outFile); } QIFReferenceFullType * ElementReferenceFullType::getId() {return Id;} void ElementReferenceFullType::setId(QIFReferenceFullType * IdIn) {Id = IdIn;} /* ***************************************************************** */ /* class ElementReferenceType */ ElementReferenceType::ElementReferenceType() { Id = 0; } ElementReferenceType::ElementReferenceType( QIFReferenceType * IdIn) { Id = IdIn; } ElementReferenceType::~ElementReferenceType() { #ifndef NODESTRUCT delete Id; #endif } void ElementReferenceType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Id"); Id->printSelf(outFile); fprintf(outFile, "</Id>\n"); doSpaces(-INDENT, outFile); } QIFReferenceType * ElementReferenceType::getId() {return Id;} void ElementReferenceType::setId(QIFReferenceType * IdIn) {Id = IdIn;} /* ***************************************************************** */ /* class FractionType */ FractionType::FractionType() { Numerator = 0; Denominator = 0; } FractionType::FractionType( NaturalType * NumeratorIn, NaturalType * DenominatorIn) { Numerator = NumeratorIn; Denominator = DenominatorIn; } FractionType::~FractionType() { #ifndef NODESTRUCT delete Numerator; delete Denominator; #endif } void FractionType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Numerator"); Numerator->printSelf(outFile); fprintf(outFile, "</Numerator>\n"); doSpaces(0, outFile); fprintf(outFile, "<Denominator"); Denominator->printSelf(outFile); fprintf(outFile, "</Denominator>\n"); doSpaces(-INDENT, outFile); } NaturalType * FractionType::getNumerator() {return Numerator;} void FractionType::setNumerator(NaturalType * NumeratorIn) {Numerator = NumeratorIn;} NaturalType * FractionType::getDenominator() {return Denominator;} void FractionType::setDenominator(NaturalType * DenominatorIn) {Denominator = DenominatorIn;} /* ***************************************************************** */ /* class I2Type */ I2Type::I2Type() : ListIntType() { } I2Type::I2Type( XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { } I2Type::I2Type( const char * valueString) : ListIntType(valueString) { I2TypeCheck(); if (bad) { fprintf(stderr, "I2TypeCheck failed\n"); exit(1); } } I2Type::~I2Type() {} void I2Type::printName(FILE * outFile) { fprintf(outFile, "I2Type"); } void I2Type::printSelf(FILE * outFile) { I2TypeCheck(); if (bad) { fprintf(stderr, "I2TypeCheck failed\n"); exit(1); } ListIntType::printSelf(outFile); } void I2Type::oPrintSelf(FILE * outFile) { I2TypeCheck(); if (bad) { fprintf(stderr, "I2TypeCheck failed\n"); exit(1); } ListIntType::oPrintSelf(outFile); } bool I2Type::I2TypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class I3Type */ I3Type::I3Type() : ListIntType() { } I3Type::I3Type( XmlInteger * aXmlInteger) : ListIntType(aXmlInteger) { } I3Type::I3Type( const char * valueString) : ListIntType(valueString) { I3TypeCheck(); if (bad) { fprintf(stderr, "I3TypeCheck failed\n"); exit(1); } } I3Type::~I3Type() {} void I3Type::printName(FILE * outFile) { fprintf(outFile, "I3Type"); } void I3Type::printSelf(FILE * outFile) { I3TypeCheck(); if (bad) { fprintf(stderr, "I3TypeCheck failed\n"); exit(1); } ListIntType::printSelf(outFile); } void I3Type::oPrintSelf(FILE * outFile) { I3TypeCheck(); if (bad) { fprintf(stderr, "I3TypeCheck failed\n"); exit(1); } ListIntType::oPrintSelf(outFile); } bool I3Type::I3TypeCheck() { bad = ((size() != 3)); return bad; } /* ***************************************************************** */ /* class LatitudeLongitudeSweepType */ LatitudeLongitudeSweepType::LatitudeLongitudeSweepType() { DirMeridianPrime = 0; DomainLatitude = 0; DomainLongitude = 0; } LatitudeLongitudeSweepType::LatitudeLongitudeSweepType( UnitVectorType * DirMeridianPrimeIn, AngleRangeType * DomainLatitudeIn, AngleRangeType * DomainLongitudeIn) { DirMeridianPrime = DirMeridianPrimeIn; DomainLatitude = DomainLatitudeIn; DomainLongitude = DomainLongitudeIn; } LatitudeLongitudeSweepType::~LatitudeLongitudeSweepType() { #ifndef NODESTRUCT delete DirMeridianPrime; delete DomainLatitude; delete DomainLongitude; #endif } void LatitudeLongitudeSweepType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<DirMeridianPrime"); DirMeridianPrime->printSelf(outFile); fprintf(outFile, "</DirMeridianPrime>\n"); doSpaces(0, outFile); fprintf(outFile, "<DomainLatitude"); DomainLatitude->printSelf(outFile); fprintf(outFile, "</DomainLatitude>\n"); doSpaces(0, outFile); fprintf(outFile, "<DomainLongitude"); DomainLongitude->printSelf(outFile); fprintf(outFile, "</DomainLongitude>\n"); doSpaces(-INDENT, outFile); } UnitVectorType * LatitudeLongitudeSweepType::getDirMeridianPrime() {return DirMeridianPrime;} void LatitudeLongitudeSweepType::setDirMeridianPrime(UnitVectorType * DirMeridianPrimeIn) {DirMeridianPrime = DirMeridianPrimeIn;} AngleRangeType * LatitudeLongitudeSweepType::getDomainLatitude() {return DomainLatitude;} void LatitudeLongitudeSweepType::setDomainLatitude(AngleRangeType * DomainLatitudeIn) {DomainLatitude = DomainLatitudeIn;} AngleRangeType * LatitudeLongitudeSweepType::getDomainLongitude() {return DomainLongitude;} void LatitudeLongitudeSweepType::setDomainLongitude(AngleRangeType * DomainLongitudeIn) {DomainLongitude = DomainLongitudeIn;} /* ***************************************************************** */ /* class LineSegment2dType */ LineSegment2dType::LineSegment2dType() { StartPoint = 0; EndPoint = 0; } LineSegment2dType::LineSegment2dType( Point2dSimpleType * StartPointIn, Point2dSimpleType * EndPointIn) { StartPoint = StartPointIn; EndPoint = EndPointIn; } LineSegment2dType::~LineSegment2dType() { #ifndef NODESTRUCT delete StartPoint; delete EndPoint; #endif } void LineSegment2dType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<StartPoint"); StartPoint->printSelf(outFile); fprintf(outFile, "</StartPoint>\n"); doSpaces(0, outFile); fprintf(outFile, "<EndPoint"); EndPoint->printSelf(outFile); fprintf(outFile, "</EndPoint>\n"); doSpaces(-INDENT, outFile); } Point2dSimpleType * LineSegment2dType::getStartPoint() {return StartPoint;} void LineSegment2dType::setStartPoint(Point2dSimpleType * StartPointIn) {StartPoint = StartPointIn;} Point2dSimpleType * LineSegment2dType::getEndPoint() {return EndPoint;} void LineSegment2dType::setEndPoint(Point2dSimpleType * EndPointIn) {EndPoint = EndPointIn;} /* ***************************************************************** */ /* class LineSegmentType */ LineSegmentType::LineSegmentType() { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; StartPoint = 0; EndPoint = 0; } LineSegmentType::LineSegmentType( PointSimpleType * StartPointIn, PointSimpleType * EndPointIn) { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; StartPoint = StartPointIn; EndPoint = EndPointIn; } LineSegmentType::LineSegmentType( XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, PointSimpleType * StartPointIn, PointSimpleType * EndPointIn) { decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; StartPoint = StartPointIn; EndPoint = EndPointIn; } LineSegmentType::~LineSegmentType() { #ifndef NODESTRUCT delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; delete StartPoint; delete EndPoint; #endif } void LineSegmentType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<StartPoint"); StartPoint->printSelf(outFile); fprintf(outFile, "</StartPoint>\n"); doSpaces(0, outFile); fprintf(outFile, "<EndPoint"); EndPoint->printSelf(outFile); fprintf(outFile, "</EndPoint>\n"); doSpaces(-INDENT, outFile); } bool LineSegmentType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in LineSegmentType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in LineSegmentType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in LineSegmentType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in LineSegmentType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in LineSegmentType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in LineSegmentType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in LineSegmentType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in LineSegmentType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in LineSegmentType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in LineSegmentType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in LineSegmentType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in LineSegmentType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in LineSegmentType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in LineSegmentType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in LineSegmentType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } XmlNonNegativeInteger * LineSegmentType::getdecimalPlaces() {return decimalPlaces;} void LineSegmentType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * LineSegmentType::getlinearUnit() {return linearUnit;} void LineSegmentType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * LineSegmentType::getsignificantFigures() {return significantFigures;} void LineSegmentType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * LineSegmentType::getvalidity() {return validity;} void LineSegmentType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * LineSegmentType::getxDecimalPlaces() {return xDecimalPlaces;} void LineSegmentType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * LineSegmentType::getxSignificantFigures() {return xSignificantFigures;} void LineSegmentType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * LineSegmentType::getxValidity() {return xValidity;} void LineSegmentType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * LineSegmentType::getyDecimalPlaces() {return yDecimalPlaces;} void LineSegmentType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * LineSegmentType::getySignificantFigures() {return ySignificantFigures;} void LineSegmentType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * LineSegmentType::getyValidity() {return yValidity;} void LineSegmentType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * LineSegmentType::getzDecimalPlaces() {return zDecimalPlaces;} void LineSegmentType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * LineSegmentType::getzSignificantFigures() {return zSignificantFigures;} void LineSegmentType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * LineSegmentType::getzValidity() {return zValidity;} void LineSegmentType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} PointSimpleType * LineSegmentType::getStartPoint() {return StartPoint;} void LineSegmentType::setStartPoint(PointSimpleType * StartPointIn) {StartPoint = StartPointIn;} PointSimpleType * LineSegmentType::getEndPoint() {return EndPoint;} void LineSegmentType::setEndPoint(PointSimpleType * EndPointIn) {EndPoint = EndPointIn;} /* ***************************************************************** */ /* class ListBooleanType */ ListBooleanType::ListBooleanType() { } ListBooleanType::ListBooleanType( XmlBoolean * aXmlBoolean) : XmlBooleanLisd(aXmlBoolean) { } ListBooleanType::ListBooleanType( const char * valueString) : XmlBooleanLisd(valueString) { } ListBooleanType::~ListBooleanType() { } void ListBooleanType::printName(FILE * outFile) { fprintf(outFile, "ListBooleanType"); } void ListBooleanType::printSelf(FILE * outFile) { XmlBooleanLisd::printSelf(outFile); } void ListBooleanType::oPrintSelf(FILE * outFile) { XmlBooleanLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ListDateTimeType */ ListDateTimeType::ListDateTimeType() { } ListDateTimeType::ListDateTimeType( XmlDateTime * aXmlDateTime) : XmlDateTimeLisd(aXmlDateTime) { } ListDateTimeType::ListDateTimeType( const char * valueString) : XmlDateTimeLisd(valueString) { } ListDateTimeType::~ListDateTimeType() { } void ListDateTimeType::printName(FILE * outFile) { fprintf(outFile, "ListDateTimeType"); } void ListDateTimeType::printSelf(FILE * outFile) { XmlDateTimeLisd::printSelf(outFile); } void ListDateTimeType::oPrintSelf(FILE * outFile) { XmlDateTimeLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ListDoubleType */ ListDoubleType::ListDoubleType() { } ListDoubleType::ListDoubleType( XmlDouble * aXmlDouble) : XmlDoubleLisd(aXmlDouble) { } ListDoubleType::ListDoubleType( const char * valueString) : XmlDoubleLisd(valueString) { } ListDoubleType::~ListDoubleType() { } void ListDoubleType::printName(FILE * outFile) { fprintf(outFile, "ListDoubleType"); } void ListDoubleType::printSelf(FILE * outFile) { XmlDoubleLisd::printSelf(outFile); } void ListDoubleType::oPrintSelf(FILE * outFile) { XmlDoubleLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ListIntType */ ListIntType::ListIntType() { } ListIntType::ListIntType( XmlInteger * aXmlInteger) : XmlIntegerLisd(aXmlInteger) { } ListIntType::ListIntType( const char * valueString) : XmlIntegerLisd(valueString) { } ListIntType::~ListIntType() { } void ListIntType::printName(FILE * outFile) { fprintf(outFile, "ListIntType"); } void ListIntType::printSelf(FILE * outFile) { XmlIntegerLisd::printSelf(outFile); } void ListIntType::oPrintSelf(FILE * outFile) { XmlIntegerLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ListNaturalType */ ListNaturalType::ListNaturalType() { } ListNaturalType::ListNaturalType( NaturalType * aNaturalType) { push_back(aNaturalType); } ListNaturalType::ListNaturalType( const char * valueString) { NaturalType * val; int n; int start; char buffer[200]; bad = false; for (n = 0; valueString[n]; n++) { for (; (valueString[n] != 0) && (isspace(valueString[n])); n++) { //skip leading white space and handle empty or white string if (valueString[n] == 0) break; } if (valueString[n] == 0) break; start = n; for (; (valueString[n] != 0) && (!isspace(valueString[n])); n++); if ((n - start) > 199) { fprintf(stderr, "%s is not a valid ListNaturalType\n", valueString); bad = true; break; } strncpy(buffer, valueString + start, 199); buffer[n - start] = 0; val = new NaturalType(buffer); if (val->bad) { fprintf(stderr, "%s is not a valid ListNaturalType\n", valueString); bad = true; break; } else push_back(val); if (valueString[n] == 0) break; } } ListNaturalType::~ListNaturalType() { #ifndef NODESTRUCT std::list<NaturalType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void ListNaturalType::printName(FILE * outFile) { fprintf(outFile, "ListNaturalType"); } void ListNaturalType::printSelf(FILE * outFile) { fprintf(outFile, ">"); oPrintSelf(outFile); } void ListNaturalType::oPrintSelf(FILE * outFile) { std::list<NaturalType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { (*iter)->oPrintSelf(outFile); if ((*iter) != back()) fprintf(outFile, " "); } } /* ***************************************************************** */ /* class ListQIFReferenceFullType */ ListQIFReferenceFullType::ListQIFReferenceFullType() : ListQIFReferenceType() { asmPathId = 0; asmPathXId = 0; } ListQIFReferenceFullType::ListQIFReferenceFullType( ListQIFReferenceTypeChoicePair * ListQIFReferenceTypePairIn) : ListQIFReferenceType( ListQIFReferenceTypePairIn) { asmPathId = 0; asmPathXId = 0; } ListQIFReferenceFullType::ListQIFReferenceFullType( NaturalType * nIn, ListQIFReferenceTypeChoicePair * ListQIFReferenceTypePairIn, QIFReferenceSimpleType * asmPathIdIn, QIFReferenceSimpleType * asmPathXIdIn) : ListQIFReferenceType( nIn, ListQIFReferenceTypePairIn) { asmPathId = asmPathIdIn; asmPathXId = asmPathXIdIn; } ListQIFReferenceFullType::~ListQIFReferenceFullType() { #ifndef NODESTRUCT delete asmPathId; delete asmPathXId; #endif } void ListQIFReferenceFullType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (asmPathId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathId=\""); asmPathId->oPrintSelf(outFile); fprintf(outFile, "\""); } if (asmPathXId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathXId=\""); asmPathXId->oPrintSelf(outFile); fprintf(outFile, "\""); } if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); ListQIFReferenceTypePair->printSelf(outFile); doSpaces(-INDENT, outFile); } bool ListQIFReferenceFullType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "asmPathId") { QIFReferenceSimpleType * asmPathIdVal; if (asmPathId) { fprintf(stderr, "two values for asmPathId in ListQIFReferenceFullType\n"); returnValue = true; break; } asmPathIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathIdVal->bad) { delete asmPathIdVal; fprintf(stderr, "bad value %s for asmPathId in ListQIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathId = asmPathIdVal; } else if (decl->name == "asmPathXId") { QIFReferenceSimpleType * asmPathXIdVal; if (asmPathXId) { fprintf(stderr, "two values for asmPathXId in ListQIFReferenceFullType\n"); returnValue = true; break; } asmPathXIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathXIdVal->bad) { delete asmPathXIdVal; fprintf(stderr, "bad value %s for asmPathXId in ListQIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathXId = asmPathXIdVal; } else if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ListQIFReferenceFullType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ListQIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ListQIFReferenceFullType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ListQIFReferenceFullType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete asmPathId; asmPathId = 0; delete asmPathXId; asmPathXId = 0; delete n; n = 0; } return returnValue; } QIFReferenceSimpleType * ListQIFReferenceFullType::getasmPathId() {return asmPathId;} void ListQIFReferenceFullType::setasmPathId(QIFReferenceSimpleType * asmPathIdIn) {asmPathId = asmPathIdIn;} QIFReferenceSimpleType * ListQIFReferenceFullType::getasmPathXId() {return asmPathXId;} void ListQIFReferenceFullType::setasmPathXId(QIFReferenceSimpleType * asmPathXIdIn) {asmPathXId = asmPathXIdIn;} /* ***************************************************************** */ /* class ListQIFReferenceSimpleType */ ListQIFReferenceSimpleType::ListQIFReferenceSimpleType() { } ListQIFReferenceSimpleType::ListQIFReferenceSimpleType( QIFReferenceSimpleType * aQIFReferenceSimpleType) { push_back(aQIFReferenceSimpleType); } ListQIFReferenceSimpleType::ListQIFReferenceSimpleType( const char * valueString) { QIFReferenceSimpleType * val; int n; int start; char buffer[200]; bad = false; for (n = 0; valueString[n]; n++) { for (; (valueString[n] != 0) && (isspace(valueString[n])); n++) { //skip leading white space and handle empty or white string if (valueString[n] == 0) break; } if (valueString[n] == 0) break; start = n; for (; (valueString[n] != 0) && (!isspace(valueString[n])); n++); if ((n - start) > 199) { fprintf(stderr, "%s is not a valid ListQIFReferenceSimpleType\n", valueString); bad = true; break; } strncpy(buffer, valueString + start, 199); buffer[n - start] = 0; val = new QIFReferenceSimpleType(buffer); if (val->bad) { fprintf(stderr, "%s is not a valid ListQIFReferenceSimpleType\n", valueString); bad = true; break; } else push_back(val); if (valueString[n] == 0) break; } } ListQIFReferenceSimpleType::~ListQIFReferenceSimpleType() { #ifndef NODESTRUCT std::list<QIFReferenceSimpleType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void ListQIFReferenceSimpleType::printName(FILE * outFile) { fprintf(outFile, "ListQIFReferenceSimpleType"); } void ListQIFReferenceSimpleType::printSelf(FILE * outFile) { fprintf(outFile, ">"); oPrintSelf(outFile); } void ListQIFReferenceSimpleType::oPrintSelf(FILE * outFile) { std::list<QIFReferenceSimpleType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { (*iter)->oPrintSelf(outFile); if ((*iter) != back()) fprintf(outFile, " "); } } /* ***************************************************************** */ /* class ListQIFReferenceType */ ListQIFReferenceType::ListQIFReferenceType() { n = 0; ListQIFReferenceTypePair = 0; } ListQIFReferenceType::ListQIFReferenceType( ListQIFReferenceTypeChoicePair * ListQIFReferenceTypePairIn) { n = 0; ListQIFReferenceTypePair = ListQIFReferenceTypePairIn; } ListQIFReferenceType::ListQIFReferenceType( NaturalType * nIn, ListQIFReferenceTypeChoicePair * ListQIFReferenceTypePairIn) { n = nIn; ListQIFReferenceTypePair = ListQIFReferenceTypePairIn; } ListQIFReferenceType::~ListQIFReferenceType() { #ifndef NODESTRUCT delete n; delete ListQIFReferenceTypePair; #endif } void ListQIFReferenceType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (n) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "n=\""); n->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"n\" missing\n"); exit(1); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); ListQIFReferenceTypePair->printSelf(outFile); doSpaces(-INDENT, outFile); } ListQIFReferenceTypeChoicePair * ListQIFReferenceType::getListQIFReferenceTypePair() {return ListQIFReferenceTypePair;} void ListQIFReferenceType::setListQIFReferenceTypePair(ListQIFReferenceTypeChoicePair * ListQIFReferenceTypePairIn) {ListQIFReferenceTypePair = ListQIFReferenceTypePairIn;} /* ***************************************************************** */ /* class ListQIFReferenceTypeChoicePair */ ListQIFReferenceTypeChoicePair::ListQIFReferenceTypeChoicePair() {} ListQIFReferenceTypeChoicePair::ListQIFReferenceTypeChoicePair( whichOne ListQIFReferenceTypeTypeIn, ListQIFReferenceTypeVal ListQIFReferenceTypeValueIn) { ListQIFReferenceTypeType = ListQIFReferenceTypeTypeIn; ListQIFReferenceTypeValue = ListQIFReferenceTypeValueIn; } ListQIFReferenceTypeChoicePair::~ListQIFReferenceTypeChoicePair() { #ifndef NODESTRUCT if (ListQIFReferenceTypeType == IdsE) delete ListQIFReferenceTypeValue.Ids; else if (ListQIFReferenceTypeType == ListQIFReferenc_1003E) delete ListQIFReferenceTypeValue.ListQIFReferenc_1003; #endif } void ListQIFReferenceTypeChoicePair::printSelf(FILE * outFile) { if (ListQIFReferenceTypeType == IdsE) { doSpaces(0, outFile); fprintf(outFile, "<Ids"); ListQIFReferenceTypeValue.Ids->printSelf(outFile); fprintf(outFile, "</Ids>\n"); } else if (ListQIFReferenceTypeType == ListQIFReferenc_1003E) { ListQIFReferenceTypeValue.ListQIFReferenc_1003->printSelf(outFile); } } bool ListQIFReferenceType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "n") { NaturalType * nVal; if (n) { fprintf(stderr, "two values for n in ListQIFReferenceType\n"); returnValue = true; break; } nVal = new NaturalType(decl->val.c_str()); if (nVal->bad) { delete nVal; fprintf(stderr, "bad value %s for n in ListQIFReferenceType\n", decl->val.c_str()); returnValue = true; break; } else n = nVal; } else { fprintf(stderr, "bad attribute in ListQIFReferenceType\n"); returnValue = true; break; } } if (n == 0) { fprintf(stderr, "required attribute \"n\" missing in ListQIFReferenceType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete n; n = 0; } return returnValue; } NaturalType * ListQIFReferenceType::getn() {return n;} void ListQIFReferenceType::setn(NaturalType * nIn) {n = nIn;} /* ***************************************************************** */ /* class ListTokenType */ ListTokenType::ListTokenType() { } ListTokenType::ListTokenType( XmlNMTOKEN * aXmlNMTOKEN) : XmlNMTOKENLisd(aXmlNMTOKEN) { } ListTokenType::ListTokenType( const char * valueString) : XmlNMTOKENLisd(valueString) { } ListTokenType::~ListTokenType() { } void ListTokenType::printName(FILE * outFile) { fprintf(outFile, "ListTokenType"); } void ListTokenType::printSelf(FILE * outFile) { XmlNMTOKENLisd::printSelf(outFile); } void ListTokenType::oPrintSelf(FILE * outFile) { XmlNMTOKENLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ListUnsignedByteType */ ListUnsignedByteType::ListUnsignedByteType() { } ListUnsignedByteType::ListUnsignedByteType( XmlUnsignedByte * aXmlUnsignedByte) : XmlUnsignedByteLisd(aXmlUnsignedByte) { } ListUnsignedByteType::ListUnsignedByteType( const char * valueString) : XmlUnsignedByteLisd(valueString) { } ListUnsignedByteType::~ListUnsignedByteType() { } void ListUnsignedByteType::printName(FILE * outFile) { fprintf(outFile, "ListUnsignedByteType"); } void ListUnsignedByteType::printSelf(FILE * outFile) { XmlUnsignedByteLisd::printSelf(outFile); } void ListUnsignedByteType::oPrintSelf(FILE * outFile) { XmlUnsignedByteLisd::oPrintSelf(outFile); } /* ***************************************************************** */ /* class Natural2Type */ Natural2Type::Natural2Type() : ListNaturalType() { } Natural2Type::Natural2Type( NaturalType * aNaturalType) : ListNaturalType(aNaturalType) { } Natural2Type::Natural2Type( const char * valueString) : ListNaturalType(valueString) { Natural2TypeCheck(); if (bad) { fprintf(stderr, "Natural2TypeCheck failed\n"); exit(1); } } Natural2Type::~Natural2Type() {} void Natural2Type::printName(FILE * outFile) { fprintf(outFile, "Natural2Type"); } void Natural2Type::printSelf(FILE * outFile) { Natural2TypeCheck(); if (bad) { fprintf(stderr, "Natural2TypeCheck failed\n"); exit(1); } ListNaturalType::printSelf(outFile); } void Natural2Type::oPrintSelf(FILE * outFile) { Natural2TypeCheck(); if (bad) { fprintf(stderr, "Natural2TypeCheck failed\n"); exit(1); } ListNaturalType::oPrintSelf(outFile); } bool Natural2Type::Natural2TypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class NaturalType */ NaturalType::NaturalType() : XmlUnsignedInt() { } NaturalType::NaturalType( const char * valIn) : XmlUnsignedInt( valIn) { if (!bad) bad = ((val < 1)); } NaturalType::~NaturalType() {} bool NaturalType::NaturalTypeIsBad() { if (XmlUnsignedIntIsBad()) return true; return ((val < 1)); } void NaturalType::printName(FILE * outFile) { fprintf(outFile, "NaturalType"); } void NaturalType::printSelf(FILE * outFile) { if (NaturalTypeIsBad()) { fprintf(stderr, "bad NaturalType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::printSelf(outFile); } void NaturalType::oPrintSelf(FILE * outFile) { if (NaturalTypeIsBad()) { fprintf(stderr, "bad NaturalType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::oPrintSelf(outFile); } /* ***************************************************************** */ /* class OrientedLatitudeLongitudeSweepType */ OrientedLatitudeLongitudeSweepType::OrientedLatitudeLongitudeSweepType() : LatitudeLongitudeSweepType() { DirNorthPole = 0; } OrientedLatitudeLongitudeSweepType::OrientedLatitudeLongitudeSweepType( UnitVectorType * DirMeridianPrimeIn, AngleRangeType * DomainLatitudeIn, AngleRangeType * DomainLongitudeIn, UnitVectorType * DirNorthPoleIn) : LatitudeLongitudeSweepType( DirMeridianPrimeIn, DomainLatitudeIn, DomainLongitudeIn) { DirNorthPole = DirNorthPoleIn; } OrientedLatitudeLongitudeSweepType::~OrientedLatitudeLongitudeSweepType() { #ifndef NODESTRUCT delete DirNorthPole; #endif } void OrientedLatitudeLongitudeSweepType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<DirMeridianPrime"); DirMeridianPrime->printSelf(outFile); fprintf(outFile, "</DirMeridianPrime>\n"); doSpaces(0, outFile); fprintf(outFile, "<DomainLatitude"); DomainLatitude->printSelf(outFile); fprintf(outFile, "</DomainLatitude>\n"); doSpaces(0, outFile); fprintf(outFile, "<DomainLongitude"); DomainLongitude->printSelf(outFile); fprintf(outFile, "</DomainLongitude>\n"); doSpaces(0, outFile); fprintf(outFile, "<DirNorthPole"); DirNorthPole->printSelf(outFile); fprintf(outFile, "</DirNorthPole>\n"); doSpaces(-INDENT, outFile); } UnitVectorType * OrientedLatitudeLongitudeSweepType::getDirNorthPole() {return DirNorthPole;} void OrientedLatitudeLongitudeSweepType::setDirNorthPole(UnitVectorType * DirNorthPoleIn) {DirNorthPole = DirNorthPoleIn;} /* ***************************************************************** */ /* class ParameterRangeType */ ParameterRangeType::ParameterRangeType() : ListDoubleType() { } ParameterRangeType::ParameterRangeType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } ParameterRangeType::ParameterRangeType( const char * valueString) : ListDoubleType(valueString) { ParameterRangeTypeCheck(); if (bad) { fprintf(stderr, "ParameterRangeTypeCheck failed\n"); exit(1); } } ParameterRangeType::~ParameterRangeType() {} void ParameterRangeType::printName(FILE * outFile) { fprintf(outFile, "ParameterRangeType"); } void ParameterRangeType::printSelf(FILE * outFile) { ParameterRangeTypeCheck(); if (bad) { fprintf(stderr, "ParameterRangeTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void ParameterRangeType::oPrintSelf(FILE * outFile) { ParameterRangeTypeCheck(); if (bad) { fprintf(stderr, "ParameterRangeTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool ParameterRangeType::ParameterRangeTypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class PlaneType */ PlaneType::PlaneType() { Point = 0; Normal = 0; } PlaneType::PlaneType( PointType * PointIn, UnitVectorType * NormalIn) { Point = PointIn; Normal = NormalIn; } PlaneType::~PlaneType() { #ifndef NODESTRUCT delete Point; delete Normal; #endif } void PlaneType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Point"); Point->printSelf(outFile); fprintf(outFile, "</Point>\n"); doSpaces(0, outFile); fprintf(outFile, "<Normal"); Normal->printSelf(outFile); fprintf(outFile, "</Normal>\n"); doSpaces(-INDENT, outFile); } PointType * PlaneType::getPoint() {return Point;} void PlaneType::setPoint(PointType * PointIn) {Point = PointIn;} UnitVectorType * PlaneType::getNormal() {return Normal;} void PlaneType::setNormal(UnitVectorType * NormalIn) {Normal = NormalIn;} /* ***************************************************************** */ /* class PlaneXType */ PlaneXType::PlaneXType() : PlaneType() { Direction = 0; } PlaneXType::PlaneXType( PointType * PointIn, UnitVectorType * NormalIn, UnitVectorType * DirectionIn) : PlaneType( PointIn, NormalIn) { Direction = DirectionIn; } PlaneXType::~PlaneXType() { #ifndef NODESTRUCT delete Direction; #endif } void PlaneXType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<Point"); Point->printSelf(outFile); fprintf(outFile, "</Point>\n"); doSpaces(0, outFile); fprintf(outFile, "<Normal"); Normal->printSelf(outFile); fprintf(outFile, "</Normal>\n"); doSpaces(0, outFile); fprintf(outFile, "<Direction"); Direction->printSelf(outFile); fprintf(outFile, "</Direction>\n"); doSpaces(-INDENT, outFile); } UnitVectorType * PlaneXType::getDirection() {return Direction;} void PlaneXType::setDirection(UnitVectorType * DirectionIn) {Direction = DirectionIn;} /* ***************************************************************** */ /* class Point2dSimpleType */ Point2dSimpleType::Point2dSimpleType() : ListDoubleType() { } Point2dSimpleType::Point2dSimpleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } Point2dSimpleType::Point2dSimpleType( const char * valueString) : ListDoubleType(valueString) { Point2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "Point2dSimpleTypeCheck failed\n"); exit(1); } } Point2dSimpleType::~Point2dSimpleType() {} void Point2dSimpleType::printName(FILE * outFile) { fprintf(outFile, "Point2dSimpleType"); } void Point2dSimpleType::printSelf(FILE * outFile) { Point2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "Point2dSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void Point2dSimpleType::oPrintSelf(FILE * outFile) { Point2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "Point2dSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool Point2dSimpleType::Point2dSimpleTypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class Point2dSimpleTypeLisd */ Point2dSimpleTypeLisd::Point2dSimpleTypeLisd() {} Point2dSimpleTypeLisd::Point2dSimpleTypeLisd( Point2dSimpleType * aPoint2dSimpleType) { push_back(aPoint2dSimpleType); } Point2dSimpleTypeLisd::Point2dSimpleTypeLisd( Point2dSimpleTypeLisd * aPoint2dSimpleTypeLisd) { *this = *aPoint2dSimpleTypeLisd; } Point2dSimpleTypeLisd::~Point2dSimpleTypeLisd() { #ifndef NODESTRUCT std::list<Point2dSimpleType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void Point2dSimpleTypeLisd::printSelf(FILE * outFile) { std::list<Point2dSimpleType *>::iterator iter; fprintf(outFile, ">"); for (iter = begin(); iter != end(); iter++) { (*iter)->printSelf(outFile); if ((*iter) != back()) fprintf(outFile, " "); } } /* ***************************************************************** */ /* class PointSimpleType */ PointSimpleType::PointSimpleType() : ListDoubleType() { } PointSimpleType::PointSimpleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } PointSimpleType::PointSimpleType( const char * valueString) : ListDoubleType(valueString) { PointSimpleTypeCheck(); if (bad) { fprintf(stderr, "PointSimpleTypeCheck failed\n"); exit(1); } } PointSimpleType::~PointSimpleType() {} void PointSimpleType::printName(FILE * outFile) { fprintf(outFile, "PointSimpleType"); } void PointSimpleType::printSelf(FILE * outFile) { PointSimpleTypeCheck(); if (bad) { fprintf(stderr, "PointSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void PointSimpleType::oPrintSelf(FILE * outFile) { PointSimpleTypeCheck(); if (bad) { fprintf(stderr, "PointSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool PointSimpleType::PointSimpleTypeCheck() { bad = ((size() != 3)); return bad; } /* ***************************************************************** */ /* class PointType */ PointType::PointType() : PointSimpleType() { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } PointType::PointType( XmlDouble * aXmlDouble) : PointSimpleType(aXmlDouble) { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } PointType::PointType( XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : PointSimpleType(aXmlDouble) { decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } PointType::~PointType() { #ifndef NODESTRUCT delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void PointType::printName(FILE * outFile) { fprintf(outFile, "PointType"); } void PointType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; PointTypeCheck(); if (bad) { fprintf(stderr, "PointTypeCheck failed\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool PointType::PointTypeCheck() { PointSimpleTypeCheck(); return bad; } bool PointType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in PointType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in PointType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in PointType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in PointType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in PointType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in PointType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in PointType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in PointType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in PointType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in PointType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in PointType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in PointType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in PointType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in PointType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in PointType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in PointType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in PointType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in PointType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in PointType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in PointType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in PointType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in PointType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in PointType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in PointType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in PointType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in PointType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in PointType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } XmlNonNegativeInteger * PointType::getdecimalPlaces() {return decimalPlaces;} void PointType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * PointType::getlinearUnit() {return linearUnit;} void PointType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * PointType::getsignificantFigures() {return significantFigures;} void PointType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * PointType::getvalidity() {return validity;} void PointType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * PointType::getxDecimalPlaces() {return xDecimalPlaces;} void PointType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * PointType::getxSignificantFigures() {return xSignificantFigures;} void PointType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * PointType::getxValidity() {return xValidity;} void PointType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * PointType::getyDecimalPlaces() {return yDecimalPlaces;} void PointType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * PointType::getySignificantFigures() {return ySignificantFigures;} void PointType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * PointType::getyValidity() {return yValidity;} void PointType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * PointType::getzDecimalPlaces() {return zDecimalPlaces;} void PointType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * PointType::getzSignificantFigures() {return zSignificantFigures;} void PointType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * PointType::getzValidity() {return zValidity;} void PointType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class PolyLineType */ PolyLineType::PolyLineType() : ArrayPointType() { } PolyLineType::PolyLineType( XmlDouble * aXmlDouble) : ArrayPointType(aXmlDouble) { } PolyLineType::PolyLineType( NaturalType * countIn, XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : ArrayPointType(aXmlDouble) { count = countIn; decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } PolyLineType::~PolyLineType() {} void PolyLineType::printName(FILE * outFile) { fprintf(outFile, "PolyLineType"); } void PolyLineType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (count) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "count=\""); count->oPrintSelf(outFile); fprintf(outFile, "\""); } else { fprintf(stderr, "required attribute \"count\" missing\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool PolyLineType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "count") { NaturalType * countVal; if (count) { fprintf(stderr, "two values for count in PolyLineType\n"); returnValue = true; break; } countVal = new NaturalType(decl->val.c_str()); if (countVal->bad) { delete countVal; fprintf(stderr, "bad value %s for count in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else count = countVal; } else if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in PolyLineType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in PolyLineType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in PolyLineType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in PolyLineType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in PolyLineType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in PolyLineType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in PolyLineType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in PolyLineType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in PolyLineType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in PolyLineType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in PolyLineType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in PolyLineType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in PolyLineType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in PolyLineType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in PolyLineType\n"); returnValue = true; break; } } if (count == 0) { fprintf(stderr, "required attribute \"count\" missing in PolyLineType\n"); returnValue = true; } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete count; count = 0; delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } /* ***************************************************************** */ /* class QIFFeaturePairType */ QIFFeaturePairType::QIFFeaturePairType() { FirstFeature = 0; SecondFeature = 0; FirstFeatureZone = 0; SecondFeatureZone = 0; } QIFFeaturePairType::QIFFeaturePairType( QIFReferenceFullType * FirstFeatureIn, QIFReferenceFullType * SecondFeatureIn, QIFReferenceFullType * FirstFeatureZoneIn, QIFReferenceFullType * SecondFeatureZoneIn) { FirstFeature = FirstFeatureIn; SecondFeature = SecondFeatureIn; FirstFeatureZone = FirstFeatureZoneIn; SecondFeatureZone = SecondFeatureZoneIn; } QIFFeaturePairType::~QIFFeaturePairType() { #ifndef NODESTRUCT delete FirstFeature; delete SecondFeature; delete FirstFeatureZone; delete SecondFeatureZone; #endif } void QIFFeaturePairType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<FirstFeature"); FirstFeature->printSelf(outFile); fprintf(outFile, "</FirstFeature>\n"); doSpaces(0, outFile); fprintf(outFile, "<SecondFeature"); SecondFeature->printSelf(outFile); fprintf(outFile, "</SecondFeature>\n"); if (FirstFeatureZone) { doSpaces(0, outFile); fprintf(outFile, "<FirstFeatureZone"); FirstFeatureZone->printSelf(outFile); fprintf(outFile, "</FirstFeatureZone>\n"); } if (SecondFeatureZone) { doSpaces(0, outFile); fprintf(outFile, "<SecondFeatureZone"); SecondFeatureZone->printSelf(outFile); fprintf(outFile, "</SecondFeatureZone>\n"); } doSpaces(-INDENT, outFile); } QIFReferenceFullType * QIFFeaturePairType::getFirstFeature() {return FirstFeature;} void QIFFeaturePairType::setFirstFeature(QIFReferenceFullType * FirstFeatureIn) {FirstFeature = FirstFeatureIn;} QIFReferenceFullType * QIFFeaturePairType::getSecondFeature() {return SecondFeature;} void QIFFeaturePairType::setSecondFeature(QIFReferenceFullType * SecondFeatureIn) {SecondFeature = SecondFeatureIn;} QIFReferenceFullType * QIFFeaturePairType::getFirstFeatureZone() {return FirstFeatureZone;} void QIFFeaturePairType::setFirstFeatureZone(QIFReferenceFullType * FirstFeatureZoneIn) {FirstFeatureZone = FirstFeatureZoneIn;} QIFReferenceFullType * QIFFeaturePairType::getSecondFeatureZone() {return SecondFeatureZone;} void QIFFeaturePairType::setSecondFeatureZone(QIFReferenceFullType * SecondFeatureZoneIn) {SecondFeatureZone = SecondFeatureZoneIn;} /* ***************************************************************** */ /* class QIFFeaturePairTypeLisd */ QIFFeaturePairTypeLisd::QIFFeaturePairTypeLisd() {} QIFFeaturePairTypeLisd::QIFFeaturePairTypeLisd(QIFFeaturePairType * aQIFFeaturePairType) { push_back(aQIFFeaturePairType); } QIFFeaturePairTypeLisd::~QIFFeaturePairTypeLisd() { #ifndef NODESTRUCT std::list<QIFFeaturePairType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QIFFeaturePairTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class QIFIdAndReferenceBaseType */ QIFIdAndReferenceBaseType::QIFIdAndReferenceBaseType() : XmlUnsignedInt() { } QIFIdAndReferenceBaseType::QIFIdAndReferenceBaseType( const char * valIn) : XmlUnsignedInt( valIn) { if (!bad) bad = (false); } QIFIdAndReferenceBaseType::~QIFIdAndReferenceBaseType() {} bool QIFIdAndReferenceBaseType::QIFIdAndReferenceBaseTypeIsBad() { if (XmlUnsignedIntIsBad()) return true; return (false); } void QIFIdAndReferenceBaseType::printName(FILE * outFile) { fprintf(outFile, "QIFIdAndReferenceBaseType"); } void QIFIdAndReferenceBaseType::printSelf(FILE * outFile) { if (QIFIdAndReferenceBaseTypeIsBad()) { fprintf(stderr, "bad QIFIdAndReferenceBaseType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::printSelf(outFile); } void QIFIdAndReferenceBaseType::oPrintSelf(FILE * outFile) { if (QIFIdAndReferenceBaseTypeIsBad()) { fprintf(stderr, "bad QIFIdAndReferenceBaseType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::oPrintSelf(outFile); } /* ***************************************************************** */ /* class QIFIdType */ QIFIdType::QIFIdType() : QIFIdAndReferenceBaseType() {} QIFIdType::QIFIdType( const char * valIn) : QIFIdAndReferenceBaseType( valIn) {} QIFIdType::~QIFIdType() {} bool QIFIdType::QIFIdTypeIsBad() { if (QIFIdAndReferenceBaseTypeIsBad()) return true; return false; } void QIFIdType::printName(FILE * outFile) { fprintf(outFile, "QIFIdType"); } void QIFIdType::printSelf(FILE * outFile) { if (QIFIdTypeIsBad()) { fprintf(stderr, "bad QIFIdType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::printSelf(outFile); } void QIFIdType::oPrintSelf(FILE * outFile) { if (QIFIdTypeIsBad()) { fprintf(stderr, "bad QIFIdType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::oPrintSelf(outFile); } /* ***************************************************************** */ /* class QIFReferenceActiveType */ QIFReferenceActiveType::QIFReferenceActiveType() : QIFReferenceType() { active = 0; val = 0; } QIFReferenceActiveType::QIFReferenceActiveType( const char * valStringIn) : QIFReferenceType(valStringIn) { active = 0; } QIFReferenceActiveType::QIFReferenceActiveType( XmlBoolean * activeIn, QIFReferenceSimpleType * xIdIn, const char * valStringIn) : QIFReferenceType(valStringIn) { active = activeIn; xId = xIdIn; } QIFReferenceActiveType::~QIFReferenceActiveType() { #ifndef NODESTRUCT delete active; #endif } void QIFReferenceActiveType::printName(FILE * outFile) { fprintf(outFile, "QIFReferenceActiveType"); } void QIFReferenceActiveType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; QIFReferenceActiveTypeIsBad(); if (bad) { fprintf(stderr, "QIFReferenceActiveTypeIsBad failed\n"); exit(1); } if (active) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "active=\""); active->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xId=\""); xId->oPrintSelf(outFile); fprintf(outFile, "\""); } XmlUnsignedInt::printSelf(outFile); } bool QIFReferenceActiveType::QIFReferenceActiveTypeIsBad() { QIFReferenceTypeIsBad(); return bad; } bool QIFReferenceActiveType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "active") { XmlBoolean * activeVal; if (active) { fprintf(stderr, "two values for active in QIFReferenceActiveType\n"); returnValue = true; break; } activeVal = new XmlBoolean(decl->val.c_str()); if (activeVal->bad) { delete activeVal; fprintf(stderr, "bad value %s for active in QIFReferenceActiveType\n", decl->val.c_str()); returnValue = true; break; } else active = activeVal; } else if (decl->name == "xId") { QIFReferenceSimpleType * xIdVal; if (xId) { fprintf(stderr, "two values for xId in QIFReferenceActiveType\n"); returnValue = true; break; } xIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (xIdVal->bad) { delete xIdVal; fprintf(stderr, "bad value %s for xId in QIFReferenceActiveType\n", decl->val.c_str()); returnValue = true; break; } else xId = xIdVal; } else { fprintf(stderr, "bad attribute in QIFReferenceActiveType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete active; active = 0; delete xId; xId = 0; } return returnValue; } XmlBoolean * QIFReferenceActiveType::getactive() {return active;} void QIFReferenceActiveType::setactive(XmlBoolean * activeIn) {active = activeIn;} /* ***************************************************************** */ /* class QIFReferenceActiveTypeLisd */ QIFReferenceActiveTypeLisd::QIFReferenceActiveTypeLisd() {} QIFReferenceActiveTypeLisd::QIFReferenceActiveTypeLisd(QIFReferenceActiveType * aQIFReferenceActiveType) { push_back(aQIFReferenceActiveType); } QIFReferenceActiveTypeLisd::~QIFReferenceActiveTypeLisd() { #ifndef NODESTRUCT std::list<QIFReferenceActiveType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QIFReferenceActiveTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class QIFReferenceBaseType */ QIFReferenceBaseType::QIFReferenceBaseType() : QIFIdAndReferenceBaseType() {} QIFReferenceBaseType::QIFReferenceBaseType( const char * valIn) : QIFIdAndReferenceBaseType( valIn) {} QIFReferenceBaseType::~QIFReferenceBaseType() {} bool QIFReferenceBaseType::QIFReferenceBaseTypeIsBad() { if (QIFIdAndReferenceBaseTypeIsBad()) return true; return false; } void QIFReferenceBaseType::printName(FILE * outFile) { fprintf(outFile, "QIFReferenceBaseType"); } void QIFReferenceBaseType::printSelf(FILE * outFile) { if (QIFReferenceBaseTypeIsBad()) { fprintf(stderr, "bad QIFReferenceBaseType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::printSelf(outFile); } void QIFReferenceBaseType::oPrintSelf(FILE * outFile) { if (QIFReferenceBaseTypeIsBad()) { fprintf(stderr, "bad QIFReferenceBaseType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::oPrintSelf(outFile); } /* ***************************************************************** */ /* class QIFReferenceFullType */ QIFReferenceFullType::QIFReferenceFullType() : QIFReferenceType() { asmPathId = 0; asmPathXId = 0; val = 0; } QIFReferenceFullType::QIFReferenceFullType( const char * valStringIn) : QIFReferenceType(valStringIn) { asmPathId = 0; asmPathXId = 0; } QIFReferenceFullType::QIFReferenceFullType( QIFReferenceSimpleType * asmPathIdIn, QIFReferenceSimpleType * asmPathXIdIn, QIFReferenceSimpleType * xIdIn, const char * valStringIn) : QIFReferenceType(valStringIn) { asmPathId = asmPathIdIn; asmPathXId = asmPathXIdIn; xId = xIdIn; } QIFReferenceFullType::~QIFReferenceFullType() { #ifndef NODESTRUCT delete asmPathId; delete asmPathXId; #endif } void QIFReferenceFullType::printName(FILE * outFile) { fprintf(outFile, "QIFReferenceFullType"); } void QIFReferenceFullType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; QIFReferenceFullTypeIsBad(); if (bad) { fprintf(stderr, "QIFReferenceFullTypeIsBad failed\n"); exit(1); } if (asmPathId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathId=\""); asmPathId->oPrintSelf(outFile); fprintf(outFile, "\""); } if (asmPathXId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "asmPathXId=\""); asmPathXId->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xId=\""); xId->oPrintSelf(outFile); fprintf(outFile, "\""); } XmlUnsignedInt::printSelf(outFile); } bool QIFReferenceFullType::QIFReferenceFullTypeIsBad() { QIFReferenceTypeIsBad(); return bad; } bool QIFReferenceFullType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "asmPathId") { QIFReferenceSimpleType * asmPathIdVal; if (asmPathId) { fprintf(stderr, "two values for asmPathId in QIFReferenceFullType\n"); returnValue = true; break; } asmPathIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathIdVal->bad) { delete asmPathIdVal; fprintf(stderr, "bad value %s for asmPathId in QIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathId = asmPathIdVal; } else if (decl->name == "asmPathXId") { QIFReferenceSimpleType * asmPathXIdVal; if (asmPathXId) { fprintf(stderr, "two values for asmPathXId in QIFReferenceFullType\n"); returnValue = true; break; } asmPathXIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (asmPathXIdVal->bad) { delete asmPathXIdVal; fprintf(stderr, "bad value %s for asmPathXId in QIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else asmPathXId = asmPathXIdVal; } else if (decl->name == "xId") { QIFReferenceSimpleType * xIdVal; if (xId) { fprintf(stderr, "two values for xId in QIFReferenceFullType\n"); returnValue = true; break; } xIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (xIdVal->bad) { delete xIdVal; fprintf(stderr, "bad value %s for xId in QIFReferenceFullType\n", decl->val.c_str()); returnValue = true; break; } else xId = xIdVal; } else { fprintf(stderr, "bad attribute in QIFReferenceFullType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete asmPathId; asmPathId = 0; delete asmPathXId; asmPathXId = 0; delete xId; xId = 0; } return returnValue; } QIFReferenceSimpleType * QIFReferenceFullType::getasmPathId() {return asmPathId;} void QIFReferenceFullType::setasmPathId(QIFReferenceSimpleType * asmPathIdIn) {asmPathId = asmPathIdIn;} QIFReferenceSimpleType * QIFReferenceFullType::getasmPathXId() {return asmPathXId;} void QIFReferenceFullType::setasmPathXId(QIFReferenceSimpleType * asmPathXIdIn) {asmPathXId = asmPathXIdIn;} /* ***************************************************************** */ /* class QIFReferenceFullTypeLisd */ QIFReferenceFullTypeLisd::QIFReferenceFullTypeLisd() {} QIFReferenceFullTypeLisd::QIFReferenceFullTypeLisd(QIFReferenceFullType * aQIFReferenceFullType) { push_back(aQIFReferenceFullType); } QIFReferenceFullTypeLisd::~QIFReferenceFullTypeLisd() { #ifndef NODESTRUCT std::list<QIFReferenceFullType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QIFReferenceFullTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class QIFReferenceSimpleType */ QIFReferenceSimpleType::QIFReferenceSimpleType() : QIFReferenceBaseType() {} QIFReferenceSimpleType::QIFReferenceSimpleType( const char * valIn) : QIFReferenceBaseType( valIn) {} QIFReferenceSimpleType::~QIFReferenceSimpleType() {} bool QIFReferenceSimpleType::QIFReferenceSimpleTypeIsBad() { if (QIFReferenceBaseTypeIsBad()) return true; return false; } void QIFReferenceSimpleType::printName(FILE * outFile) { fprintf(outFile, "QIFReferenceSimpleType"); } void QIFReferenceSimpleType::printSelf(FILE * outFile) { if (QIFReferenceSimpleTypeIsBad()) { fprintf(stderr, "bad QIFReferenceSimpleType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::printSelf(outFile); } void QIFReferenceSimpleType::oPrintSelf(FILE * outFile) { if (QIFReferenceSimpleTypeIsBad()) { fprintf(stderr, "bad QIFReferenceSimpleType value, "); XmlUnsignedInt::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlUnsignedInt::oPrintSelf(outFile); } /* ***************************************************************** */ /* class QIFReferenceType */ QIFReferenceType::QIFReferenceType() : QIFReferenceBaseType() { xId = 0; val = 0; } QIFReferenceType::QIFReferenceType( const char * valStringIn) : QIFReferenceBaseType(valStringIn) { xId = 0; } QIFReferenceType::QIFReferenceType( QIFReferenceSimpleType * xIdIn, const char * valStringIn) : QIFReferenceBaseType(valStringIn) { xId = xIdIn; } QIFReferenceType::~QIFReferenceType() { #ifndef NODESTRUCT delete xId; #endif } void QIFReferenceType::printName(FILE * outFile) { fprintf(outFile, "QIFReferenceType"); } void QIFReferenceType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; QIFReferenceTypeIsBad(); if (bad) { fprintf(stderr, "QIFReferenceTypeIsBad failed\n"); exit(1); } if (xId) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xId=\""); xId->oPrintSelf(outFile); fprintf(outFile, "\""); } XmlUnsignedInt::printSelf(outFile); } bool QIFReferenceType::QIFReferenceTypeIsBad() { QIFReferenceBaseTypeIsBad(); return bad; } bool QIFReferenceType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "xId") { QIFReferenceSimpleType * xIdVal; if (xId) { fprintf(stderr, "two values for xId in QIFReferenceType\n"); returnValue = true; break; } xIdVal = new QIFReferenceSimpleType(decl->val.c_str()); if (xIdVal->bad) { delete xIdVal; fprintf(stderr, "bad value %s for xId in QIFReferenceType\n", decl->val.c_str()); returnValue = true; break; } else xId = xIdVal; } else { fprintf(stderr, "bad attribute in QIFReferenceType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete xId; xId = 0; } return returnValue; } QIFReferenceSimpleType * QIFReferenceType::getxId() {return xId;} void QIFReferenceType::setxId(QIFReferenceSimpleType * xIdIn) {xId = xIdIn;} /* ***************************************************************** */ /* class QIFReferenceTypeLisd */ QIFReferenceTypeLisd::QIFReferenceTypeLisd() {} QIFReferenceTypeLisd::QIFReferenceTypeLisd(QIFReferenceType * aQIFReferenceType) { push_back(aQIFReferenceType); } QIFReferenceTypeLisd::~QIFReferenceTypeLisd() { #ifndef NODESTRUCT std::list<QIFReferenceType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QIFReferenceTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class QPIdFullReferenceType */ QPIdFullReferenceType::QPIdFullReferenceType() { ItemQPId = 0; DocumentQPId = 0; } QPIdFullReferenceType::QPIdFullReferenceType( QPIdReferenceType * ItemQPIdIn, QPIdReferenceTypeLisd * DocumentQPIdIn) { ItemQPId = ItemQPIdIn; DocumentQPId = DocumentQPIdIn; } QPIdFullReferenceType::~QPIdFullReferenceType() { #ifndef NODESTRUCT delete ItemQPId; delete DocumentQPId; #endif } void QPIdFullReferenceType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<ItemQPId"); ItemQPId->printSelf(outFile); fprintf(outFile, "</ItemQPId>\n"); { if (!DocumentQPId) { DocumentQPId = new QPIdReferenceTypeLisd; } std::list<QPIdReferenceType *>::iterator iter; for (iter = DocumentQPId->begin(); iter != DocumentQPId->end(); iter++) {// list may be empty doSpaces(0, outFile); fprintf(outFile, "<DocumentQPId"); (*iter)->printSelf(outFile); fprintf(outFile, "</DocumentQPId>\n"); } } doSpaces(-INDENT, outFile); } QPIdReferenceType * QPIdFullReferenceType::getItemQPId() {return ItemQPId;} void QPIdFullReferenceType::setItemQPId(QPIdReferenceType * ItemQPIdIn) {ItemQPId = ItemQPIdIn;} QPIdReferenceTypeLisd * QPIdFullReferenceType::getDocumentQPId() {return DocumentQPId;} void QPIdFullReferenceType::setDocumentQPId(QPIdReferenceTypeLisd * DocumentQPIdIn) {DocumentQPId = DocumentQPIdIn;} /* ***************************************************************** */ /* class QPIdFullReferenceTypeLisd */ QPIdFullReferenceTypeLisd::QPIdFullReferenceTypeLisd() {} QPIdFullReferenceTypeLisd::QPIdFullReferenceTypeLisd(QPIdFullReferenceType * aQPIdFullReferenceType) { push_back(aQPIdFullReferenceType); } QPIdFullReferenceTypeLisd::~QPIdFullReferenceTypeLisd() { #ifndef NODESTRUCT std::list<QPIdFullReferenceType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QPIdFullReferenceTypeLisd::printSelf(FILE * outFile){} /* ***************************************************************** */ /* class QPIdReferenceType */ QPIdReferenceType::QPIdReferenceType() : XmlToken() { } QPIdReferenceType::QPIdReferenceType( const char * valIn) : XmlToken( valIn) { if (!bad) { boost::regex pattern; const char * regexp = "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$"; pattern = boost::regex(regexp, boost::regex::extended|boost::regex::no_except); if (pattern.empty()) fprintf(stderr, "cannot handle \"%s\", so not checking %s\n", regexp, val.c_str()); else bad = !boost::regex_search(val, pattern); } } QPIdReferenceType::~QPIdReferenceType() {} bool QPIdReferenceType::QPIdReferenceTypeIsBad() { boost::regex pattern; const char * regexp = "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$"; if (XmlTokenIsBad() == true) return true; pattern = boost::regex(regexp, boost::regex::extended|boost::regex::no_except); if (pattern.empty()) { fprintf(stderr, "cannot handle \"%s\", so not checking %s\n", regexp, val.c_str()); return false; } return !boost::regex_search(val, pattern); } void QPIdReferenceType::printName(FILE * outFile) { fprintf(outFile, "QPIdReferenceType"); } void QPIdReferenceType::printSelf(FILE * outFile) { if (QPIdReferenceTypeIsBad()) { fprintf(stderr, "bad QPIdReferenceType value, "); XmlToken::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlToken::printSelf(outFile); } void QPIdReferenceType::oPrintSelf(FILE * outFile) { if (QPIdReferenceTypeIsBad()) { fprintf(stderr, "bad QPIdReferenceType value, "); XmlToken::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlToken::oPrintSelf(outFile); } /* ***************************************************************** */ /* class QPIdReferenceTypeLisd */ QPIdReferenceTypeLisd::QPIdReferenceTypeLisd() {} QPIdReferenceTypeLisd::QPIdReferenceTypeLisd( QPIdReferenceType * aQPIdReferenceType) { push_back(aQPIdReferenceType); } QPIdReferenceTypeLisd::QPIdReferenceTypeLisd( QPIdReferenceTypeLisd * aQPIdReferenceTypeLisd) { *this = *aQPIdReferenceTypeLisd; } QPIdReferenceTypeLisd::~QPIdReferenceTypeLisd() { #ifndef NODESTRUCT std::list<QPIdReferenceType *>::iterator iter; for (iter = begin(); iter != end(); iter++) { delete *iter; } #endif } void QPIdReferenceTypeLisd::printSelf(FILE * outFile) { std::list<QPIdReferenceType *>::iterator iter; fprintf(outFile, ">"); for (iter = begin(); iter != end(); iter++) { (*iter)->printSelf(outFile); if ((*iter) != back()) fprintf(outFile, " "); } } /* ***************************************************************** */ /* class QPIdType */ QPIdType::QPIdType() : XmlToken() { } QPIdType::QPIdType( const char * valIn) : XmlToken( valIn) { if (!bad) { boost::regex pattern; const char * regexp = "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$"; pattern = boost::regex(regexp, boost::regex::extended|boost::regex::no_except); if (pattern.empty()) fprintf(stderr, "cannot handle \"%s\", so not checking %s\n", regexp, val.c_str()); else bad = !boost::regex_search(val, pattern); } } QPIdType::~QPIdType() {} bool QPIdType::QPIdTypeIsBad() { boost::regex pattern; const char * regexp = "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$"; if (XmlTokenIsBad() == true) return true; pattern = boost::regex(regexp, boost::regex::extended|boost::regex::no_except); if (pattern.empty()) { fprintf(stderr, "cannot handle \"%s\", so not checking %s\n", regexp, val.c_str()); return false; } return !boost::regex_search(val, pattern); } void QPIdType::printName(FILE * outFile) { fprintf(outFile, "QPIdType"); } void QPIdType::printSelf(FILE * outFile) { if (QPIdTypeIsBad()) { fprintf(stderr, "bad QPIdType value, "); XmlToken::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlToken::printSelf(outFile); } void QPIdType::oPrintSelf(FILE * outFile) { if (QPIdTypeIsBad()) { fprintf(stderr, "bad QPIdType value, "); XmlToken::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlToken::oPrintSelf(outFile); } /* ***************************************************************** */ /* class SweepType */ SweepType::SweepType() { DirBeg = 0; DomainAngle = 0; } SweepType::SweepType( UnitVectorType * DirBegIn, AngleRangeType * DomainAngleIn) { DirBeg = DirBegIn; DomainAngle = DomainAngleIn; } SweepType::~SweepType() { #ifndef NODESTRUCT delete DirBeg; delete DomainAngle; #endif } void SweepType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<DirBeg"); DirBeg->printSelf(outFile); fprintf(outFile, "</DirBeg>\n"); doSpaces(0, outFile); fprintf(outFile, "<DomainAngle"); DomainAngle->printSelf(outFile); fprintf(outFile, "</DomainAngle>\n"); doSpaces(-INDENT, outFile); } UnitVectorType * SweepType::getDirBeg() {return DirBeg;} void SweepType::setDirBeg(UnitVectorType * DirBegIn) {DirBeg = DirBegIn;} AngleRangeType * SweepType::getDomainAngle() {return DomainAngle;} void SweepType::setDomainAngle(AngleRangeType * DomainAngleIn) {DomainAngle = DomainAngleIn;} /* ***************************************************************** */ /* class TransformMatrixType */ TransformMatrixType::TransformMatrixType() : CoordinateSystemCoreType() { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } TransformMatrixType::TransformMatrixType( TransformRotationType * RotationIn, PointSimpleType * OriginIn) : CoordinateSystemCoreType( RotationIn, OriginIn) { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } TransformMatrixType::TransformMatrixType( TransformRotationType * RotationIn, PointSimpleType * OriginIn, XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn) : CoordinateSystemCoreType( RotationIn, OriginIn) { decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } TransformMatrixType::~TransformMatrixType() { #ifndef NODESTRUCT delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void TransformMatrixType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); if (Rotation) { doSpaces(0, outFile); fprintf(outFile, "<Rotation"); Rotation->printSelf(outFile); doSpaces(0, outFile); fprintf(outFile, "</Rotation>\n"); } if (Origin) { doSpaces(0, outFile); fprintf(outFile, "<Origin"); Origin->printSelf(outFile); fprintf(outFile, "</Origin>\n"); } doSpaces(-INDENT, outFile); } bool TransformMatrixType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in TransformMatrixType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in TransformMatrixType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in TransformMatrixType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in TransformMatrixType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in TransformMatrixType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in TransformMatrixType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in TransformMatrixType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in TransformMatrixType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in TransformMatrixType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in TransformMatrixType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in TransformMatrixType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in TransformMatrixType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in TransformMatrixType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in TransformMatrixType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in TransformMatrixType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } XmlNonNegativeInteger * TransformMatrixType::getdecimalPlaces() {return decimalPlaces;} void TransformMatrixType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * TransformMatrixType::getlinearUnit() {return linearUnit;} void TransformMatrixType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * TransformMatrixType::getsignificantFigures() {return significantFigures;} void TransformMatrixType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * TransformMatrixType::getvalidity() {return validity;} void TransformMatrixType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * TransformMatrixType::getxDecimalPlaces() {return xDecimalPlaces;} void TransformMatrixType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * TransformMatrixType::getxSignificantFigures() {return xSignificantFigures;} void TransformMatrixType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * TransformMatrixType::getxValidity() {return xValidity;} void TransformMatrixType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * TransformMatrixType::getyDecimalPlaces() {return yDecimalPlaces;} void TransformMatrixType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * TransformMatrixType::getySignificantFigures() {return ySignificantFigures;} void TransformMatrixType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * TransformMatrixType::getyValidity() {return yValidity;} void TransformMatrixType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * TransformMatrixType::getzDecimalPlaces() {return zDecimalPlaces;} void TransformMatrixType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * TransformMatrixType::getzSignificantFigures() {return zSignificantFigures;} void TransformMatrixType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * TransformMatrixType::getzValidity() {return zValidity;} void TransformMatrixType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class TransformRotationType */ TransformRotationType::TransformRotationType() { XDirection = 0; YDirection = 0; ZDirection = 0; } TransformRotationType::TransformRotationType( UnitVectorSimpleType * XDirectionIn, UnitVectorSimpleType * YDirectionIn, UnitVectorSimpleType * ZDirectionIn) { XDirection = XDirectionIn; YDirection = YDirectionIn; ZDirection = ZDirectionIn; } TransformRotationType::~TransformRotationType() { #ifndef NODESTRUCT delete XDirection; delete YDirection; delete ZDirection; #endif } void TransformRotationType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); doSpaces(0, outFile); fprintf(outFile, "<XDirection"); XDirection->printSelf(outFile); fprintf(outFile, "</XDirection>\n"); doSpaces(0, outFile); fprintf(outFile, "<YDirection"); YDirection->printSelf(outFile); fprintf(outFile, "</YDirection>\n"); doSpaces(0, outFile); fprintf(outFile, "<ZDirection"); ZDirection->printSelf(outFile); fprintf(outFile, "</ZDirection>\n"); doSpaces(-INDENT, outFile); } UnitVectorSimpleType * TransformRotationType::getXDirection() {return XDirection;} void TransformRotationType::setXDirection(UnitVectorSimpleType * XDirectionIn) {XDirection = XDirectionIn;} UnitVectorSimpleType * TransformRotationType::getYDirection() {return YDirection;} void TransformRotationType::setYDirection(UnitVectorSimpleType * YDirectionIn) {YDirection = YDirectionIn;} UnitVectorSimpleType * TransformRotationType::getZDirection() {return ZDirection;} void TransformRotationType::setZDirection(UnitVectorSimpleType * ZDirectionIn) {ZDirection = ZDirectionIn;} /* ***************************************************************** */ /* class UnitVector2dSimpleType */ UnitVector2dSimpleType::UnitVector2dSimpleType() : ListDoubleType() { } UnitVector2dSimpleType::UnitVector2dSimpleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } UnitVector2dSimpleType::UnitVector2dSimpleType( const char * valueString) : ListDoubleType(valueString) { UnitVector2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVector2dSimpleTypeCheck failed\n"); exit(1); } } UnitVector2dSimpleType::~UnitVector2dSimpleType() {} void UnitVector2dSimpleType::printName(FILE * outFile) { fprintf(outFile, "UnitVector2dSimpleType"); } void UnitVector2dSimpleType::printSelf(FILE * outFile) { UnitVector2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVector2dSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void UnitVector2dSimpleType::oPrintSelf(FILE * outFile) { UnitVector2dSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVector2dSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool UnitVector2dSimpleType::UnitVector2dSimpleTypeCheck() { bad = ((size() != 2)); return bad; } /* ***************************************************************** */ /* class UnitVectorSimpleType */ UnitVectorSimpleType::UnitVectorSimpleType() : ListDoubleType() { } UnitVectorSimpleType::UnitVectorSimpleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } UnitVectorSimpleType::UnitVectorSimpleType( const char * valueString) : ListDoubleType(valueString) { UnitVectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVectorSimpleTypeCheck failed\n"); exit(1); } } UnitVectorSimpleType::~UnitVectorSimpleType() {} void UnitVectorSimpleType::printName(FILE * outFile) { fprintf(outFile, "UnitVectorSimpleType"); } void UnitVectorSimpleType::printSelf(FILE * outFile) { UnitVectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVectorSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void UnitVectorSimpleType::oPrintSelf(FILE * outFile) { UnitVectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "UnitVectorSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool UnitVectorSimpleType::UnitVectorSimpleTypeCheck() { bad = ((size() != 3)); return bad; } /* ***************************************************************** */ /* class UnitVectorType */ UnitVectorType::UnitVectorType() : UnitVectorSimpleType() { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } UnitVectorType::UnitVectorType( XmlDouble * aXmlDouble) : UnitVectorSimpleType(aXmlDouble) { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } UnitVectorType::UnitVectorType( XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : UnitVectorSimpleType(aXmlDouble) { decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } UnitVectorType::~UnitVectorType() { #ifndef NODESTRUCT delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void UnitVectorType::printName(FILE * outFile) { fprintf(outFile, "UnitVectorType"); } void UnitVectorType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; UnitVectorTypeCheck(); if (bad) { fprintf(stderr, "UnitVectorTypeCheck failed\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool UnitVectorType::UnitVectorTypeCheck() { UnitVectorSimpleTypeCheck(); return bad; } bool UnitVectorType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in UnitVectorType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in UnitVectorType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in UnitVectorType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in UnitVectorType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in UnitVectorType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in UnitVectorType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in UnitVectorType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in UnitVectorType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in UnitVectorType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in UnitVectorType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in UnitVectorType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in UnitVectorType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in UnitVectorType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in UnitVectorType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in UnitVectorType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } XmlNonNegativeInteger * UnitVectorType::getdecimalPlaces() {return decimalPlaces;} void UnitVectorType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * UnitVectorType::getlinearUnit() {return linearUnit;} void UnitVectorType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * UnitVectorType::getsignificantFigures() {return significantFigures;} void UnitVectorType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * UnitVectorType::getvalidity() {return validity;} void UnitVectorType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * UnitVectorType::getxDecimalPlaces() {return xDecimalPlaces;} void UnitVectorType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * UnitVectorType::getxSignificantFigures() {return xSignificantFigures;} void UnitVectorType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * UnitVectorType::getxValidity() {return xValidity;} void UnitVectorType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * UnitVectorType::getyDecimalPlaces() {return yDecimalPlaces;} void UnitVectorType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * UnitVectorType::getySignificantFigures() {return ySignificantFigures;} void UnitVectorType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * UnitVectorType::getyValidity() {return yValidity;} void UnitVectorType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * UnitVectorType::getzDecimalPlaces() {return zDecimalPlaces;} void UnitVectorType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * UnitVectorType::getzSignificantFigures() {return zSignificantFigures;} void UnitVectorType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * UnitVectorType::getzValidity() {return zValidity;} void UnitVectorType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class UserDataXMLType */ UserDataXMLType::UserDataXMLType() : XmlString() { } UserDataXMLType::UserDataXMLType( const char * valIn) : XmlString( valIn) {} UserDataXMLType::~UserDataXMLType() {} bool UserDataXMLType::UserDataXMLTypeIsBad() { return (false); } void UserDataXMLType::printName(FILE * outFile) { fprintf(outFile, "UserDataXMLType"); } void UserDataXMLType::printSelf(FILE * outFile) { if (UserDataXMLTypeIsBad()) { fprintf(stderr, "bad UserDataXMLType value, "); XmlString::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlString::printSelf(outFile); } void UserDataXMLType::oPrintSelf(FILE * outFile) { if (UserDataXMLTypeIsBad()) { fprintf(stderr, "bad UserDataXMLType value, "); XmlString::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlString::oPrintSelf(outFile); } /* ***************************************************************** */ /* class ValidationPointsType */ ValidationPointsType::ValidationPointsType() { ValidationPoint_1004 = 0; ValidationPoint_1005 = 0; } ValidationPointsType::ValidationPointsType( ValidationPoint_1004_Type * ValidationPoint_1004In, ValidationPoint_1005_Type * ValidationPoint_1005In) { ValidationPoint_1004 = ValidationPoint_1004In; ValidationPoint_1005 = ValidationPoint_1005In; } ValidationPointsType::~ValidationPointsType() { #ifndef NODESTRUCT delete ValidationPoint_1004; delete ValidationPoint_1005; #endif } void ValidationPointsType::printSelf(FILE * outFile) { fprintf(outFile, ">\n"); doSpaces(+INDENT, outFile); ValidationPoint_1004->printSelf(outFile); if (ValidationPoint_1005) { ValidationPoint_1005->printSelf(outFile); } doSpaces(-INDENT, outFile); } ValidationPoint_1004_Type * ValidationPointsType::getValidationPoint_1004() {return ValidationPoint_1004;} void ValidationPointsType::setValidationPoint_1004(ValidationPoint_1004_Type * ValidationPoint_1004In) {ValidationPoint_1004 = ValidationPoint_1004In;} ValidationPoint_1005_Type * ValidationPointsType::getValidationPoint_1005() {return ValidationPoint_1005;} void ValidationPointsType::setValidationPoint_1005(ValidationPoint_1005_Type * ValidationPoint_1005In) {ValidationPoint_1005 = ValidationPoint_1005In;} /* ***************************************************************** */ /* class ValidityEnumType */ ValidityEnumType::ValidityEnumType() : XmlNMTOKEN() { } ValidityEnumType::ValidityEnumType( const char * valIn) : XmlNMTOKEN( valIn) { if (!bad) bad = (strcmp(val.c_str(), "REPORTED") && strcmp(val.c_str(), "DUMMY") && strcmp(val.c_str(), "MOOT") && strcmp(val.c_str(), "DERIVED") && strcmp(val.c_str(), "SET")); } ValidityEnumType::~ValidityEnumType() {} bool ValidityEnumType::ValidityEnumTypeIsBad() { return (strcmp(val.c_str(), "REPORTED") && strcmp(val.c_str(), "DUMMY") && strcmp(val.c_str(), "MOOT") && strcmp(val.c_str(), "DERIVED") && strcmp(val.c_str(), "SET")); } void ValidityEnumType::printName(FILE * outFile) { fprintf(outFile, "ValidityEnumType"); } void ValidityEnumType::printSelf(FILE * outFile) { if (ValidityEnumTypeIsBad()) { fprintf(stderr, "bad ValidityEnumType value, "); XmlNMTOKEN::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlNMTOKEN::printSelf(outFile); } void ValidityEnumType::oPrintSelf(FILE * outFile) { if (ValidityEnumTypeIsBad()) { fprintf(stderr, "bad ValidityEnumType value, "); XmlNMTOKEN::printBad(stderr); fprintf(stderr, " exiting\n"); exit(1); } XmlNMTOKEN::oPrintSelf(outFile); } /* ***************************************************************** */ /* class VectorSimpleType */ VectorSimpleType::VectorSimpleType() : ListDoubleType() { } VectorSimpleType::VectorSimpleType( XmlDouble * aXmlDouble) : ListDoubleType(aXmlDouble) { } VectorSimpleType::VectorSimpleType( const char * valueString) : ListDoubleType(valueString) { VectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "VectorSimpleTypeCheck failed\n"); exit(1); } } VectorSimpleType::~VectorSimpleType() {} void VectorSimpleType::printName(FILE * outFile) { fprintf(outFile, "VectorSimpleType"); } void VectorSimpleType::printSelf(FILE * outFile) { VectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "VectorSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::printSelf(outFile); } void VectorSimpleType::oPrintSelf(FILE * outFile) { VectorSimpleTypeCheck(); if (bad) { fprintf(stderr, "VectorSimpleTypeCheck failed\n"); exit(1); } ListDoubleType::oPrintSelf(outFile); } bool VectorSimpleType::VectorSimpleTypeCheck() { bad = ((size() != 3)); return bad; } /* ***************************************************************** */ /* class VectorType */ VectorType::VectorType() : VectorSimpleType() { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } VectorType::VectorType( XmlDouble * aXmlDouble) : VectorSimpleType(aXmlDouble) { decimalPlaces = 0; linearUnit = 0; significantFigures = 0; validity = 0; xDecimalPlaces = 0; xSignificantFigures = 0; xValidity = 0; yDecimalPlaces = 0; ySignificantFigures = 0; yValidity = 0; zDecimalPlaces = 0; zSignificantFigures = 0; zValidity = 0; } VectorType::VectorType( XmlNonNegativeInteger * decimalPlacesIn, XmlToken * linearUnitIn, XmlNonNegativeInteger * significantFiguresIn, ValidityEnumType * validityIn, XmlNonNegativeInteger * xDecimalPlacesIn, XmlNonNegativeInteger * xSignificantFiguresIn, ValidityEnumType * xValidityIn, XmlNonNegativeInteger * yDecimalPlacesIn, XmlNonNegativeInteger * ySignificantFiguresIn, ValidityEnumType * yValidityIn, XmlNonNegativeInteger * zDecimalPlacesIn, XmlNonNegativeInteger * zSignificantFiguresIn, ValidityEnumType * zValidityIn, XmlDouble * aXmlDouble) : VectorSimpleType(aXmlDouble) { decimalPlaces = decimalPlacesIn; linearUnit = linearUnitIn; significantFigures = significantFiguresIn; validity = validityIn; xDecimalPlaces = xDecimalPlacesIn; xSignificantFigures = xSignificantFiguresIn; xValidity = xValidityIn; yDecimalPlaces = yDecimalPlacesIn; ySignificantFigures = ySignificantFiguresIn; yValidity = yValidityIn; zDecimalPlaces = zDecimalPlacesIn; zSignificantFigures = zSignificantFiguresIn; zValidity = zValidityIn; } VectorType::~VectorType() { #ifndef NODESTRUCT delete decimalPlaces; delete linearUnit; delete significantFigures; delete validity; delete xDecimalPlaces; delete xSignificantFigures; delete xValidity; delete yDecimalPlaces; delete ySignificantFigures; delete yValidity; delete zDecimalPlaces; delete zSignificantFigures; delete zValidity; #endif } void VectorType::printName(FILE * outFile) { fprintf(outFile, "VectorType"); } void VectorType::printSelf(FILE * outFile) { bool printedOne; printedOne = false; VectorTypeCheck(); if (bad) { fprintf(stderr, "VectorTypeCheck failed\n"); exit(1); } if (decimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "decimalPlaces=\""); decimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (linearUnit) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "linearUnit=\""); linearUnit->oPrintSelf(outFile); fprintf(outFile, "\""); } if (significantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "significantFigures=\""); significantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (validity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "validity=\""); validity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xDecimalPlaces=\""); xDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xSignificantFigures=\""); xSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (xValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "xValidity=\""); xValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yDecimalPlaces=\""); yDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (ySignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "ySignificantFigures=\""); ySignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (yValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "yValidity=\""); yValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zDecimalPlaces) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zDecimalPlaces=\""); zDecimalPlaces->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zSignificantFigures) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zSignificantFigures=\""); zSignificantFigures->oPrintSelf(outFile); fprintf(outFile, "\""); } if (zValidity) { if (printedOne) { fprintf(outFile, "\n"); doSpaces(0, outFile); fprintf(outFile, " "); } else { fprintf(outFile, " "); printedOne = true; } fprintf(outFile, "zValidity=\""); zValidity->oPrintSelf(outFile); fprintf(outFile, "\""); } ListDoubleType::printSelf(outFile); } bool VectorType::VectorTypeCheck() { VectorSimpleTypeCheck(); return bad; } bool VectorType::badAttributes( AttributePairLisd * attributes) { std::list<AttributePair *>::iterator iter; AttributePair * decl; bool returnValue; returnValue = false; for (iter = attributes->begin(); iter != attributes->end(); iter++) { decl = *iter; if (decl->name == "decimalPlaces") { XmlNonNegativeInteger * decimalPlacesVal; if (decimalPlaces) { fprintf(stderr, "two values for decimalPlaces in VectorType\n"); returnValue = true; break; } decimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (decimalPlacesVal->bad) { delete decimalPlacesVal; fprintf(stderr, "bad value %s for decimalPlaces in VectorType\n", decl->val.c_str()); returnValue = true; break; } else decimalPlaces = decimalPlacesVal; } else if (decl->name == "linearUnit") { XmlToken * linearUnitVal; if (linearUnit) { fprintf(stderr, "two values for linearUnit in VectorType\n"); returnValue = true; break; } linearUnitVal = new XmlToken(decl->val.c_str()); if (linearUnitVal->bad) { delete linearUnitVal; fprintf(stderr, "bad value %s for linearUnit in VectorType\n", decl->val.c_str()); returnValue = true; break; } else linearUnit = linearUnitVal; } else if (decl->name == "significantFigures") { XmlNonNegativeInteger * significantFiguresVal; if (significantFigures) { fprintf(stderr, "two values for significantFigures in VectorType\n"); returnValue = true; break; } significantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (significantFiguresVal->bad) { delete significantFiguresVal; fprintf(stderr, "bad value %s for significantFigures in VectorType\n", decl->val.c_str()); returnValue = true; break; } else significantFigures = significantFiguresVal; } else if (decl->name == "validity") { ValidityEnumType * validityVal; if (validity) { fprintf(stderr, "two values for validity in VectorType\n"); returnValue = true; break; } validityVal = new ValidityEnumType(decl->val.c_str()); if (validityVal->bad) { delete validityVal; fprintf(stderr, "bad value %s for validity in VectorType\n", decl->val.c_str()); returnValue = true; break; } else validity = validityVal; } else if (decl->name == "xDecimalPlaces") { XmlNonNegativeInteger * xDecimalPlacesVal; if (xDecimalPlaces) { fprintf(stderr, "two values for xDecimalPlaces in VectorType\n"); returnValue = true; break; } xDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xDecimalPlacesVal->bad) { delete xDecimalPlacesVal; fprintf(stderr, "bad value %s for xDecimalPlaces in VectorType\n", decl->val.c_str()); returnValue = true; break; } else xDecimalPlaces = xDecimalPlacesVal; } else if (decl->name == "xSignificantFigures") { XmlNonNegativeInteger * xSignificantFiguresVal; if (xSignificantFigures) { fprintf(stderr, "two values for xSignificantFigures in VectorType\n"); returnValue = true; break; } xSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (xSignificantFiguresVal->bad) { delete xSignificantFiguresVal; fprintf(stderr, "bad value %s for xSignificantFigures in VectorType\n", decl->val.c_str()); returnValue = true; break; } else xSignificantFigures = xSignificantFiguresVal; } else if (decl->name == "xValidity") { ValidityEnumType * xValidityVal; if (xValidity) { fprintf(stderr, "two values for xValidity in VectorType\n"); returnValue = true; break; } xValidityVal = new ValidityEnumType(decl->val.c_str()); if (xValidityVal->bad) { delete xValidityVal; fprintf(stderr, "bad value %s for xValidity in VectorType\n", decl->val.c_str()); returnValue = true; break; } else xValidity = xValidityVal; } else if (decl->name == "yDecimalPlaces") { XmlNonNegativeInteger * yDecimalPlacesVal; if (yDecimalPlaces) { fprintf(stderr, "two values for yDecimalPlaces in VectorType\n"); returnValue = true; break; } yDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (yDecimalPlacesVal->bad) { delete yDecimalPlacesVal; fprintf(stderr, "bad value %s for yDecimalPlaces in VectorType\n", decl->val.c_str()); returnValue = true; break; } else yDecimalPlaces = yDecimalPlacesVal; } else if (decl->name == "ySignificantFigures") { XmlNonNegativeInteger * ySignificantFiguresVal; if (ySignificantFigures) { fprintf(stderr, "two values for ySignificantFigures in VectorType\n"); returnValue = true; break; } ySignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (ySignificantFiguresVal->bad) { delete ySignificantFiguresVal; fprintf(stderr, "bad value %s for ySignificantFigures in VectorType\n", decl->val.c_str()); returnValue = true; break; } else ySignificantFigures = ySignificantFiguresVal; } else if (decl->name == "yValidity") { ValidityEnumType * yValidityVal; if (yValidity) { fprintf(stderr, "two values for yValidity in VectorType\n"); returnValue = true; break; } yValidityVal = new ValidityEnumType(decl->val.c_str()); if (yValidityVal->bad) { delete yValidityVal; fprintf(stderr, "bad value %s for yValidity in VectorType\n", decl->val.c_str()); returnValue = true; break; } else yValidity = yValidityVal; } else if (decl->name == "zDecimalPlaces") { XmlNonNegativeInteger * zDecimalPlacesVal; if (zDecimalPlaces) { fprintf(stderr, "two values for zDecimalPlaces in VectorType\n"); returnValue = true; break; } zDecimalPlacesVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zDecimalPlacesVal->bad) { delete zDecimalPlacesVal; fprintf(stderr, "bad value %s for zDecimalPlaces in VectorType\n", decl->val.c_str()); returnValue = true; break; } else zDecimalPlaces = zDecimalPlacesVal; } else if (decl->name == "zSignificantFigures") { XmlNonNegativeInteger * zSignificantFiguresVal; if (zSignificantFigures) { fprintf(stderr, "two values for zSignificantFigures in VectorType\n"); returnValue = true; break; } zSignificantFiguresVal = new XmlNonNegativeInteger(decl->val.c_str()); if (zSignificantFiguresVal->bad) { delete zSignificantFiguresVal; fprintf(stderr, "bad value %s for zSignificantFigures in VectorType\n", decl->val.c_str()); returnValue = true; break; } else zSignificantFigures = zSignificantFiguresVal; } else if (decl->name == "zValidity") { ValidityEnumType * zValidityVal; if (zValidity) { fprintf(stderr, "two values for zValidity in VectorType\n"); returnValue = true; break; } zValidityVal = new ValidityEnumType(decl->val.c_str()); if (zValidityVal->bad) { delete zValidityVal; fprintf(stderr, "bad value %s for zValidity in VectorType\n", decl->val.c_str()); returnValue = true; break; } else zValidity = zValidityVal; } else { fprintf(stderr, "bad attribute in VectorType\n"); returnValue = true; break; } } for (iter = attributes->begin(); iter != attributes->end(); iter++) { delete *iter; } attributes->clear(); if (returnValue == true) { delete decimalPlaces; decimalPlaces = 0; delete linearUnit; linearUnit = 0; delete significantFigures; significantFigures = 0; delete validity; validity = 0; delete xDecimalPlaces; xDecimalPlaces = 0; delete xSignificantFigures; xSignificantFigures = 0; delete xValidity; xValidity = 0; delete yDecimalPlaces; yDecimalPlaces = 0; delete ySignificantFigures; ySignificantFigures = 0; delete yValidity; yValidity = 0; delete zDecimalPlaces; zDecimalPlaces = 0; delete zSignificantFigures; zSignificantFigures = 0; delete zValidity; zValidity = 0; } return returnValue; } XmlNonNegativeInteger * VectorType::getdecimalPlaces() {return decimalPlaces;} void VectorType::setdecimalPlaces(XmlNonNegativeInteger * decimalPlacesIn) {decimalPlaces = decimalPlacesIn;} XmlToken * VectorType::getlinearUnit() {return linearUnit;} void VectorType::setlinearUnit(XmlToken * linearUnitIn) {linearUnit = linearUnitIn;} XmlNonNegativeInteger * VectorType::getsignificantFigures() {return significantFigures;} void VectorType::setsignificantFigures(XmlNonNegativeInteger * significantFiguresIn) {significantFigures = significantFiguresIn;} ValidityEnumType * VectorType::getvalidity() {return validity;} void VectorType::setvalidity(ValidityEnumType * validityIn) {validity = validityIn;} XmlNonNegativeInteger * VectorType::getxDecimalPlaces() {return xDecimalPlaces;} void VectorType::setxDecimalPlaces(XmlNonNegativeInteger * xDecimalPlacesIn) {xDecimalPlaces = xDecimalPlacesIn;} XmlNonNegativeInteger * VectorType::getxSignificantFigures() {return xSignificantFigures;} void VectorType::setxSignificantFigures(XmlNonNegativeInteger * xSignificantFiguresIn) {xSignificantFigures = xSignificantFiguresIn;} ValidityEnumType * VectorType::getxValidity() {return xValidity;} void VectorType::setxValidity(ValidityEnumType * xValidityIn) {xValidity = xValidityIn;} XmlNonNegativeInteger * VectorType::getyDecimalPlaces() {return yDecimalPlaces;} void VectorType::setyDecimalPlaces(XmlNonNegativeInteger * yDecimalPlacesIn) {yDecimalPlaces = yDecimalPlacesIn;} XmlNonNegativeInteger * VectorType::getySignificantFigures() {return ySignificantFigures;} void VectorType::setySignificantFigures(XmlNonNegativeInteger * ySignificantFiguresIn) {ySignificantFigures = ySignificantFiguresIn;} ValidityEnumType * VectorType::getyValidity() {return yValidity;} void VectorType::setyValidity(ValidityEnumType * yValidityIn) {yValidity = yValidityIn;} XmlNonNegativeInteger * VectorType::getzDecimalPlaces() {return zDecimalPlaces;} void VectorType::setzDecimalPlaces(XmlNonNegativeInteger * zDecimalPlacesIn) {zDecimalPlaces = zDecimalPlacesIn;} XmlNonNegativeInteger * VectorType::getzSignificantFigures() {return zSignificantFigures;} void VectorType::setzSignificantFigures(XmlNonNegativeInteger * zSignificantFiguresIn) {zSignificantFigures = zSignificantFiguresIn;} ValidityEnumType * VectorType::getzValidity() {return zValidity;} void VectorType::setzValidity(ValidityEnumType * zValidityIn) {zValidity = zValidityIn;} /* ***************************************************************** */ /* class ArrayBinaryQIFR_1001_Type */ ArrayBinaryQIFR_1001_Type::ArrayBinaryQIFR_1001_Type() { Id = 0; XIds = 0; } ArrayBinaryQIFR_1001_Type::ArrayBinaryQIFR_1001_Type( QIFReferenceSimpleType * IdIn, ArrayBinaryType * XIdsIn) { Id = IdIn; XIds = XIdsIn; } ArrayBinaryQIFR_1001_Type::~ArrayBinaryQIFR_1001_Type() { #ifndef NODESTRUCT delete Id; delete XIds; #endif } void ArrayBinaryQIFR_1001_Type::printSelf(FILE * outFile) { doSpaces(0, outFile); fprintf(outFile, "<Id"); Id->printSelf(outFile); fprintf(outFile, "</Id>\n"); doSpaces(0, outFile); fprintf(outFile, "<XIds"); XIds->printSelf(outFile); fprintf(outFile, "</XIds>\n"); } QIFReferenceSimpleType * ArrayBinaryQIFR_1001_Type::getId() {return Id;} void ArrayBinaryQIFR_1001_Type::setId(QIFReferenceSimpleType * IdIn) {Id = IdIn;} ArrayBinaryType * ArrayBinaryQIFR_1001_Type::getXIds() {return XIds;} void ArrayBinaryQIFR_1001_Type::setXIds(ArrayBinaryType * XIdsIn) {XIds = XIdsIn;} /* ***************************************************************** */ /* class AttributeUserTy_1002_Type */ AttributeUserTy_1002_Type::AttributeUserTy_1002_Type() { AttributeUserTy_1002_TypePair = 0; } AttributeUserTy_1002_Type::AttributeUserTy_1002_Type( AttributeUserTy_1002_TypeChoicePair * AttributeUserTy_1002_TypePairIn) { AttributeUserTy_1002_TypePair = AttributeUserTy_1002_TypePairIn; } AttributeUserTy_1002_Type::~AttributeUserTy_1002_Type() { #ifndef NODESTRUCT delete AttributeUserTy_1002_TypePair; #endif } void AttributeUserTy_1002_Type::printSelf(FILE * outFile) { AttributeUserTy_1002_TypePair->printSelf(outFile); } AttributeUserTy_1002_TypeChoicePair * AttributeUserTy_1002_Type::getAttributeUserTy_1002_TypePair() {return AttributeUserTy_1002_TypePair;} void AttributeUserTy_1002_Type::setAttributeUserTy_1002_TypePair(AttributeUserTy_1002_TypeChoicePair * AttributeUserTy_1002_TypePairIn) {AttributeUserTy_1002_TypePair = AttributeUserTy_1002_TypePairIn;} /* ***************************************************************** */ /* class AttributeUserTy_1002_TypeChoicePair */ AttributeUserTy_1002_TypeChoicePair::AttributeUserTy_1002_TypeChoicePair() {} AttributeUserTy_1002_TypeChoicePair::AttributeUserTy_1002_TypeChoicePair( whichOne AttributeUserTy_1002_TypeTypeIn, AttributeUserTy_1002_TypeVal AttributeUserTy_1002_TypeValueIn) { AttributeUserTy_1002_TypeType = AttributeUserTy_1002_TypeTypeIn; AttributeUserTy_1002_TypeValue = AttributeUserTy_1002_TypeValueIn; } AttributeUserTy_1002_TypeChoicePair::~AttributeUserTy_1002_TypeChoicePair() { #ifndef NODESTRUCT if (AttributeUserTy_1002_TypeType == UserDataXMLE) delete AttributeUserTy_1002_TypeValue.UserDataXML; else if (AttributeUserTy_1002_TypeType == UserDataBinaryE) delete AttributeUserTy_1002_TypeValue.UserDataBinary; #endif } void AttributeUserTy_1002_TypeChoicePair::printSelf(FILE * outFile) { if (AttributeUserTy_1002_TypeType == UserDataXMLE) { doSpaces(0, outFile); fprintf(outFile, "<UserDataXML"); AttributeUserTy_1002_TypeValue.UserDataXML->printSelf(outFile); fprintf(outFile, "</UserDataXML>\n"); } else if (AttributeUserTy_1002_TypeType == UserDataBinaryE) { doSpaces(0, outFile); fprintf(outFile, "<UserDataBinary"); AttributeUserTy_1002_TypeValue.UserDataBinary->printSelf(outFile); fprintf(outFile, "</UserDataBinary>\n"); } } /* ***************************************************************** */ /* class ListQIFReferenc_1003_Type */ ListQIFReferenc_1003_Type::ListQIFReferenc_1003_Type() { Id = 0; XIds = 0; } ListQIFReferenc_1003_Type::ListQIFReferenc_1003_Type( QIFReferenceSimpleType * IdIn, ListQIFReferenceSimpleType * XIdsIn) { Id = IdIn; XIds = XIdsIn; } ListQIFReferenc_1003_Type::~ListQIFReferenc_1003_Type() { #ifndef NODESTRUCT delete Id; delete XIds; #endif } void ListQIFReferenc_1003_Type::printSelf(FILE * outFile) { doSpaces(0, outFile); fprintf(outFile, "<Id"); Id->printSelf(outFile); fprintf(outFile, "</Id>\n"); doSpaces(0, outFile); fprintf(outFile, "<XIds"); XIds->printSelf(outFile); fprintf(outFile, "</XIds>\n"); } QIFReferenceSimpleType * ListQIFReferenc_1003_Type::getId() {return Id;} void ListQIFReferenc_1003_Type::setId(QIFReferenceSimpleType * IdIn) {Id = IdIn;} ListQIFReferenceSimpleType * ListQIFReferenc_1003_Type::getXIds() {return XIds;} void ListQIFReferenc_1003_Type::setXIds(ListQIFReferenceSimpleType * XIdsIn) {XIds = XIdsIn;} /* ***************************************************************** */ /* class ValidationPoint_1004_Type */ ValidationPoint_1004_Type::ValidationPoint_1004_Type() { ValidationPoint_1004_TypePair = 0; } ValidationPoint_1004_Type::ValidationPoint_1004_Type( ValidationPoint_1004_TypeChoicePair * ValidationPoint_1004_TypePairIn) { ValidationPoint_1004_TypePair = ValidationPoint_1004_TypePairIn; } ValidationPoint_1004_Type::~ValidationPoint_1004_Type() { #ifndef NODESTRUCT delete ValidationPoint_1004_TypePair; #endif } void ValidationPoint_1004_Type::printSelf(FILE * outFile) { ValidationPoint_1004_TypePair->printSelf(outFile); } ValidationPoint_1004_TypeChoicePair * ValidationPoint_1004_Type::getValidationPoint_1004_TypePair() {return ValidationPoint_1004_TypePair;} void ValidationPoint_1004_Type::setValidationPoint_1004_TypePair(ValidationPoint_1004_TypeChoicePair * ValidationPoint_1004_TypePairIn) {ValidationPoint_1004_TypePair = ValidationPoint_1004_TypePairIn;} /* ***************************************************************** */ /* class ValidationPoint_1004_TypeChoicePair */ ValidationPoint_1004_TypeChoicePair::ValidationPoint_1004_TypeChoicePair() {} ValidationPoint_1004_TypeChoicePair::ValidationPoint_1004_TypeChoicePair( whichOne ValidationPoint_1004_TypeTypeIn, ValidationPoint_1004_TypeVal ValidationPoint_1004_TypeValueIn) { ValidationPoint_1004_TypeType = ValidationPoint_1004_TypeTypeIn; ValidationPoint_1004_TypeValue = ValidationPoint_1004_TypeValueIn; } ValidationPoint_1004_TypeChoicePair::~ValidationPoint_1004_TypeChoicePair() { #ifndef NODESTRUCT if (ValidationPoint_1004_TypeType == PointsE) delete ValidationPoint_1004_TypeValue.Points; else if (ValidationPoint_1004_TypeType == PointsBinaryE) delete ValidationPoint_1004_TypeValue.PointsBinary; #endif } void ValidationPoint_1004_TypeChoicePair::printSelf(FILE * outFile) { if (ValidationPoint_1004_TypeType == PointsE) { doSpaces(0, outFile); fprintf(outFile, "<Points"); ValidationPoint_1004_TypeValue.Points->printSelf(outFile); fprintf(outFile, "</Points>\n"); } else if (ValidationPoint_1004_TypeType == PointsBinaryE) { doSpaces(0, outFile); fprintf(outFile, "<PointsBinary"); ValidationPoint_1004_TypeValue.PointsBinary->printSelf(outFile); fprintf(outFile, "</PointsBinary>\n"); } } /* ***************************************************************** */ /* class ValidationPoint_1005_Type */ ValidationPoint_1005_Type::ValidationPoint_1005_Type() { ValidationPoint_1005_TypePair = 0; } ValidationPoint_1005_Type::ValidationPoint_1005_Type( ValidationPoint_1005_TypeChoicePair * ValidationPoint_1005_TypePairIn) { ValidationPoint_1005_TypePair = ValidationPoint_1005_TypePairIn; } ValidationPoint_1005_Type::~ValidationPoint_1005_Type() { #ifndef NODESTRUCT delete ValidationPoint_1005_TypePair; #endif } void ValidationPoint_1005_Type::printSelf(FILE * outFile) { if (ValidationPoint_1005_TypePair) { ValidationPoint_1005_TypePair->printSelf(outFile); } } ValidationPoint_1005_TypeChoicePair * ValidationPoint_1005_Type::getValidationPoint_1005_TypePair() {return ValidationPoint_1005_TypePair;} void ValidationPoint_1005_Type::setValidationPoint_1005_TypePair(ValidationPoint_1005_TypeChoicePair * ValidationPoint_1005_TypePairIn) {ValidationPoint_1005_TypePair = ValidationPoint_1005_TypePairIn;} /* ***************************************************************** */ /* class ValidationPoint_1005_TypeChoicePair */ ValidationPoint_1005_TypeChoicePair::ValidationPoint_1005_TypeChoicePair() {} ValidationPoint_1005_TypeChoicePair::ValidationPoint_1005_TypeChoicePair( whichOne ValidationPoint_1005_TypeTypeIn, ValidationPoint_1005_TypeVal ValidationPoint_1005_TypeValueIn) { ValidationPoint_1005_TypeType = ValidationPoint_1005_TypeTypeIn; ValidationPoint_1005_TypeValue = ValidationPoint_1005_TypeValueIn; } ValidationPoint_1005_TypeChoicePair::~ValidationPoint_1005_TypeChoicePair() { #ifndef NODESTRUCT if (ValidationPoint_1005_TypeType == DirectionsE) delete ValidationPoint_1005_TypeValue.Directions; else if (ValidationPoint_1005_TypeType == DirectionsBinaryE) delete ValidationPoint_1005_TypeValue.DirectionsBinary; #endif } void ValidationPoint_1005_TypeChoicePair::printSelf(FILE * outFile) { if (ValidationPoint_1005_TypeType == DirectionsE) { doSpaces(0, outFile); fprintf(outFile, "<Directions"); ValidationPoint_1005_TypeValue.Directions->printSelf(outFile); fprintf(outFile, "</Directions>\n"); } else if (ValidationPoint_1005_TypeType == DirectionsBinaryE) { doSpaces(0, outFile); fprintf(outFile, "<DirectionsBinary"); ValidationPoint_1005_TypeValue.DirectionsBinary->printSelf(outFile); fprintf(outFile, "</DirectionsBinary>\n"); } } /* ***************************************************************** */
24.58647
143
0.574255
QualityInformationFramework
3978150b5fc9891bcc517b90c1f00949ef9b8222
2,483
cpp
C++
Core/Source/fbxIterator.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
17
2018-03-29T15:24:40.000Z
2022-01-10T05:01:09.000Z
Core/Source/fbxIterator.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
null
null
null
Core/Source/fbxIterator.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
3
2018-04-07T06:02:05.000Z
2019-01-21T00:37:18.000Z
// Copyright 2018 E*D Films. All Rights Reserved. /** * fbxIterator.h * * Fbx implementation of the IteratorBase class * * @author dotBunny <hello@dotbunny.com> * @version 1 * @since 1.0.0 */ #include "fbxIterator.h" #include "fbxExporter.h" namespace SceneTrackFbx { FbxExporterT* Iterator::sExporter = nullptr; AssetManager_t* Iterator::sAssetManager = nullptr; Ref<GameObject_t> Iterator::ReadGameObjectRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateGameObject(handle); } Asset Iterator::ReadAsset(AssetType type) const { std::string assetName; ReadString(assetName); return sExporter->FindOrCreateAsset(assetName, type); } Ref<Transform_t> Iterator::ReadTransformRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateTransform(handle); } void Iterator::ReadTransformRefs(std::vector<Ref<Transform_t>>& values) const { std::vector<u32> handles; ReadArray(handles); values.reserve(handles.size()); for(auto handle : handles) { values.push_back(sExporter->FindOrCreateTransform(handle)); } } Ref<StandardMeshRenderer_t> Iterator::ReadStandardMeshRendererRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateStandardMeshRenderer(handle); } Ref<Mesh_t> Iterator::ReadMeshRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateMesh(handle); } Ref<SubMesh_t> Iterator::ReadSubMeshRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateSubMesh(handle); } void Iterator::ReadSubMeshRefs(std::vector<Ref<SubMesh_t>>& values) const { std::vector<u32> handles; ReadArray(handles); values.reserve(handles.size()); for(auto handle : handles) { values.push_back(sExporter->FindOrCreateSubMesh(handle)); } } Ref<Material_t> Iterator::ReadMaterialRef() const { u32 handle = stIteratorGetValue_uint32(iterator, 0); return sExporter->FindOrCreateMaterial(handle); } void Iterator::ReadMaterialRefs(std::vector<Ref<Material_t>>& values) const { std::vector<u32> handles; ReadArray(handles); values.reserve(handles.size()); for(auto handle : handles) { values.push_back(sExporter->FindOrCreateMaterial(handle)); } } }
23.205607
79
0.702376
EDFilms
397d4732a62f69b1726d2c8280a6189e7bbec931
110
cpp
C++
Pbinfo/Lazi.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Pbinfo/Lazi.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Pbinfo/Lazi.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; int main(){ int l,h; cin>>l>>h; cout<<h/l; return 0; }
10
20
0.563636
Al3x76
397fb9724af1c3e1062d71ef9ca3c5b2af95b51b
4,099
cxx
C++
xp_comm_proj/examfld/examfld.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
3
2020-08-03T08:52:20.000Z
2021-04-10T11:55:49.000Z
xp_comm_proj/examfld/examfld.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
null
null
null
xp_comm_proj/examfld/examfld.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
1
2021-06-08T18:16:45.000Z
2021-06-08T18:16:45.000Z
/* Copyright / Disclaimer : This software/documentation was produced as part of the INDEX project (Intelligent Data Extraction) which is funded under contract ESPRIT EP22745 of the European Community. For further details see http://www.man.ac.uk/MVC/research/INDEX/Public/. Copyright (c) June 1998, Manchester Visualisation Centre, UK. All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted without fee, provided that the above copyright notice and this permission notice appear in all copies of this software/documentation. This software/documentation is provided with no warranty, express or implied, including, without limitation, warrant of merchantability or fitness for a particular purpose. */ /* AVS/Express field examination/info tool. Amardeep S Bhattal. March 1998. a.bhattal@mcc.ac.uk Looks at the input field, and prints out the number of arrays, and information about each array - name, type, length, size. */ #include <iomanip.h> #include <iostream.h> #ifdef MSDOS #include <strstrea.h> #else #include <strstream.h> #endif #include "out_hdr.h" void n_arrays_info (OMobj_id field_id, strstream& info); void array_info (OMobj_id array_id, strstream& info); /* -------------------------------------------------------------------------- */ void n_arrays_info (OMobj_id field_id, strstream& info) { info << n_arrays (field_id) << " arrays" << endl << "(" << n_grid_arrays (field_id) << " gr, " << n_node_data_arrays (field_id) << " nd, " << n_cell_data_arrays (field_id) << " cd, " << n_connectivity_arrays (field_id) << " co" << ")." << endl << endl; } /* -------------------------------------------------------------------------- */ void array_info (OMobj_id array_id, strstream& info) { char *label_p, *type_p; int size; info.setf(ios::fixed,ios::floatfield); info.precision (0); array_label (array_id, &label_p, OM_OBJ_RD); if (label_p==NULL) info << "?"; else info << label_p; info << endl; type_to_string (array_type(array_id), &type_p); if (type_p==NULL) info << "?"; else info << type_p; info << " [" << array_length(array_id) << "], "; size = array_size (array_id); if (size < 1024) info << size << " bytes."; else info << size/1024.0 << "kb"; info << endl << endl; if (label_p) free (label_p); if (type_p) free (type_p); info.setf(0,ios::floatfield); info.precision (6); } /* -------------------------------------------------------------------------- */ /* void print_array_info (OMobj_id array_id) { char *label_p, *type_p; cout << " " << setfill('-') << setw(70) << "" << setfill(' ') << endl; array_label (array_id, &label_p, OM_OBJ_RD); if (label_p==NULL) cout << setw(14) << "?"; else cout << setw(14) << label_p; cout << " [" << setw(7) << array_length(array_id) << "], "; type_to_string (array_type(array_id), &type_p); if (type_p==NULL) cout << setw(6) << "?" << ", "; else cout << setw(6) << type_p << ", "; cout << setw(8) << array_size(array_id) << " bytes." << endl; if (label_p) free (label_p); if (type_p) free (type_p); cout << " " << setfill('-') << setw(70) << "" << setfill(' ') << endl; } */ /* -------------------------------------------------------------------------- */ int Examine_Field_Examine_Field_Prim::update(OMevent_mask event_mask, int seq_num) { int i; strstream info; char *string_p; if (this_is_a_field((OMobj_id)data)) { text_rows = 3*n_arrays ((OMobj_id)data) + 2; n_arrays_info ((OMobj_id)data, info); for (i=0; i<n_arrays((OMobj_id)data); i++) { info << i+1 << " - "; array_info (ith_array_id ((OMobj_id)data, i, OM_OBJ_RD), info); } info << ends; string_p = info.str(); text_string = string_p; delete string_p; } else cout << " this is not a field." << endl << endl; return(1); } /* -------------------------------------------------------------------------- */
25.61875
84
0.570627
avs
302d47f8b882aa6d4cc8fbbfc1044859ba87532e
820
cpp
C++
cpp/11448.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
9
2021-01-15T13:36:39.000Z
2022-02-23T03:44:46.000Z
cpp/11448.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
1
2021-07-31T17:11:26.000Z
2021-08-02T01:01:03.000Z
cpp/11448.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; using pii = pair<int, int>; int main() { fastio; int N; cin >> N; while (N--) { int n, cnt{}; cin >> n; vector<string> v(n), visited(n, string(n, 0)); for (int i = 0; i < n; i++) cin >> v[i]; queue<pii> Q; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (v[i][j] == 'w') Q.push({ i, j }), visited[i][j] = 1; while (Q.size()) { auto [x, y] = Q.front(); Q.pop(); if (v[x][y] == '-') cnt++; for (int k = 0; k < 8; k++) { int nx = x + "10001222"[k] - '1'; int ny = y + "22100012"[k] - '1'; if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; if (v[nx][ny] == 'b' || visited[nx][ny]) continue; Q.push({ nx, ny }), visited[nx][ny] = 1; } } cout << cnt << '\n'; } }
27.333333
59
0.462195
jinhan814
303071f0b70917d0dd647e321d33687596bf2613
12,786
cpp
C++
Daniel2.Encoder.FileReadMT/CEncoderTest.cpp
lewk2/Cinecoder.Samples
74f614a2a8b6a9fef818d4acedd9565637a68c4f
[ "Apache-2.0" ]
1
2019-03-14T00:56:19.000Z
2019-03-14T00:56:19.000Z
Daniel2.Encoder.FileReadMT/CEncoderTest.cpp
VitaliiGitHub/Cinecoder.Samples
74f614a2a8b6a9fef818d4acedd9565637a68c4f
[ "Apache-2.0" ]
null
null
null
Daniel2.Encoder.FileReadMT/CEncoderTest.cpp
VitaliiGitHub/Cinecoder.Samples
74f614a2a8b6a9fef818d4acedd9565637a68c4f
[ "Apache-2.0" ]
1
2019-02-19T16:48:04.000Z
2019-02-19T16:48:04.000Z
#include "stdafx.h" #include "CEncoderTest.h" //--------------------------------------------------------------- CEncoderTest::CEncoderTest() //--------------------------------------------------------------- { m_bRunning = FALSE; m_NumActiveThreads = 0; } //--------------------------------------------------------------- CEncoderTest::~CEncoderTest() //--------------------------------------------------------------- { Close(); } //--------------------------------------------------------------- int CEncoderTest::CheckParameters(const TEST_PARAMS &par) //--------------------------------------------------------------- { return 0; } //--------------------------------------------------------------- int CEncoderTest::CreateEncoder(const TEST_PARAMS &par) //--------------------------------------------------------------- { int hr; CComPtr<ICC_ClassFactory> pFactory; if (FAILED(hr = Cinecoder_CreateClassFactory(&pFactory))) return print_error(hr, "Cinecoder factory creation error"); if (FAILED(hr = pFactory->AssignLicense(par.CompanyName, par.LicenseKey))) return print_error(hr, "AssignLicense error"); CComPtr<ICC_VideoEncoder> pEncoder; CLSID clsidEnc = par.DeviceId >= 0 ? CLSID_CC_DanielVideoEncoder_CUDA : CLSID_CC_DanielVideoEncoder; if (FAILED(hr = pFactory->CreateInstance(clsidEnc, IID_ICC_VideoEncoder, (IUnknown**)&pEncoder))) return print_error(hr, "Encoder creation error"); // We use ICC_DanielVideoEncoderSettings_CUDA settings for both encoders because _CUDA settings class is an inheritor of ICC_DanielVideoEncoderSettings. CComPtr<ICC_DanielVideoEncoderSettings_CUDA> pSettings; if (FAILED(hr = pFactory->CreateInstance(CLSID_CC_DanielVideoEncoderSettings_CUDA, IID_ICC_DanielVideoEncoderSettings_CUDA, (IUnknown**)&pSettings))) return print_error(hr, "Encoder settings creation error"); pSettings->put_FrameSize(MK_SIZE(par.Width, par.Height)); pSettings->put_FrameRate(MK_RATIONAL(par.FrameRateN, par.FrameRateD)); pSettings->put_InputColorFormat(par.InputColorFormat); pSettings->put_ChromaFormat(par.ChromaFormat); pSettings->put_BitDepth(par.BitDepth); pSettings->put_RateMode(par.BitrateMode); pSettings->put_BitRate(par.Bitrate); pSettings->put_QuantScale(par.QuantScale); pSettings->put_CodingMethod(par.CodingMethod); pSettings->put_DeviceID(par.DeviceId); pSettings->put_NumSingleEncoders(par.NumSingleEncoders); if (FAILED(hr = pEncoder->Init(pSettings))) return print_error(hr, "Encoder initialization error"); CComPtr<ICC_OutputFile> pFileWriter; if (FAILED(hr = pFactory->CreateInstance(CLSID_CC_OutputFile, IID_ICC_OutputFile, (IUnknown**)&pFileWriter))) return print_error(hr, "File writer creation error"); if (FAILED(hr = pFileWriter->Create(CComBSTR(par.OutputFileName)))) return print_error(hr, "Output file creation error"); #if 1 if (FAILED(hr = pEncoder->put_OutputCallback(pFileWriter))) return print_error(hr, "Encoder cb assignment error"); #else CComPtr<ICC_IndexWriter> pIndexWriter; if (FAILED(hr = pFactory->CreateInstance(CLSID_CC_MvxWriter, IID_ICC_IndexWriter, (IUnknown**)&pIndexWriter))) return print_error(hr, "Index writer creation error"); if(FAILED(hr = pEncoder->put_OutputCallback(pIndexWriter))) return print_error(hr, "Encoder cb assignment error"); if(FAILED(hr = pIndexWriter->put_OutputCallback(pFileWriter))) return print_error(hr, "Index writer cb assignment error"); CComPtr<ICC_OutputFile> pIndexFileWriter; if (FAILED(hr = pFactory->CreateInstance(CLSID_CC_OutputFile, IID_ICC_OutputFile, (IUnknown**)&pIndexFileWriter))) return print_error(hr, "Index file writer creation error"); CComQIPtr<ICC_DataWriterEx> pDataWriterEx = pIndexFileWriter; if(!pDataWriterEx) return print_error(hr, "ICC_File has no ICC_DataWriterEx interface"); if (FAILED(hr = pIndexWriter->put_IndexCallback(pDataWriterEx))) return print_error(hr, "Index writer cb 2 assignment error"); if (FAILED(hr = pIndexFileWriter->Create(CComBSTR(CString(par.OutputFileName) )))) return print_error(hr, "Output file creation error"); #endif m_pEncoder = pEncoder; return S_OK; } //--------------------------------------------------------------- int CEncoderTest::AssignParameters(const TEST_PARAMS &par) //--------------------------------------------------------------- { int hr; if(FAILED(hr = CheckParameters(par))) return hr; if(FAILED(hr = CreateEncoder(par))) return hr; m_FrameSizeInBytes = 0;// par.ReadBlockSize; switch (par.InputColorFormat) { case CCF_UYVY: case CCF_YUY2: m_FrameSizeInBytes = par.Height * par.Width * 2; break; case CCF_V210: m_FrameSizeInBytes = par.Height * ((par.Width + 47) / 48) * 128; break; case CCF_RGB30: m_FrameSizeInBytes = par.Height * par.Width * 4; break; default: return print_error(E_INVALIDARG, "The color format is not supported by test app"), E_INVALIDARG; } for(int i = 0; i < par.QueueSize; i++) { BufferDescr descr = {}; extern void *cuda_alloc_pinned(size_t size); if(par.DeviceId >= 0) descr.pBuffer = (LPBYTE)cuda_alloc_pinned(m_FrameSizeInBytes); else descr.pBuffer = (LPBYTE)VirtualAlloc(NULL, m_FrameSizeInBytes, MEM_COMMIT, PAGE_READWRITE); if (!descr.pBuffer) return print_error(E_OUTOFMEMORY, "Can't allocate an input frame buffer for the queue"); descr.evVacant = CreateEvent(NULL, FALSE, TRUE, NULL); descr.evFilled = CreateEvent(NULL, FALSE, FALSE, NULL); m_Queue.push_back(descr); } m_evCancel = CreateEvent(NULL, TRUE, FALSE, NULL); m_EncPar = par; memset((void*)&m_Stats, 0, sizeof(m_Stats)); return S_OK; } //--------------------------------------------------------------- int CEncoderTest::Close() //--------------------------------------------------------------- { if (!m_pEncoder) return S_FALSE; if(m_bRunning) Cancel(); while(!m_Queue.empty()) { BufferDescr descr = m_Queue.back(); CloseHandle(descr.evVacant); CloseHandle(descr.evFilled); extern void cuda_free_pinned(void *ptr); if(m_EncPar.DeviceId >= 0) cuda_free_pinned(descr.pBuffer); else VirtualFree(descr.pBuffer, 0, MEM_RELEASE); m_Queue.pop_back(); } CloseHandle(m_evCancel); m_pEncoder = NULL; return S_OK; } //--------------------------------------------------------------- int CEncoderTest::Run() //--------------------------------------------------------------- { m_hEncodingThread = CreateThread(NULL, 0, encoding_thread_proc, this, 0, NULL); for (int i = 0; i < m_EncPar.NumReadThreads; i++) m_hReadingThreads.push_back(CreateThread(NULL, 0, reading_thread_proc, this, 0, NULL)); m_NumActiveThreads = m_EncPar.NumReadThreads + 1; m_ReadFrameCounter = 0; m_hrResult = S_OK; m_bRunning = TRUE; return S_OK; } //--------------------------------------------------------------- bool CEncoderTest::IsActive() const //--------------------------------------------------------------- { return m_NumActiveThreads != 0; } //--------------------------------------------------------------- HRESULT CEncoderTest::GetResult() const //--------------------------------------------------------------- { return m_hrResult; } //--------------------------------------------------------------- int CEncoderTest::Cancel() //--------------------------------------------------------------- { if (!m_bRunning) return S_FALSE; SetEvent(m_evCancel); WaitForSingleObject(m_hEncodingThread, INFINITE); WaitForMultipleObjects((DWORD)m_hReadingThreads.size(), &m_hReadingThreads[0], TRUE, INFINITE); for(size_t i = 0; i < m_hReadingThreads.size(); i++) CloseHandle(m_hReadingThreads[i]); m_hReadingThreads.clear(); CloseHandle(m_hEncodingThread); m_bRunning = false; return S_OK; } //--------------------------------------------------------------- int CEncoderTest::GetCurrentEncodingStats(ENCODER_STATS *pStats) //--------------------------------------------------------------- { if (!pStats) return E_POINTER; pStats->NumFramesRead = m_Stats.NumFramesRead; pStats->NumFramesWritten = m_Stats.NumFramesWritten; pStats->NumBytesRead = InterlockedExchangeAdd64(&m_Stats.NumBytesRead, 0); pStats->NumBytesWritten = InterlockedExchangeAdd64(&m_Stats.NumBytesWritten, 0); return S_OK; } //--------------------------------------------------------------- DWORD WINAPI CEncoderTest::reading_thread_proc(void *p) //--------------------------------------------------------------- { return reinterpret_cast<CEncoderTest*>(p)->ReadingThreadProc(); } //--------------------------------------------------------------- DWORD CEncoderTest::ReadingThreadProc() //--------------------------------------------------------------- { fprintf(stderr, "Reading thread %d is started\n", GetCurrentThreadId()); HANDLE hFile = CreateFile(m_EncPar.InputFileName, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, m_EncPar.UseCache ? 0 : FILE_FLAG_NO_BUFFERING, NULL); //if(hFile == INVALID_HANDLE_VALUE) // return fprintf(stderr, "Thread %d: error %08xh opening the file\n", GetCurrentThreadId(), HRESULT_FROM_WIN32(GetLastError())), HRESULT_FROM_WIN32(GetLastError()); for(;;) { int frame_no = InterlockedExchangeAdd(&m_ReadFrameCounter, 1); int buffer_id = frame_no % m_EncPar.QueueSize; BufferDescr &bufdescr = m_Queue[buffer_id]; HANDLE hh[2] = { m_evCancel, bufdescr.evVacant }; DWORD wait_result = WaitForMultipleObjects(2, hh, FALSE, INFINITE); if(wait_result == WAIT_OBJECT_0) break; if (m_EncPar.StopFrameNum >= 0) { if (frame_no > m_EncPar.StopFrameNum && !m_EncPar.Looped) { bufdescr.hrReadStatus = S_FALSE; SetEvent(bufdescr.evFilled); break; } int num_frames_in_range = m_EncPar.StopFrameNum - m_EncPar.StartFrameNum + 1; if (num_frames_in_range > 0) frame_no = frame_no % num_frames_in_range + m_EncPar.StartFrameNum; else frame_no = m_EncPar.StopFrameNum - frame_no % (1-num_frames_in_range); } LONGLONG offset = frame_no * LONGLONG(m_FrameSizeInBytes); SetFilePointer(hFile, (LONG)offset, ((LONG*)&offset)+1, FILE_BEGIN); DWORD r; if (hFile == INVALID_HANDLE_VALUE || !ReadFile(hFile, bufdescr.pBuffer, m_FrameSizeInBytes, &r, NULL)) { bufdescr.hrReadStatus = HRESULT_FROM_WIN32(GetLastError()); SetEvent(bufdescr.evFilled); break; } if (r != m_FrameSizeInBytes) { bufdescr.hrReadStatus = S_FALSE; SetEvent(bufdescr.evFilled); break; } InterlockedIncrement(&m_Stats.NumFramesRead); InterlockedAdd64(&m_Stats.NumBytesRead, m_FrameSizeInBytes); SetEvent(bufdescr.evFilled); } HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); if(FAILED(hr)) { fprintf(stderr, "Reading thread %d: error %08x\n", GetCurrentThreadId(), hr); SetEvent(m_evCancel); } CloseHandle(hFile); InterlockedDecrement(&m_NumActiveThreads); fprintf(stderr, "Reading thread %d is done\n", GetCurrentThreadId()); return hr; } //--------------------------------------------------------------- DWORD WINAPI CEncoderTest::encoding_thread_proc(void *p) //--------------------------------------------------------------- { return reinterpret_cast<CEncoderTest*>(p)->EncodingThreadProc(); } //--------------------------------------------------------------- DWORD CEncoderTest::EncodingThreadProc() //--------------------------------------------------------------- { HRESULT hr = S_OK; fprintf(stderr, "Encoding thread %d is started\n", GetCurrentThreadId()); for(int frame_no = 0; ; frame_no++) { int buffer_id = frame_no % m_EncPar.QueueSize; DWORD t0 = GetTickCount(); HANDLE hh[2] = { m_evCancel, m_Queue[buffer_id].evFilled }; DWORD wait_result = WaitForMultipleObjects(2, hh, FALSE, INFINITE); if (wait_result == WAIT_OBJECT_0) { m_hrResult = S_FALSE;// E_ABORT; break; } if (m_Queue[buffer_id].hrReadStatus != S_OK) { m_hrResult = m_Queue[buffer_id].hrReadStatus; break; } CC_VIDEO_FRAME_DESCR frame_descr = { m_EncPar.InputColorFormat }; if (CComQIPtr<ICC_VideoConsumerExtAsync> pEncAsync = m_pEncoder) { hr = pEncAsync->AddScaleFrameAsync( m_Queue[buffer_id].pBuffer, m_FrameSizeInBytes, &frame_descr, CComPtr<IUnknown>(), NULL); } else { hr = m_pEncoder->AddScaleFrame( m_Queue[buffer_id].pBuffer, m_FrameSizeInBytes, &frame_descr, NULL); } if(FAILED(hr)) break; DWORD t1 = GetTickCount(); int wait_time = 42 - (t1 - t0); // if (wait_time > 1) // Sleep(wait_time); InterlockedIncrement(&m_Stats.NumFramesWritten); InterlockedAdd64(&m_Stats.NumBytesWritten, 0); SetEvent(m_Queue[buffer_id].evVacant); } InterlockedDecrement(&m_NumActiveThreads); fprintf(stderr, "Encoding thread %d is done\n", GetCurrentThreadId()); return hr; }
29.665893
199
0.623807
lewk2
30347a858cf9beff30348cf559c722da0504d627
8,479
cpp
C++
Source/Geometry/Mesh/imstkPointSet.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
2
2020-08-14T07:21:30.000Z
2021-08-30T09:39:09.000Z
Source/Geometry/Mesh/imstkPointSet.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
null
null
null
Source/Geometry/Mesh/imstkPointSet.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
1
2020-08-14T07:00:31.000Z
2020-08-14T07:00:31.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic Institute. 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. =========================================================================*/ #include "imstkPointSet.h" //#include "imstkGraph.h" #include "imstkParallelUtils.h" namespace imstk { void PointSet::initialize(const StdVectorOfVec3d& vertices) { this->setInitialVertexPositions(vertices); this->setVertexPositions(vertices); } void PointSet::clear() { m_initialVertexPositions.clear(); m_vertexPositions.clear(); m_vertexPositionsPostTransform.clear(); } void PointSet::print() const { Geometry::print(); LOG(INFO) << "Number of vertices: " << this->getNumVertices(); LOG(INFO) << "Vertex positions:"; for (auto& verts : m_vertexPositions) { LOG(INFO) << verts.x() << ", " << verts.y() << ", " << verts.z(); } } void PointSet::computeBoundingBox(Vec3d& lowerCorner, Vec3d& upperCorner, const double paddingPercent) { updatePostTransformData(); ParallelUtils::findAABB(m_vertexPositions, lowerCorner, upperCorner); if (paddingPercent > 0.0) { const Vec3d range = upperCorner - lowerCorner; lowerCorner = lowerCorner - range * (paddingPercent / 100.0); upperCorner = upperCorner + range * (paddingPercent / 100.0); } } void PointSet::setInitialVertexPositions(const StdVectorOfVec3d& vertices) { if (m_originalNumVertices == 0) { m_initialVertexPositions = vertices; m_originalNumVertices = vertices.size(); m_maxNumVertices = static_cast<size_t>(m_originalNumVertices * m_loadFactor); m_vertexPositions.reserve(m_maxNumVertices); } else { LOG(WARNING) << "Already set initial vertices"; } } const StdVectorOfVec3d& PointSet::getInitialVertexPositions() const { return m_initialVertexPositions; } const Vec3d& PointSet::getInitialVertexPosition(const size_t vertNum) const { #if defined(DEBUG) || defined(_DEBUG) || !defined(NDEBUG) LOG_IF(FATAL, (vertNum >= m_initialVertexPositions.size())) << "Invalid index"; #endif return m_initialVertexPositions[vertNum]; } void PointSet::setVertexPositions(const StdVectorOfVec3d& vertices) { if (vertices.size() <= m_maxNumVertices) { m_vertexPositions = vertices; m_dataModified = true; m_transformApplied = false; this->updatePostTransformData(); } else { LOG(WARNING) << "Vertices not set, exceeded maximum number of vertices"; } } const StdVectorOfVec3d& PointSet::getVertexPositions(DataType type /* = DataType::PostTransform */) { if (type == DataType::PostTransform) { this->updatePostTransformData(); return m_vertexPositionsPostTransform; } return m_vertexPositions; } void PointSet::setVertexPosition(const size_t vertNum, const Vec3d& pos) { #if defined(DEBUG) || defined(_DEBUG) || !defined(NDEBUG) LOG_IF(FATAL, (vertNum >= m_vertexPositions.size())) << "Invalid index"; #endif m_vertexPositions[vertNum] = pos; m_dataModified = true; m_transformApplied = false; this->updatePostTransformData(); } const Vec3d& PointSet::getVertexPosition(const size_t vertNum, DataType type) { #if defined(DEBUG) || defined(_DEBUG) || !defined(NDEBUG) LOG_IF(FATAL, (vertNum >= getVertexPositions().size())) << "Invalid index"; #endif return this->getVertexPositions(type)[vertNum]; } void PointSet::setVertexDisplacements(const StdVectorOfVec3d& diff) { assert(diff.size() == m_vertexPositions.size()); ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] = m_initialVertexPositions[i] + diff[i]; }); m_dataModified = true; m_transformApplied = false; } void PointSet::setVertexDisplacements(const Vectord& u) { assert(u.size() == 3 * m_vertexPositions.size()); ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] = m_initialVertexPositions[i] + Vec3d(u(i * 3), u(i * 3 + 1), u(i * 3 + 2)); }); m_dataModified = true; m_transformApplied = false; } void PointSet::translateVertices(const Vec3d& t) { ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] += t; }); m_dataModified = true; m_transformApplied = false; } void PointSet::setPointDataMap(const std::map<std::string, StdVectorOfVectorf>& pointData) { m_pointDataMap = pointData; } const std::map<std::string, StdVectorOfVectorf>& PointSet::getPointDataMap() const { return m_pointDataMap; } void PointSet::setPointDataArray(const std::string& arrayName, const StdVectorOfVectorf& arrayData) { if (arrayData.size() != this->getNumVertices()) { LOG(WARNING) << "Specified array should have " << this->getNumVertices() << " tuples, has " << arrayData.size(); return; } m_pointDataMap[arrayName] = arrayData; } const StdVectorOfVectorf* PointSet::getPointDataArray(const std::string& arrayName) const { auto it = m_pointDataMap.find(arrayName); if (it == m_pointDataMap.end()) { LOG(WARNING) << "No array with such name holds any point data."; return nullptr; } return &(it->second); } bool PointSet::hasPointDataArray(const std::string& arrayName) const { auto it = m_pointDataMap.find(arrayName); if (it == m_pointDataMap.end()) { return false; } return true; } size_t PointSet::getNumVertices() const { return m_vertexPositions.size(); } void PointSet::applyTranslation(const Vec3d t) { ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] += t; m_initialVertexPositions[i] += t; }); m_dataModified = true; m_transformApplied = false; } void PointSet::applyRotation(const Mat3d r) { ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] = r * m_vertexPositions[i]; m_initialVertexPositions[i] = r * m_initialVertexPositions[i]; }); m_dataModified = true; m_transformApplied = false; } void PointSet::applyScaling(const double s) { ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { m_vertexPositions[i] = s * m_vertexPositions[i]; m_initialVertexPositions[i] = s * m_initialVertexPositions[i]; }); m_dataModified = true; m_transformApplied = false; } void PointSet::updatePostTransformData() { if (m_transformApplied) { return; } if (m_vertexPositionsPostTransform.size() != m_vertexPositions.size()) { m_vertexPositionsPostTransform.resize(m_vertexPositions.size()); } ParallelUtils::parallelFor(m_vertexPositions.size(), [&](const size_t i) { // NOTE: Right now scaling is appended on top of the rigid transform // for scaling around the mesh center, and not concatenated within // the transform, for ease of use. m_vertexPositionsPostTransform[i] = m_transform * (m_vertexPositions[i] * m_scaling); }); m_transformApplied = true; } void PointSet::setLoadFactor(double loadFactor) { m_loadFactor = loadFactor; m_maxNumVertices = (size_t)(m_originalNumVertices * m_loadFactor); m_vertexPositions.reserve(m_maxNumVertices); } double PointSet::getLoadFactor() { return m_loadFactor; } size_t PointSet::getMaxNumVertices() { return m_maxNumVertices; } } // imstk
26.41433
109
0.654912
quantingxie
303679c53ccd3d6d0603152e985f42ecde9bb5f4
410
cpp
C++
number/test/prime_factorization.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
20
2021-06-21T00:18:54.000Z
2022-03-17T17:45:44.000Z
number/test/prime_factorization.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
56
2021-06-03T14:42:13.000Z
2022-03-26T14:15:30.000Z
number/test/prime_factorization.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
3
2019-12-11T06:45:45.000Z
2020-09-07T13:45:32.000Z
#include "../sieve.hpp" #include <iostream> #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_1_A" using namespace std; int main() { Sieve sieve(1 << 15); int N; cin >> N; map<long long int, int> factors = sieve.factorize<long long>(N); cout << N << ':'; for (auto p : factors) { while (p.second--) cout << ' ' << p.first; } cout << '\n'; }
24.117647
82
0.570732
ankit6776
303792ed5ded8936fa35b2c947bb01f3e2978c1c
2,537
cpp
C++
Info/Info/EventNonPlayerItemList/EventNonPlayerItemList.cpp
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
Info/Info/EventNonPlayerItemList/EventNonPlayerItemList.cpp
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
Info/Info/EventNonPlayerItemList/EventNonPlayerItemList.cpp
Teles1/LuniaAsio
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
[ "MIT" ]
null
null
null
#pragma once #include "EventNonPlayerItemList.h" namespace Lunia { namespace XRated { namespace Database { namespace Info { void NpcDropEventItems::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Database::Info::NpcDropEventItems"); out.Write(L"NpcItems", NpcItems); out.Write(L"StageItems", StageItems); out.Write(L"AnyWhereItems", AnyWhereItems); } void NpcDropEventItems::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Database::Info::NpcDropEventItems"); in.Read(L"NpcItems", NpcItems); in.Read(L"StageItems", StageItems); in.Read(L"AnyWhereItems", AnyWhereItems); ValidEvents(); } void NpcDropEventItems::ValidEvents() { { float totalProbability = 0.f; std::map<uint32/*NpcHash*/, std::vector<NonPlayerInfo::Item> >::const_iterator iter = NpcItems.begin(); while (iter != NpcItems.end()) { totalProbability = 0.f; std::vector<NonPlayerInfo::Item>::const_iterator itemIter = iter->second.begin(); while (itemIter != iter->second.end()) { totalProbability += itemIter->Probability; ++itemIter; } if (totalProbability > 0.1f) { Logger::GetInstance().Exception(L"NpcDropEventItems Probality over 10% : npcHash={0}", iter->first); } ++iter; } } { float totalProbability = 0.f; std::map<XRated::StageLocation, std::vector<NonPlayerInfo::Item> >::const_iterator iter = StageItems.begin(); while (iter != StageItems.end()) { totalProbability = 0.f; std::vector<NonPlayerInfo::Item>::const_iterator itemIter = iter->second.begin(); while (itemIter != iter->second.end()) { totalProbability += itemIter->Probability; ++itemIter; } if (totalProbability > 0.1f) { Logger::GetInstance().Exception(L"NpcDropEventItems Probality over 10% : stageGroupHash={0}, accessLevel={1}", iter->first.StageGroupHash, iter->first.Level); } ++iter; } } { float totalProbability = 0.f; std::vector<NonPlayerInfo::Item>::const_iterator iter = AnyWhereItems.begin(); while (iter != AnyWhereItems.end()) { totalProbability += iter->Probability; ++iter; } if (totalProbability > 0.1f) { Logger::GetInstance().Exception(L"NpcDropEventItems AnyWhereItems Probality over 10%"); } } } } } } }
27.879121
166
0.612534
Teles1
303a1082493a98e9a225b4b1edd280e2b13e4876
77,673
cpp
C++
src/networking.cpp
shaishasag/redispp
a02abc5809cac2c7b1037a9775d6fd2d1ccbc932
[ "BSD-3-Clause" ]
1
2018-01-12T12:31:34.000Z
2018-01-12T12:31:34.000Z
src/networking.cpp
shaishasag/redispp
a02abc5809cac2c7b1037a9775d6fd2d1ccbc932
[ "BSD-3-Clause" ]
null
null
null
src/networking.cpp
shaishasag/redispp
a02abc5809cac2c7b1037a9775d6fd2d1ccbc932
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * 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 Redis 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 "server.h" #include "atomicvar.h" #include <sys/uio.h> #include <math.h> #include <ctype.h> /* Return the size consumed from the allocator, for the specified SDS string, * including internal fragmentation. This function is used in order to compute * the client output buffer size. */ size_t sdsZmallocSize(sds s) { void *sh = sdsAllocPtr(s); return zmalloc_size(sh); } /* Return the amount of memory used by the sds string at object->ptr * for a string object. */ size_t getStringObjectSdsUsedMemory(robj *o) { serverAssertWithInfo(NULL,o,o->type == OBJ_STRING); switch(o->encoding) { case OBJ_ENCODING_RAW: return sdsZmallocSize((sds)o->ptr); case OBJ_ENCODING_EMBSTR: return zmalloc_size(o)-sizeof(robj); default: return 0; /* Just integer encoding for now. */ } } /* Client.reply list dup and free methods. */ void *dupClientReplyValue(void *o) { return sdsdup((sds)o); } void freeClientReplyValue(void *o) { sdsfree((sds)o); } int listMatchObjects(void *a, void *b) { return equalStringObjects((robj *)a,(robj *)b); } blockingState::blockingState() : m_timeout(0) , m_keys(dictCreate(&objectKeyPointerValueDictType,NULL)) , m_target(NULL) , m_num_replicas(0) , m_replication_offset() , m_module_blocked_handle(NULL) {} client *createClient(int fd) { void* client_mem = zmalloc(sizeof(client)); /* passing -1 as fd it is possible to create a non connected client. * This is useful since all the commands needs to be executed * in the context of a client. When commands are executed in other * contexts (for instance a Lua script) we need a non connected client. */ if (fd != -1) { anetNonBlock(NULL,fd); anetEnableTcpNoDelay(NULL,fd); if (server.tcpkeepalive) anetKeepAlive(NULL,fd,server.tcpkeepalive); if (server.el->aeCreateFileEvent(fd,AE_READABLE, readQueryFromClient, client_mem) == AE_ERR) { close(fd); zfree(client_mem); return NULL; } } uint64_t client_id; atomicGetIncr(server.next_client_id, client_id, 1); client *c = new (client_mem) client(client_id, fd); c->selectDb(0); if (fd != -1) server.clients->listAddNodeTail(c); return c; } client::client(uint64_t in_client_id, int in_fd) : m_client_id(in_client_id) , m_fd(in_fd) , m_client_name(NULL) , m_response_buff_pos(0) , m_query_buf(sdsempty()) , m_pending_query_buf(sdsempty()) , m_query_buf_peak(0) , m_req_protocol_type(0) , m_argc(0) , m_argv(NULL) , m_cmd(NULL) , m_last_cmd(NULL) , m_multi_bulk_len(0) , m_bulk_len(-1) , m_already_sent_len(0) , m_flags(0) , m_ctime(server.unixtime) , m_last_interaction_time(m_ctime) , m_authenticated(0) , m_replication_state(REPL_STATE_NONE) , m_repl_put_online_on_ack(0) , m_applied_replication_offset(0) , m_read_replication_offset(0) , m_replication_ack_off(0) , m_replication_ack_time(0) , m_slave_listening_port(0) , m_slave_capabilities(SLAVE_CAPA_NONE) , m_reply(listCreate()) , m_reply_bytes(0) , m_obuf_soft_limit_reached_time(0) , m_blocking_op_type(BLOCKED_NONE) , m_blocking_state() , m_last_write_global_replication_offset(0) , m_watched_keys(listCreate()) , m_pubsub_channels(dictCreate(&objectKeyPointerValueDictType,NULL)) , m_pubsub_patterns(listCreate()) , m_cached_peer_id(NULL) { m_reply->listSetFreeMethod(freeClientReplyValue); m_reply->listSetDupMethod(dupClientReplyValue); m_slave_ip[0] = '\0'; m_pubsub_patterns->listSetFreeMethod(decrRefCountVoid); m_pubsub_patterns->listSetMatchMethod(listMatchObjects); initClientMultiState(this); } /* This function is called every time we are going to transmit new data * to the client. The behavior is the following: * * If the client should receive new data (normal clients will) the function * returns C_OK, and make sure to install the write handler in our event * loop so that when the socket is writable new data gets written. * * If the client should not receive new data, because it is a fake client * (used to load AOF in memory), a master or because the setup of the write * handler failed, the function returns C_ERR. * * The function may return C_OK without actually installing the write * event handler in the following cases: * * 1) The event handler should already be installed since the output buffer * already contains something. * 2) The client is a slave but not yet online, so we want to just accumulate * writes in the buffer but not actually sending them yet. * * Typically gets called every time a reply is built, before adding more * data to the clients output buffers. If the function returns C_ERR no * data should be appended to the output buffers. */ int client::prepareClientToWrite() { /* If it's the Lua client we always return ok without installing any * handler since there is no socket at all. */ if (m_flags & (CLIENT_LUA|CLIENT_MODULE)) return C_OK; /* CLIENT REPLY OFF / SKIP handling: don't send replies. */ if (m_flags & (CLIENT_REPLY_OFF|CLIENT_REPLY_SKIP)) return C_ERR; /* Masters don't receive replies, unless CLIENT_MASTER_FORCE_REPLY flag * is set. */ if ((m_flags & CLIENT_MASTER) && !(m_flags & CLIENT_MASTER_FORCE_REPLY)) return C_ERR; if (m_fd <= 0) return C_ERR; /* Fake client for AOF loading. */ /* Schedule the client to write the output buffers to the socket only * if not already done (there were no pending writes already and the client * was yet not flagged), and, for slaves, if the slave can actually * receive writes at this stage. */ if (!this->clientHasPendingReplies() && !(m_flags & CLIENT_PENDING_WRITE) && (m_replication_state == REPL_STATE_NONE || (m_replication_state == SLAVE_STATE_ONLINE && !m_repl_put_online_on_ack))) { /* Here instead of installing the write handler, we just flag the * client and put it into a list of clients that have something * to write to the socket. This way before re-entering the event * loop, we can try to directly write to the client sockets avoiding * a system call. We'll only really install the write handler if * we'll not be able to write the whole reply at once. */ m_flags |= CLIENT_PENDING_WRITE; server.clients_pending_write->listAddNodeHead(this); } /* Authorize the caller to queue in the output buffer of this client. */ return C_OK; } /* ----------------------------------------------------------------------------- * Low level functions to add more data to output buffers. * -------------------------------------------------------------------------- */ int client::_addReplyToBuffer(const char *s, size_t len) { size_t available = sizeof(m_response_buff) - m_response_buff_pos; if (m_flags & CLIENT_CLOSE_AFTER_REPLY) return C_OK; /* If there already are entries in the reply list, we cannot * add anything more to the static buffer. */ if (m_reply->listLength() > 0) return C_ERR; /* Check that the buffer has enough space available for this string. */ if (len > available) return C_ERR; memcpy(m_response_buff + m_response_buff_pos, s, len); m_response_buff_pos += len; return C_OK; } void client::_addReplyObjectToList(robj *o) { if (m_flags & CLIENT_CLOSE_AFTER_REPLY) return; if (m_reply->listLength() == 0) { sds s = sdsdup((sds)o->ptr); m_reply->listAddNodeTail(s); m_reply_bytes += sdslen(s); } else { listNode *ln = m_reply->listLast(); sds tail = (sds)ln->listNodeValue(); /* Append to this object when possible. If tail == NULL it was * set via addDeferredMultiBulkLength(). */ if (tail && sdslen(tail)+sdslen((sds)o->ptr) <= PROTO_REPLY_CHUNK_BYTES) { tail = sdscatsds(tail,(sds)o->ptr); ln->SetNodeValue(tail); m_reply_bytes += sdslen((sds)o->ptr); } else { sds s = sdsdup((sds)o->ptr); m_reply->listAddNodeTail(s); m_reply_bytes += sdslen(s); } } asyncCloseClientOnOutputBufferLimitReached(); } /* This method takes responsibility over the sds. When it is no longer * needed it will be free'd, otherwise it ends up in a robj. */ void client::_addReplySdsToList(sds s) { if (m_flags & CLIENT_CLOSE_AFTER_REPLY) { sdsfree(s); return; } if (m_reply->listLength() == 0) { m_reply->listAddNodeTail(s); m_reply_bytes += sdslen(s); } else { listNode *ln = m_reply->listLast(); sds tail = (sds)ln->listNodeValue(); /* Append to this object when possible. If tail == NULL it was * set via addDeferredMultiBulkLength(). */ if (tail && sdslen(tail)+sdslen(s) <= PROTO_REPLY_CHUNK_BYTES) { tail = sdscatsds(tail,s); ln->SetNodeValue(tail); m_reply_bytes += sdslen(s); sdsfree(s); } else { m_reply->listAddNodeTail(s); m_reply_bytes += sdslen(s); } } asyncCloseClientOnOutputBufferLimitReached(); } void client::_addReplyStringToList(const char *s, size_t len) { if (m_flags & CLIENT_CLOSE_AFTER_REPLY) return; if (m_reply->listLength() == 0) { sds node = sdsnewlen(s,len); m_reply->listAddNodeTail(node); m_reply_bytes += len; } else { listNode *ln = m_reply->listLast(); sds tail = (sds)ln->listNodeValue(); /* Append to this object when possible. If tail == NULL it was * set via addDeferredMultiBulkLength(). */ if (tail && sdslen(tail)+len <= PROTO_REPLY_CHUNK_BYTES) { tail = sdscatlen(tail,s,len); ln->SetNodeValue(tail); m_reply_bytes += len; } else { sds node = sdsnewlen(s,len); m_reply->listAddNodeTail(node); m_reply_bytes += len; } } asyncCloseClientOnOutputBufferLimitReached(); } /* ----------------------------------------------------------------------------- * Higher level functions to queue data on the client output buffer. * The following functions are the ones that commands implementations will call. * -------------------------------------------------------------------------- */ void client::addReply(robj *obj) { if (prepareClientToWrite() != C_OK) return; /* This is an important place where we can avoid copy-on-write * when there is a saving child running, avoiding touching the * refcount field of the object if it's not needed. * * If the encoding is RAW and there is room in the static buffer * we'll be able to send the object to the client without * messing with its page. */ if (sdsEncodedObject(obj)) { if (_addReplyToBuffer((const char*)obj->ptr,sdslen((sds)obj->ptr)) != C_OK) _addReplyObjectToList(obj); } else if (obj->encoding == OBJ_ENCODING_INT) { /* Optimization: if there is room in the static buffer for 32 bytes * (more than the max chars a 64 bit integer can take as string) we * avoid decoding the object and go for the lower level approach. */ if (m_reply->listLength() == 0 && (sizeof(m_response_buff) - m_response_buff_pos) >= 32) { char buf[32]; int len; len = ll2string(buf,sizeof(buf),(long)obj->ptr); if (_addReplyToBuffer(buf, len) == C_OK) return; /* else... continue with the normal code path, but should never * happen actually since we verified there is room. */ } obj = getDecodedObject(obj); if (_addReplyToBuffer((const char*)obj->ptr,sdslen((sds)obj->ptr)) != C_OK) _addReplyObjectToList(obj); decrRefCount(obj); } else { serverPanic("Wrong obj->encoding in addReply()"); } } void client::addReplySds(sds s) { if (prepareClientToWrite() != C_OK) { /* The caller expects the sds to be free'd. */ sdsfree(s); return; } if (_addReplyToBuffer((const char*)s,sdslen(s)) == C_OK) { sdsfree(s); } else { /* This method free's the sds when it is no longer needed. */ _addReplySdsToList(s); } } /* This low level function just adds whatever protocol you send it to the * client buffer, trying the static buffer initially, and using the string * of objects if not possible. * * It is efficient because does not create an SDS object nor an Redis object * if not needed. The object will only be created by calling * _addReplyStringToList() if we fail to extend the existing tail object * in the list of objects. */ void client::addReplyString(const char *s, size_t len) { if (prepareClientToWrite() != C_OK) return; if (_addReplyToBuffer(s,len) != C_OK) _addReplyStringToList(s,len); } void client::addReplyErrorLength(const char *s, size_t len) { addReplyString("-ERR ",5); addReplyString(s,len); addReplyString("\r\n",2); } void client::addReplyError(const char *err) { addReplyErrorLength(err, strlen(err)); } void client::addReplyErrorFormat(const char *fmt, ...) { size_t l, j; va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); /* Make sure there are no newlines in the string, otherwise invalid protocol * is emitted. */ l = sdslen(s); for (j = 0; j < l; j++) { if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; } addReplyErrorLength(s,sdslen(s)); sdsfree(s); } void client::addReplyStatusLength(const char *s, size_t len) { addReplyString("+",1); addReplyString(s,len); addReplyString("\r\n",2); } void client::addReplyStatus(const char *status) { addReplyStatusLength(status,strlen(status)); } void client::addReplyStatusFormat(const char *fmt, ...) { va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); addReplyStatusLength(s,sdslen(s)); sdsfree(s); } /* Adds an empty object to the reply list that will contain the multi bulk * length, which is not known when this function is called. */ void* client::addDeferredMultiBulkLength() { /* Note that we install the write event here even if the object is not * ready to be sent, since we are sure that before returning to the * event loop setDeferredMultiBulkLength() will be called. */ if (prepareClientToWrite() != C_OK) return NULL; m_reply->listAddNodeTail(NULL); /* NULL is our placeholder. */ return m_reply->listLast(); } /* Populate the length object and try gluing it to the next chunk. */ void client::setDeferredMultiBulkLength(void *node, long length) { listNode *ln = (listNode*)node; sds len, next; /* Abort when *node is NULL: when the client should not accept writes * we return NULL in addDeferredMultiBulkLength() */ if (node == NULL) return; len = sdscatprintf(sdsnewlen("*",1),"%ld\r\n",length); ln->SetNodeValue(len); m_reply_bytes += sdslen(len); if (ln->listNextNode() != NULL) { next = (sds)ln->listNextNode()->listNodeValue(); /* Only glue when the next node is non-NULL (an sds in this case) */ if (next != NULL) { len = sdscatsds(len,next); m_reply->listDelNode(ln->listNextNode()); ln->SetNodeValue(len); /* No need to update reply_bytes: we are just moving the same * amount of bytes from one node to another. */ } } asyncCloseClientOnOutputBufferLimitReached(); } /* Add a double as a bulk reply */ void client::addReplyDouble(double d) { char dbuf[128], sbuf[128]; int dlen, slen; if (isinf(d)) { /* Libc in odd systems (Hi Solaris!) will format infinite in a * different way, so better to handle it in an explicit way. */ addReplyBulkCString(d > 0 ? "inf" : "-inf"); } else { dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); addReplyString(sbuf,slen); } } /* Add a long double as a bulk reply, but uses a human readable formatting * of the double instead of exposing the crude behavior of doubles to the * dear user. */ void client::addReplyHumanLongDouble(long double d) { robj *o = createStringObjectFromLongDouble(d,1); addReplyBulk(o); decrRefCount(o); } /* Add a long long as integer reply or bulk len / multi bulk count. * Basically this is used to output <prefix><long long><crlf>. */ void client::addReplyLongLongWithPrefix(long long ll, char prefix) { char buf[128]; int len; /* Things like $3\r\n or *2\r\n are emitted very often by the protocol * so we have a few shared objects to use if the integer is small * like it is most of the times. */ if (prefix == '*' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(shared.mbulkhdr[ll]); return; } else if (prefix == '$' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(shared.bulkhdr[ll]); return; } buf[0] = prefix; len = ll2string(buf+1,sizeof(buf)-1,ll); buf[len+1] = '\r'; buf[len+2] = '\n'; addReplyString(buf,len+3); } void client::addReplyLongLong(long long ll) { if (ll == 0) addReply(shared.czero); else if (ll == 1) addReply(shared.cone); else addReplyLongLongWithPrefix(ll,':'); } void client::addReplyMultiBulkLen(long length) { if (length < OBJ_SHARED_BULKHDR_LEN) addReply(shared.mbulkhdr[length]); else addReplyLongLongWithPrefix(length,'*'); } /* Create the length prefix of a bulk reply, example: $2234 */ void client::addReplyBulkLen(robj *obj) { size_t len; if (sdsEncodedObject(obj)) { len = sdslen((sds)obj->ptr); } else { long n = (long)obj->ptr; /* Compute how many bytes will take this integer as a radix 10 string */ len = 1; if (n < 0) { len++; n = -n; } while((n = n/10) != 0) { len++; } } if (len < OBJ_SHARED_BULKHDR_LEN) addReply(shared.bulkhdr[len]); else addReplyLongLongWithPrefix(len,'$'); } /* Add a Redis Object as a bulk reply */ void client::addReplyBulk(robj *obj) { addReplyBulkLen(obj); addReply(obj); addReply(shared.crlf); } /* Add a C buffer as bulk reply */ void client::addReplyBulkCBuffer(const void *p, size_t len) { addReplyLongLongWithPrefix(len,'$'); addReplyString((const char *)p,len); addReply(shared.crlf); } /* Add sds to reply (takes ownership of sds and frees it) */ void client::addReplyBulkSds(sds s) { addReplyLongLongWithPrefix(sdslen(s),'$'); addReplySds(s); addReply(shared.crlf); } /* Add a C nul term string as bulk reply */ void client::addReplyBulkCString(const char *s) { if (s == NULL) { addReply(shared.nullbulk); } else { addReplyBulkCBuffer(s,strlen(s)); } } /* Add a long long as a bulk reply */ void client::addReplyBulkLongLong(long long ll) { char buf[64]; int len; len = ll2string(buf,64,ll); addReplyBulkCBuffer(buf,len); } /* Copy 'src' client output buffers into 'dst' client output buffers. * The function takes care of freeing the old output buffers of the * destination client. */ void copyClientOutputBuffer(client *dst, client *src) { listRelease(dst->m_reply); dst->m_reply = src->m_reply->listDup(); memcpy(dst->m_response_buff,src->m_response_buff,src->m_response_buff_pos); dst->m_response_buff_pos = src->m_response_buff_pos; dst->m_reply_bytes = src->m_reply_bytes; } /* Return true if the specified client has pending reply buffers to write to * the socket. */ int client::clientHasPendingReplies() { return m_response_buff_pos || m_reply->listLength(); } #define MAX_ACCEPTS_PER_CALL 1000 static void acceptCommonHandler(int fd, int flags, char *ip) { client *c; if ((c = createClient(fd)) == NULL) { serverLog(LL_WARNING, "Error registering fd event for the new client: %s (fd=%d)", strerror(errno),fd); close(fd); /* May be already closed, just ignore errors */ return; } /* If maxclient directive is set and this is one client more... close the * connection. Note that we create the client instead to check before * for this condition, since now the socket is already set in non-blocking * mode and we can send an error for free using the Kernel I/O */ if (server.clients->listLength() > server.maxclients) { char *err = "-ERR max number of clients reached\r\n"; /* That's a best effort error message, don't check write errors */ if (write(c->m_fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } /* If the server is running in protected mode (the default) and there * is no password set, nor a specific interface is bound, we don't accept * requests from non loopback interfaces. Instead we try to explain the * user what to do to fix it if needed. */ if (server.protected_mode && server.bindaddr_count == 0 && server.requirepass == NULL && !(flags & CLIENT_UNIX_SOCKET) && ip != NULL) { if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) { char *err = "-DENIED Redis is running in protected mode because protected " "mode is enabled, no bind address was specified, no " "authentication password is requested to clients. In this mode " "connections are only accepted from the loopback interface. " "If you want to connect from external computers to Redis you " "may adopt one of the following solutions: " "1) Just disable protected mode sending the command " "'CONFIG SET protected-mode no' from the loopback interface " "by connecting to Redis from the same host the server is " "running, however MAKE SURE Redis is not publicly accessible " "from internet if you do so. Use CONFIG REWRITE to make this " "change permanent. " "2) Alternatively you can just disable the protected mode by " "editing the Redis configuration file, and setting the protected " "mode option to 'no', and then restarting the server. " "3) If you started the server manually just for testing, restart " "it with the '--protected-mode no' option. " "4) Setup a bind address or an authentication password. " "NOTE: You only need to do one of the above things in order for " "the server to start accepting connections from the outside.\r\n"; if (write(c->m_fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } } server.stat_numconnections++; c->m_flags |= flags; } void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cport, cfd, max = MAX_ACCEPTS_PER_CALL; char cip[NET_IP_STR_LEN]; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); acceptCommonHandler(cfd,0,cip); } } void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cfd, max = MAX_ACCEPTS_PER_CALL; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetUnixAccept(server.neterr, fd); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); acceptCommonHandler(cfd,CLIENT_UNIX_SOCKET,NULL); } } void client::freeClientArgv() { int j; for (j = 0; j < m_argc; j++) decrRefCount(m_argv[j]); m_argc = 0; m_cmd = NULL; } /* Close all the slaves connections. This is useful in chained replication * when we resync with our own master and want to force all our slaves to * resync with us as well. */ void disconnectSlaves() { while (server.slaves->listLength()) { listNode *ln = server.slaves->listFirst(); freeClient((client*)ln->listNodeValue()); } } /* Remove the specified client from global lists where the client could * be referenced, not including the Pub/Sub channels. * This is used by freeClient() and replicationCacheMaster(). */ void client::unlinkClient() { /* If this is marked as current client unset it. */ if (server.current_client == this) server.current_client = NULL; /* Certain operations must be done only if the client has an active socket. * If the client was already unlinked or if it's a "fake client" the * fd is already set to -1. */ if (m_fd != -1) { /* Remove from the list of active clients. */ listNode* ln = server.clients->listSearchKey(this); serverAssert(ln != NULL); server.clients->listDelNode(ln); /* Unregister async I/O handlers and close the socket. */ server.el->aeDeleteFileEvent(m_fd,AE_READABLE); server.el->aeDeleteFileEvent(m_fd,AE_WRITABLE); close(m_fd); m_fd = -1; } /* Remove from the list of pending writes if needed. */ if (m_flags & CLIENT_PENDING_WRITE) { listNode* ln = server.clients_pending_write->listSearchKey(this); serverAssert(ln != NULL); server.clients_pending_write->listDelNode(ln); m_flags &= ~CLIENT_PENDING_WRITE; } /* When client was just unblocked because of a blocking operation, * remove it from the list of unblocked clients. */ if (m_flags & CLIENT_UNBLOCKED) { listNode* ln = server.unblocked_clients->listSearchKey(this); serverAssert(ln != NULL); server.unblocked_clients->listDelNode(ln); m_flags &= ~CLIENT_UNBLOCKED; } } void freeClient(client *c) { /* If it is our master that's being disconnected we should make sure * to cache the state to try a partial resynchronization later. * * Note that before doing this we make sure that the client is not in * some unexpected state, by checking its flags. */ if (server.master && c->m_flags & CLIENT_MASTER) { serverLog(LL_WARNING,"Connection with master lost."); if (!(c->m_flags & (CLIENT_CLOSE_AFTER_REPLY| CLIENT_CLOSE_ASAP| CLIENT_BLOCKED| CLIENT_UNBLOCKED))) { c->replicationCacheMaster(); return; } } c->~client(); zfree(c); } client::~client() { /* Log link disconnection with slave */ if ((m_flags & CLIENT_SLAVE) && !(m_flags & CLIENT_MONITOR)) { serverLog(LL_WARNING,"Connection with slave %s lost.", replicationGetSlaveName()); } /* Free the query buffer */ sdsfree(m_query_buf); sdsfree(m_pending_query_buf); m_query_buf = NULL; /* Deallocate structures used to block on blocking ops. */ if (m_flags & CLIENT_BLOCKED) unblockClient(); dictRelease(m_blocking_state.m_keys); /* UNWATCH all the keys */ unwatchAllKeys(); listRelease(m_watched_keys); /* Unsubscribe from all the pubsub channels */ pubsubUnsubscribeAllChannels(0); pubsubUnsubscribeAllPatterns(0); dictRelease(m_pubsub_channels); listRelease(m_pubsub_patterns); /* Free data structures. */ listRelease(m_reply); freeClientArgv(); /* Unlink the client: this will close the socket, remove the I/O * handlers, and remove references of the client from different * places where active clients may be referenced. */ unlinkClient(); /* Master/slave cleanup Case 1: * we lost the connection with a slave. */ if (m_flags & CLIENT_SLAVE) { if (m_replication_state == SLAVE_STATE_SEND_BULK) { if (m_replication_db_fd != -1) close(m_replication_db_fd); if (m_replication_db_preamble) sdsfree(m_replication_db_preamble); } list *l = (m_flags & CLIENT_MONITOR) ? server.monitors : server.slaves; listNode* ln = l->listSearchKey(this); serverAssert(ln != NULL); l->listDelNode(ln); /* We need to remember the time when we started to have zero * attached slaves, as after some time we'll free the replication * backlog. */ if (m_flags & CLIENT_SLAVE && server.slaves->listLength() == 0) server.repl_no_slaves_since = server.unixtime; refreshGoodSlavesCount(); } /* Master/slave cleanup Case 2: * we lost the connection with the master. */ if (m_flags & CLIENT_MASTER) replicationHandleMasterDisconnection(); /* If this client was scheduled for async freeing we need to remove it * from the queue. */ if (m_flags & CLIENT_CLOSE_ASAP) { listNode* ln = server.clients_to_close->listSearchKey(this); serverAssert(ln != NULL); server.clients_to_close->listDelNode(ln); } /* Release other dynamically allocated client structure fields, * and finally release the client structure itself. */ if (m_client_name) decrRefCount(m_client_name); zfree(m_argv); freeClientMultiState(this); sdsfree(m_cached_peer_id); } /* Schedule a client to free it at a safe time in the serverCron() function. * This function is useful when we need to terminate a client but we are in * a context where calling freeClient() is not possible, because the client * should be valid for the continuation of the flow of the program. */ void freeClientAsync(client *c) { if (c->m_flags & CLIENT_CLOSE_ASAP || c->m_flags & CLIENT_LUA) return; c->m_flags |= CLIENT_CLOSE_ASAP; server.clients_to_close->listAddNodeTail(c); } void freeClientsInAsyncFreeQueue() { while (server.clients_to_close->listLength()) { listNode *ln = server.clients_to_close->listFirst(); client *c = (client *)ln->listNodeValue(); c->m_flags &= ~CLIENT_CLOSE_ASAP; freeClient(c); server.clients_to_close->listDelNode(ln); } } /* Write data in output buffers to client. Return C_OK if the client * is still valid after the call, C_ERR if it was freed. */ int writeToClient(int fd, client *c, int handler_installed) { ssize_t nwritten = 0, totwritten = 0; size_t objlen; sds o; while(c->clientHasPendingReplies()) { if (c->m_response_buff_pos > 0) { nwritten = write(fd,c->m_response_buff+c->m_already_sent_len,c->m_response_buff_pos-c->m_already_sent_len); if (nwritten <= 0) break; c->m_already_sent_len += nwritten; totwritten += nwritten; /* If the buffer was sent, set bufpos to zero to continue with * the remainder of the reply. */ if ((int)c->m_already_sent_len == c->m_response_buff_pos) { c->m_response_buff_pos = 0; c->m_already_sent_len = 0; } } else { o = (sds)c->m_reply->listFirst()->listNodeValue(); objlen = sdslen(o); if (objlen == 0) { c->m_reply->listDelNode(c->m_reply->listFirst()); continue; } nwritten = write(fd, o + c->m_already_sent_len, objlen - c->m_already_sent_len); if (nwritten <= 0) break; c->m_already_sent_len += nwritten; totwritten += nwritten; /* If we fully sent the object on head go to the next one */ if (c->m_already_sent_len == objlen) { c->m_reply->listDelNode(c->m_reply->listFirst()); c->m_already_sent_len = 0; c->m_reply_bytes -= objlen; /* If there are no longer objects in the list, we expect * the count of reply bytes to be exactly zero. */ if (c->m_reply->listLength() == 0) serverAssert(c->m_reply_bytes == 0); } } /* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT * bytes, in a single threaded server it's a good idea to serve * other clients as well, even if a very large request comes from * super fast link that is always able to accept data (in real world * scenario think about 'KEYS *' against the loopback interface). * * However if we are over the maxmemory limit we ignore that and * just deliver as much data as it is possible to deliver. */ if (totwritten > NET_MAX_WRITES_PER_EVENT && (server.maxmemory == 0 || zmalloc_used_memory() < server.maxmemory)) break; } server.stat_net_output_bytes += totwritten; if (nwritten == -1) { if (errno == EAGAIN) { nwritten = 0; } else { serverLog(LL_VERBOSE, "Error writing to client: %s", strerror(errno)); freeClient(c); return C_ERR; } } if (totwritten > 0) { /* For clients representing masters we don't count sending data * as an interaction, since we always send REPLCONF ACK commands * that take some time to just fill the socket output buffer. * We just rely on data / pings received for timeout detection. */ if (!(c->m_flags & CLIENT_MASTER)) c->m_last_interaction_time = server.unixtime; } if (!c->clientHasPendingReplies()) { c->m_already_sent_len = 0; if (handler_installed) server.el->aeDeleteFileEvent(c->m_fd,AE_WRITABLE); /* Close connection after entire reply has been sent. */ if (c->m_flags & CLIENT_CLOSE_AFTER_REPLY) { freeClient(c); return C_ERR; } } return C_OK; } /* Write event handler. Just send data to the client. */ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(mask); writeToClient(fd,(client*)privdata,1); } /* This function is called just before entering the event loop, in the hope * we can just write the replies to the client output buffer without any * need to use a syscall in order to install the writable event handler, * get it called, and so forth. */ int handleClientsWithPendingWrites() { listNode *ln; int processed = server.clients_pending_write->listLength(); listIter li(server.clients_pending_write); while((ln = li.listNext())) { client *c = (client *)ln->listNodeValue(); c->m_flags &= ~CLIENT_PENDING_WRITE; server.clients_pending_write->listDelNode(ln); /* Try to write buffers to the client socket. */ if (writeToClient(c->m_fd,c,0) == C_ERR) continue; /* If there is nothing left, do nothing. Otherwise install * the write handler. */ if (c->clientHasPendingReplies() && server.el->aeCreateFileEvent(c->m_fd, AE_WRITABLE, sendReplyToClient, c) == AE_ERR) { freeClientAsync(c); } } return processed; } /* resetClient prepare the client to process the next command */ void client::resetClient() { redisCommandProc *prevcmd = m_cmd ? m_cmd->proc : NULL; freeClientArgv(); m_req_protocol_type = 0; m_multi_bulk_len = 0; m_bulk_len = -1; /* We clear the ASKING flag as well if we are not inside a MULTI, and * if what we just executed is not the ASKING command itself. */ if (!(m_flags & CLIENT_MULTI) && prevcmd != askingCommand) m_flags &= ~CLIENT_ASKING; /* Remove the CLIENT_REPLY_SKIP flag if any so that the reply * to the next command will be sent, but set the flag if the command * we just processed was "CLIENT REPLY SKIP". */ m_flags &= ~CLIENT_REPLY_SKIP; if (m_flags & CLIENT_REPLY_SKIP_NEXT) { m_flags |= CLIENT_REPLY_SKIP; m_flags &= ~CLIENT_REPLY_SKIP_NEXT; } } /* Like processMultibulkBuffer(), but for the inline protocol instead of RESP, * this function consumes the client query buffer and creates a command ready * to be executed inside the client structure. Returns C_OK if the command * is ready to be executed, or C_ERR if there is still protocol to read to * have a well formed command. The function also returns C_ERR when there is * a protocol error: in such a case the client structure is setup to reply * with the error and close the connection. */ int client::processInlineBuffer() { char *newline; int argc, j; sds *argv, aux; size_t querylen; /* Search for end of line */ newline = strchr(m_query_buf,'\n'); /* Nothing to do without a \r\n */ if (newline == NULL) { if (sdslen((sds)m_query_buf) > PROTO_INLINE_MAX_SIZE) { addReplyError("Protocol error: too big inline request"); setProtocolError("too big inline request", 0); } return C_ERR; } /* Handle the \r\n case. */ if (newline && newline != m_query_buf && *(newline-1) == '\r') newline--; /* Split the input buffer up to the \r\n */ querylen = newline-(m_query_buf); aux = sdsnewlen(m_query_buf,querylen); argv = sdssplitargs(aux,&argc); sdsfree(aux); if (argv == NULL) { addReplyError("Protocol error: unbalanced quotes in request"); setProtocolError("unbalanced quotes in inline request", 0); return C_ERR; } /* Newline from slaves can be used to refresh the last ACK time. * This is useful for a slave to ping back while loading a big * RDB file. */ if (querylen == 0 && m_flags & CLIENT_SLAVE) m_replication_ack_time = server.unixtime; /* Leave data after the first line of the query in the buffer */ sdsrange(m_query_buf,querylen+2,-1); /* Setup argv array on client structure */ if (argc) { if (m_argv) zfree(m_argv); m_argv = (robj **)zmalloc(sizeof(robj*)*argc); } /* Create redis objects for all arguments. */ for (m_argc = 0, j = 0; j < argc; j++) { if (sdslen((sds)argv[j])) { m_argv[m_argc] = createObject(OBJ_STRING,argv[j]); m_argc++; } else { sdsfree(argv[j]); } } zfree(argv); return C_OK; } /* Helper function. Trims query buffer to make the function that processes * multi bulk requests idempotent. */ #define PROTO_DUMP_LEN 128 void client::setProtocolError(const char *errstr, int pos) { if (server.verbosity <= LL_VERBOSE) { sds client_info = catClientInfoString(sdsempty()); /* Sample some protocol to given an idea about what was inside. */ char buf[256]; if (sdslen((sds)m_query_buf) < PROTO_DUMP_LEN) { snprintf(buf,sizeof(buf),"Query buffer during protocol error: '%s'", m_query_buf); } else { snprintf(buf,sizeof(buf),"Query buffer during protocol error: '%.*s' (... more %zu bytes ...) '%.*s'", PROTO_DUMP_LEN/2, m_query_buf, sdslen((sds)m_query_buf)-PROTO_DUMP_LEN, PROTO_DUMP_LEN/2, m_query_buf+sdslen((sds)m_query_buf)-PROTO_DUMP_LEN/2); } /* Remove non printable chars. */ char *p = buf; while (*p != '\0') { if (!isprint(*p)) *p = '.'; p++; } /* Log all the client and protocol info. */ serverLog(LL_VERBOSE, "Protocol error (%s) from client: %s. %s", errstr, client_info, buf); sdsfree(client_info); } m_flags |= CLIENT_CLOSE_AFTER_REPLY; sdsrange(m_query_buf,pos,-1); } /* Process the query buffer for client 'c', setting up the client argument * vector for command execution. Returns C_OK if after running the function * the client has a well-formed ready to be processed command, otherwise * C_ERR if there is still to read more buffer to get the full command. * The function also returns C_ERR when there is a protocol error: in such a * case the client structure is setup to reply with the error and close * the connection. * * This function is called if processInputBuffer() detects that the next * command is in RESP format, so the first byte in the command is found * to be '*'. Otherwise for inline commands processInlineBuffer() is called. */ int client::processMultibulkBuffer() { char *newline = NULL; int pos = 0, ok; long long ll; if (m_multi_bulk_len == 0) { /* The client should have been reset */ serverAssertWithInfo(this,NULL,m_argc == 0); /* Multi bulk length cannot be read without a \r\n */ newline = strchr(m_query_buf,'\r'); if (newline == NULL) { if (sdslen((sds)m_query_buf) > PROTO_INLINE_MAX_SIZE) { addReplyError("Protocol error: too big mbulk count string"); setProtocolError("too big mbulk count string",0); } return C_ERR; } /* Buffer should also contain \n */ if (newline-m_query_buf > ((signed)sdslen((sds)m_query_buf)-2)) return C_ERR; /* We know for sure there is a whole line since newline != NULL, * so go ahead and find out the multi bulk length. */ serverAssertWithInfo(this,NULL,m_query_buf[0] == '*'); ok = string2ll(m_query_buf+1,newline-(m_query_buf+1),&ll); if (!ok || ll > 1024*1024) { addReplyError("Protocol error: invalid multibulk length"); setProtocolError("invalid mbulk count", pos); return C_ERR; } pos = (newline-m_query_buf)+2; if (ll <= 0) { sdsrange(m_query_buf,pos,-1); return C_OK; } m_multi_bulk_len = ll; /* Setup argv array on client structure */ if (m_argv) zfree(m_argv); m_argv = (robj **)zmalloc(sizeof(robj*)*m_multi_bulk_len); } serverAssertWithInfo(this,NULL,m_multi_bulk_len > 0); while(m_multi_bulk_len) { /* Read bulk length if unknown */ if (m_bulk_len == -1) { newline = strchr(m_query_buf+pos,'\r'); if (newline == NULL) { if (sdslen((sds)m_query_buf) > PROTO_INLINE_MAX_SIZE) { addReplyError( "Protocol error: too big bulk count string"); setProtocolError("too big bulk count string", 0); return C_ERR; } break; } /* Buffer should also contain \n */ if (newline-m_query_buf > ((signed)sdslen((sds)m_query_buf)-2)) break; if (m_query_buf[pos] != '$') { addReplyErrorFormat( "Protocol error: expected '$', got '%c'", m_query_buf[pos]); setProtocolError("expected $ but got something else", pos); return C_ERR; } ok = string2ll(m_query_buf+pos+1,newline-(m_query_buf+pos+1),&ll); if (!ok || ll < 0 || ll > 512*1024*1024) { addReplyError("Protocol error: invalid bulk length"); setProtocolError("invalid bulk length", pos); return C_ERR; } pos += newline-(m_query_buf+pos)+2; if (ll >= PROTO_MBULK_BIG_ARG) { size_t qblen; /* If we are going to read a large object from network * try to make it likely that it will start at querybuf * boundary so that we can optimize object creation * avoiding a large copy of data. */ sdsrange(m_query_buf,pos,-1); pos = 0; qblen = sdslen((sds)m_query_buf); /* Hint the sds library about the amount of bytes this string is * going to contain. */ if (qblen < (size_t)ll+2) m_query_buf = sdsMakeRoomFor(m_query_buf,ll+2-qblen); } m_bulk_len = ll; } /* Read bulk argument */ if (sdslen((sds)m_query_buf)-pos < (unsigned)(m_bulk_len+2)) { /* Not enough data (+2 == trailing \r\n) */ break; } else { /* Optimization: if the buffer contains JUST our bulk element * instead of creating a new object by *copying* the sds we * just use the current sds string. */ if (pos == 0 && m_bulk_len >= PROTO_MBULK_BIG_ARG && (signed) sdslen((sds)m_query_buf) == m_bulk_len+2) { m_argv[m_argc++] = createObject(OBJ_STRING,m_query_buf); sdsIncrLen(m_query_buf,-2); /* remove CRLF */ /* Assume that if we saw a fat argument we'll see another one * likely... */ m_query_buf = sdsnewlen(NULL,m_bulk_len+2); sdsclear(m_query_buf); pos = 0; } else { m_argv[m_argc++] = createStringObject(m_query_buf+pos,m_bulk_len); pos += m_bulk_len+2; } m_bulk_len = -1; m_multi_bulk_len--; } } /* Trim to pos */ if (pos) sdsrange(m_query_buf,pos,-1); /* We're done when multibulk == 0 */ if (m_multi_bulk_len == 0) return C_OK; /* Still not ready to process the command */ return C_ERR; } /* This function is called every time, in the client structure 'c', there is * more query buffer to process, because we read more data from the socket * or because a client was blocked and later reactivated, so there could be * pending query buffer, already representing a full command, to process. */ void client::processInputBuffer() { server.current_client = this; /* Keep processing while there is something in the input buffer */ while(sdslen((sds)m_query_buf)) { /* Return if clients are paused. */ if (!(m_flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (m_flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). * * The same applies for clients we want to terminate ASAP. */ if (m_flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break; /* Determine request type when unknown. */ if (!m_req_protocol_type) { if (m_query_buf[0] == '*') { m_req_protocol_type = PROTO_REQ_MULTIBULK; } else { m_req_protocol_type = PROTO_REQ_INLINE; } } if (m_req_protocol_type == PROTO_REQ_INLINE) { if (processInlineBuffer() != C_OK) break; } else if (m_req_protocol_type == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer() != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (m_argc == 0) { resetClient(); } else { /* Only reset the client when the command was executed. */ if (processCommand(this) == C_OK) { if (m_flags & CLIENT_MASTER && !(m_flags & CLIENT_MULTI)) { /* Update the applied replication offset of our master. */ m_applied_replication_offset = m_read_replication_offset - sdslen((sds)m_query_buf); } /* Don't reset the client structure for clients blocked in a * module blocking command, so that the reply callback will * still be able to access the client argv and argc field. * The client will be reset in unblockClientFromModule(). */ if (!(m_flags & CLIENT_BLOCKED) || m_blocking_op_type != BLOCKED_MODULE) resetClient(); } /* freeMemoryIfNeeded may flush slave output buffers. This may * result into a slave, that may be the active client, to be * freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(mask); client *c = (client*) privdata; size_t read_len = PROTO_IOBUF_LEN; /* If this is a multi bulk request, and we are processing a bulk reply * that is large enough, try to maximize the probability that the query * buffer contains exactly the SDS string representing the object, even * at the risk of requiring more read(2) calls. This way the function * processMultiBulkBuffer() can avoid copying buffers to create the * Redis Object representing the argument. */ if (c->m_req_protocol_type == PROTO_REQ_MULTIBULK && c->m_multi_bulk_len && c->m_bulk_len != -1 && c->m_bulk_len >= PROTO_MBULK_BIG_ARG) { int remaining = (unsigned)(c->m_bulk_len+2)-sdslen(c->m_query_buf); if (remaining < read_len) read_len = remaining; } size_t qblen = sdslen(c->m_query_buf); if (c->m_query_buf_peak < qblen) c->m_query_buf_peak = qblen; c->m_query_buf = sdsMakeRoomFor(c->m_query_buf, read_len); ssize_t nread = read(fd, c->m_query_buf+qblen, read_len); if (nread == -1) { if (errno == EAGAIN) { return; } else { serverLog(LL_VERBOSE, "Reading from client: %s",strerror(errno)); freeClient(c); return; } } else if (nread == 0) { serverLog(LL_VERBOSE, "Client closed connection"); freeClient(c); return; } else if (c->m_flags & CLIENT_MASTER) { /* Append the query buffer to the pending (not applied) buffer * of the master. We'll use this buffer later in order to have a * copy of the string applied by the last command executed. */ c->m_pending_query_buf = sdscatlen(c->m_pending_query_buf, c->m_query_buf+qblen,nread); } sdsIncrLen(c->m_query_buf,nread); c->m_last_interaction_time = server.unixtime; if (c->m_flags & CLIENT_MASTER) c->m_read_replication_offset += nread; server.stat_net_input_bytes += nread; if (sdslen(c->m_query_buf) > server.client_max_querybuf_len) { sds ci = c->catClientInfoString(sdsempty()), bytes = sdsempty(); bytes = sdscatrepr(bytes,c->m_query_buf,64); serverLog(LL_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes); sdsfree(ci); sdsfree(bytes); freeClient(c); return; } /* Time to process the buffer. If the client is a master we need to * compute the difference between the applied offset before and after * processing the buffer, to understand how much of the replication stream * was actually applied to the master state: this quantity, and its * corresponding part of the replication stream, will be propagated to * the sub-slaves and to the replication backlog. */ if (!(c->m_flags & CLIENT_MASTER)) { c->processInputBuffer(); } else { size_t prev_offset = c->m_applied_replication_offset; c->processInputBuffer(); size_t applied = c->m_applied_replication_offset - prev_offset; if (applied) { replicationFeedSlavesFromMasterStream(server.slaves, c->m_pending_query_buf, applied); sdsrange(c->m_pending_query_buf,applied,-1); } } } void getClientsMaxBuffers(unsigned long *longest_output_list, unsigned long *biggest_input_buffer) { client *c; listNode *ln; unsigned long lol = 0, bib = 0; listIter li(server.clients); while ((ln = li.listNext()) != NULL) { c = (client *)ln->listNodeValue(); if (c->m_reply->listLength() > lol) lol = c->m_reply->listLength(); if (sdslen(c->m_query_buf) > bib) bib = sdslen(c->m_query_buf); } *longest_output_list = lol; *biggest_input_buffer = bib; } /* A Redis "Peer ID" is a colon separated ip:port pair. * For IPv4 it's in the form x.y.z.k:port, example: "127.0.0.1:1234". * For IPv6 addresses we use [] around the IP part, like in "[::1]:1234". * For Unix sockets we use path:0, like in "/tmp/redis:0". * * A Peer ID always fits inside a buffer of NET_PEER_ID_LEN bytes, including * the null term. * * On failure the function still populates 'peerid' with the "?:0" string * in case you want to relax error checking or need to display something * anyway (see anetPeerToString implementation for more info). */ void client::genClientPeerId(char *peerid, size_t peerid_len) { if (m_flags & CLIENT_UNIX_SOCKET) { /* Unix socket client. */ snprintf(peerid,peerid_len,"%s:0",server.unixsocket); } else { /* TCP client. */ anetFormatPeer(m_fd, peerid, peerid_len); } } /* This function returns the client peer id, by creating and caching it * if client->peerid is NULL, otherwise returning the cached value. * The Peer ID never changes during the life of the client, however it * is expensive to compute. */ char* client::getClientPeerId() { char peerid[NET_PEER_ID_LEN]; if (m_cached_peer_id == NULL) { genClientPeerId(peerid, sizeof(peerid)); m_cached_peer_id = sdsnew(peerid); } return m_cached_peer_id; } /* Concatenate a string representing the state of a client in an human * readable format, into the sds string 's'. */ sds client::catClientInfoString(sds s) { char flags[16], events[3], *p; int emask; p = flags; if (m_flags & CLIENT_SLAVE) { if (m_flags & CLIENT_MONITOR) *p++ = 'O'; else *p++ = 'S'; } if (m_flags & CLIENT_MASTER) *p++ = 'M'; if (m_flags & CLIENT_MULTI) *p++ = 'x'; if (m_flags & CLIENT_BLOCKED) *p++ = 'b'; if (m_flags & CLIENT_DIRTY_CAS) *p++ = 'd'; if (m_flags & CLIENT_CLOSE_AFTER_REPLY) *p++ = 'c'; if (m_flags & CLIENT_UNBLOCKED) *p++ = 'u'; if (m_flags & CLIENT_CLOSE_ASAP) *p++ = 'A'; if (m_flags & CLIENT_UNIX_SOCKET) *p++ = 'U'; if (m_flags & CLIENT_READONLY) *p++ = 'r'; if (p == flags) *p++ = 'N'; *p++ = '\0'; emask = m_fd == -1 ? 0 : server.el->aeGetFileEvents(m_fd); p = events; if (emask & AE_READABLE) *p++ = 'r'; if (emask & AE_WRITABLE) *p++ = 'w'; *p = '\0'; return sdscatfmt(s, "id=%U addr=%s fd=%i name=%s age=%I idle=%I flags=%s db=%i sub=%i psub=%i multi=%i qbuf=%U qbuf-free=%U obl=%U oll=%U omem=%U events=%s cmd=%s", (unsigned long long) m_client_id, getClientPeerId(), m_fd, m_client_name ? (char*)m_client_name->ptr : "", (long long)(server.unixtime - m_ctime), (long long)(server.unixtime - m_last_interaction_time), flags, m_cur_selected_db->m_id, (int) m_pubsub_channels->dictSize(), (int) m_pubsub_patterns->listLength(), (m_flags & CLIENT_MULTI) ? m_multi_exec_state.m_count : -1, (unsigned long long) sdslen(m_query_buf), (unsigned long long) sdsavail(m_query_buf), (unsigned long long) m_response_buff_pos, (unsigned long long) m_reply->listLength(), (unsigned long long) getClientOutputBufferMemoryUsage(), events, m_last_cmd ? m_last_cmd->name : "NULL"); } sds getAllClientsInfoString() { listNode *ln; sds o = sdsnewlen(NULL,200*server.clients->listLength()); sdsclear(o); listIter li(server.clients); while ((ln = li.listNext()) != NULL) { client* _client = (client *)ln->listNodeValue(); o = _client->catClientInfoString(o); o = sdscatlen(o,"\n",1); } return o; } void clientCommand(client *c) { listNode *ln; client *_client; if (!strcasecmp((const char*)c->m_argv[1]->ptr,"list") && c->m_argc == 2) { /* CLIENT LIST */ sds o = getAllClientsInfoString(); c->addReplyBulkCBuffer(o,sdslen(o)); sdsfree(o); } else if (!strcasecmp((const char*)c->m_argv[1]->ptr,"reply") && c->m_argc == 3) { /* CLIENT REPLY ON|OFF|SKIP */ if (!strcasecmp((const char*)c->m_argv[2]->ptr,"on")) { c->m_flags &= ~(CLIENT_REPLY_SKIP|CLIENT_REPLY_OFF); c->addReply(shared.ok); } else if (!strcasecmp((const char*)c->m_argv[2]->ptr,"off")) { c->m_flags |= CLIENT_REPLY_OFF; } else if (!strcasecmp((const char*)c->m_argv[2]->ptr,"skip")) { if (!(c->m_flags & CLIENT_REPLY_OFF)) c->m_flags |= CLIENT_REPLY_SKIP_NEXT; } else { c->addReply(shared.syntaxerr); return; } } else if (!strcasecmp((const char*)c->m_argv[1]->ptr,"kill")) { /* CLIENT KILL <ip:port> * CLIENT KILL <option> [value] ... <option> [value] */ char *addr = NULL; int type = -1; uint64_t id = 0; int skipme = 1; int killed = 0, close_this_client = 0; if (c->m_argc == 3) { /* Old style syntax: CLIENT KILL <addr> */ addr = (char *)c->m_argv[2]->ptr; skipme = 0; /* With the old form, you can kill yourself. */ } else if (c->m_argc > 3) { int i = 2; /* Next option index. */ /* New style syntax: parse options. */ while(i < c->m_argc) { int moreargs = c->m_argc > i+1; if (!strcasecmp((const char*)c->m_argv[i]->ptr,"id") && moreargs) { long long tmp; if (getLongLongFromObjectOrReply(c,c->m_argv[i+1],&tmp,NULL) != C_OK) return; id = tmp; } else if (!strcasecmp((const char*)c->m_argv[i]->ptr,"type") && moreargs) { type = client::getClientTypeByName((char*)c->m_argv[i+1]->ptr); if (type == -1) { c->addReplyErrorFormat("Unknown client type '%s'", (char*) c->m_argv[i+1]->ptr); return; } } else if (!strcasecmp((const char*)c->m_argv[i]->ptr,"addr") && moreargs) { addr = (char *)c->m_argv[i+1]->ptr; } else if (!strcasecmp((const char*)c->m_argv[i]->ptr,"skipme") && moreargs) { if (!strcasecmp((const char*)c->m_argv[i+1]->ptr,"yes")) { skipme = 1; } else if (!strcasecmp((const char*)c->m_argv[i+1]->ptr,"no")) { skipme = 0; } else { c->addReply(shared.syntaxerr); return; } } else { c->addReply(shared.syntaxerr); return; } i += 2; } } else { c->addReply(shared.syntaxerr); return; } /* Iterate clients killing all the matching clients. */ listIter li(server.clients); while ((ln = li.listNext()) != NULL) { _client = (client *)ln->listNodeValue(); if (addr && strcmp(_client->getClientPeerId(),addr) != 0) continue; if (type != -1 && _client->getClientType() != type) continue; if (id != 0 && _client->m_client_id != id) continue; if (c == _client && skipme) continue; /* Kill it. */ if (c == _client) { close_this_client = 1; } else { freeClient(_client); } killed++; } /* Reply according to old/new format. */ if (c->m_argc == 3) { if (killed == 0) c->addReplyError("No such client"); else c->addReply(shared.ok); } else { c->addReplyLongLong(killed); } /* If this client has to be closed, flag it as CLOSE_AFTER_REPLY * only after we queued the reply to its output buffers. */ if (close_this_client) c->m_flags |= CLIENT_CLOSE_AFTER_REPLY; } else if (!strcasecmp((const char*)c->m_argv[1]->ptr,"setname") && c->m_argc == 3) { int j; int len = sdslen((sds)c->m_argv[2]->ptr); char *p = (char *)c->m_argv[2]->ptr; /* Setting the client name to an empty string actually removes * the current name. */ if (len == 0) { if (c->m_client_name) decrRefCount(c->m_client_name); c->m_client_name = NULL; c->addReply(shared.ok); return; } /* Otherwise check if the charset is ok. We need to do this otherwise * CLIENT LIST format will break. You should always be able to * split by space to get the different fields. */ for (j = 0; j < len; j++) { if (p[j] < '!' || p[j] > '~') { /* ASCII is assumed. */ c->addReplyError( "Client names cannot contain spaces, " "newlines or special characters."); return; } } if (c->m_client_name) decrRefCount(c->m_client_name); c->m_client_name = c->m_argv[2]; incrRefCount(c->m_client_name); c->addReply(shared.ok); } else if (!strcasecmp((const char*)c->m_argv[1]->ptr,"getname") && c->m_argc == 2) { if (c->m_client_name) c->addReplyBulk(c->m_client_name); else c->addReply(shared.nullbulk); } else if (!strcasecmp((const char*)c->m_argv[1]->ptr,"pause") && c->m_argc == 3) { long long duration; if (getTimeoutFromObjectOrReply(c,c->m_argv[2],&duration,UNIT_MILLISECONDS) != C_OK) return; pauseClients(duration); c->addReply(shared.ok); } else { c->addReplyError( "Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME | PAUSE | REPLY)"); } } /* This callback is bound to POST and "Host:" command names. Those are not * really commands, but are used in security attacks in order to talk to * Redis instances via HTTP, with a technique called "cross protocol scripting" * which exploits the fact that services like Redis will discard invalid * HTTP headers and will process what follows. * * As a protection against this attack, Redis will terminate the connection * when a POST or "Host:" header is seen, and will log the event from * time to time (to avoid creating a DOS as a result of too many logs). */ void securityWarningCommand(client *c) { static time_t logged_time; time_t now = time(NULL); if (labs(now-logged_time) > 60) { serverLog(LL_WARNING,"Possible SECURITY ATTACK detected. It looks like somebody is sending POST or Host: commands to Redis. This is likely due to an attacker attempting to use Cross Protocol Scripting to compromise your Redis instance. Connection aborted."); logged_time = now; } freeClientAsync(c); } /* Rewrite the command vector of the client. All the new objects ref count * is incremented. The old command vector is freed, and the old objects * ref count is decremented. */ void client::rewriteClientCommandVector(int argc, ...) { va_list ap; int j; robj **argv = (robj **)zmalloc(sizeof(robj*)*argc); va_start(ap,argc); for (j = 0; j < argc; j++) { robj *a; a = va_arg(ap, robj*); argv[j] = a; incrRefCount(a); } /* We free the objects in the original vector at the end, so we are * sure that if the same objects are reused in the new vector the * refcount gets incremented before it gets decremented. */ for (j = 0; j < m_argc; j++) decrRefCount(m_argv[j]); zfree(m_argv); /* Replace argv and argc with our new versions. */ m_argv = argv; m_argc = argc; m_cmd = lookupCommandOrOriginal((sds)m_argv[0]->ptr); serverAssertWithInfo(this,NULL,m_cmd != NULL); va_end(ap); } /* Completely replace the client command vector with the provided one. */ void client::replaceClientCommandVector(int argc, robj **argv) { freeClientArgv(); zfree(m_argv); m_argv = argv; m_argc = argc; m_cmd = lookupCommandOrOriginal((sds)m_argv[0]->ptr); serverAssertWithInfo(this,NULL,m_cmd != NULL); } /* Rewrite a single item in the command vector. * The new val ref count is incremented, and the old decremented. * * It is possible to specify an argument over the current size of the * argument vector: in this case the array of objects gets reallocated * and c->argc set to the max value. However it's up to the caller to * * 1. Make sure there are no "holes" and all the arguments are set. * 2. If the original argument vector was longer than the one we * want to end with, it's up to the caller to set c->argc and * free the no longer used objects on c->argv. */ void client::rewriteClientCommandArgument(int i, robj *newval) { robj *oldval; if (i >= m_argc) { m_argv = (robj **)zrealloc(m_argv,sizeof(robj*)*(i+1)); m_argc = i+1; m_argv[i] = NULL; } oldval = m_argv[i]; m_argv[i] = newval; incrRefCount(newval); if (oldval) decrRefCount(oldval); /* If this is the command name make sure to fix c->cmd. */ if (i == 0) { m_cmd = lookupCommandOrOriginal((sds)m_argv[0]->ptr); serverAssertWithInfo(this,NULL,m_cmd != NULL); } } /* This function returns the number of bytes that Redis is virtually * using to store the reply still not read by the client. * It is "virtual" since the reply output list may contain objects that * are shared and are not really using additional memory. * * The function returns the total sum of the length of all the objects * stored in the output list, plus the memory used to allocate every * list node. The static reply buffer is not taken into account since it * is allocated anyway. * * Note: this function is very fast so can be called as many time as * the caller wishes. The main usage of this function currently is * enforcing the client output length limits. */ unsigned long client::getClientOutputBufferMemoryUsage() { unsigned long list_item_size = sizeof(listNode)+5; /* The +5 above means we assume an sds16 hdr, may not be true * but is not going to be a problem. */ return m_reply_bytes + (list_item_size*m_reply->listLength()); } /* Get the class of a client, used in order to enforce limits to different * classes of clients. * * The function will return one of the following: * CLIENT_TYPE_NORMAL -> Normal client * CLIENT_TYPE_SLAVE -> Slave or client executing MONITOR command * CLIENT_TYPE_PUBSUB -> Client subscribed to Pub/Sub channels * CLIENT_TYPE_MASTER -> The client representing our replication master. */ int client::getClientType() { if (m_flags & CLIENT_MASTER) return CLIENT_TYPE_MASTER; if ((m_flags & CLIENT_SLAVE) && !(m_flags & CLIENT_MONITOR)) return CLIENT_TYPE_SLAVE; if (m_flags & CLIENT_PUBSUB) return CLIENT_TYPE_PUBSUB; return CLIENT_TYPE_NORMAL; } int client::getClientTypeByName(char *name) { if (!strcasecmp(name,"normal")) return CLIENT_TYPE_NORMAL; else if (!strcasecmp(name,"slave")) return CLIENT_TYPE_SLAVE; else if (!strcasecmp(name,"pubsub")) return CLIENT_TYPE_PUBSUB; else if (!strcasecmp(name,"master")) return CLIENT_TYPE_MASTER; else return -1; } char *client::getClientTypeName(int client_name) { switch(client_name) { case CLIENT_TYPE_NORMAL: return "normal"; case CLIENT_TYPE_SLAVE: return "slave"; case CLIENT_TYPE_PUBSUB: return "pubsub"; case CLIENT_TYPE_MASTER: return "master"; default: return NULL; } } /* The function checks if the client reached output buffer soft or hard * limit, and also update the state needed to check the soft limit as * a side effect. * * Return value: non-zero if the client reached the soft or the hard limit. * Otherwise zero is returned. */ int client::checkClientOutputBufferLimits() { int soft = 0; int hard = 0; int _class; unsigned long used_mem = getClientOutputBufferMemoryUsage(); _class = getClientType(); /* For the purpose of output buffer limiting, masters are handled * like normal clients. */ if (_class == CLIENT_TYPE_MASTER) _class = CLIENT_TYPE_NORMAL; if (server.client_obuf_limits[_class].hard_limit_bytes && used_mem >= server.client_obuf_limits[_class].hard_limit_bytes) hard = 1; if (server.client_obuf_limits[_class].soft_limit_bytes && used_mem >= server.client_obuf_limits[_class].soft_limit_bytes) soft = 1; /* We need to check if the soft limit is reached continuously for the * specified amount of seconds. */ if (soft) { if (m_obuf_soft_limit_reached_time == 0) { m_obuf_soft_limit_reached_time = server.unixtime; soft = 0; /* First time we see the soft limit reached */ } else { time_t elapsed = server.unixtime - m_obuf_soft_limit_reached_time; if (elapsed <= server.client_obuf_limits[_class].soft_limit_seconds) { soft = 0; /* The client still did not reached the max number of seconds for the soft limit to be considered reached. */ } } } else { m_obuf_soft_limit_reached_time = 0; } return soft || hard; } /* Asynchronously close a client if soft or hard limit is reached on the * output buffer size. The caller can check if the client will be closed * checking if the client CLIENT_CLOSE_ASAP flag is set. * * Note: we need to close the client asynchronously because this function is * called from contexts where the client can't be freed safely, i.e. from the * lower level functions pushing data inside the client output buffers. */ void client::asyncCloseClientOnOutputBufferLimitReached() { serverAssert(m_reply_bytes < SIZE_MAX-(1024*64)); if (m_reply_bytes == 0 || m_flags & CLIENT_CLOSE_ASAP) return; if (checkClientOutputBufferLimits()) { sds client = catClientInfoString(sdsempty()); freeClientAsync(this); serverLog(LL_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client); sdsfree(client); } } /* Helper function used by freeMemoryIfNeeded() in order to flush slaves * output buffers without returning control to the event loop. * This is also called by SHUTDOWN for a best-effort attempt to send * slaves the latest writes. */ void flushSlavesOutputBuffers() { listNode *ln; listIter li(server.slaves); while((ln = li.listNext())) { client *slave = (client *)ln->listNodeValue(); int events; /* Note that the following will not flush output buffers of slaves * in STATE_ONLINE but having put_online_on_ack set to true: in this * case the writable event is never installed, since the purpose * of put_online_on_ack is to postpone the moment it is installed. * This is what we want since slaves in this state should not receive * writes before the first ACK. */ events = server.el->aeGetFileEvents(slave->m_fd); if (events & AE_WRITABLE && slave->m_replication_state == SLAVE_STATE_ONLINE && slave->clientHasPendingReplies()) { writeToClient(slave->m_fd,slave,0); } } } /* Pause clients up to the specified unixtime (in ms). While clients * are paused no command is processed from clients, so the data set can't * change during that time. * * However while this function pauses normal and Pub/Sub clients, slaves are * still served, so this function can be used on server upgrades where it is * required that slaves process the latest bytes from the replication stream * before being turned to masters. * * This function is also internally used by Redis Cluster for the manual * failover procedure implemented by CLUSTER FAILOVER. * * The function always succeed, even if there is already a pause in progress. * In such a case, the pause is extended if the duration is more than the * time left for the previous duration. However if the duration is smaller * than the time left for the previous pause, no change is made to the * left duration. */ void pauseClients(mstime_t end) { if (!server.clients_paused || end > server.clients_pause_end_time) server.clients_pause_end_time = end; server.clients_paused = 1; } /* Return non-zero if clients are currently paused. As a side effect the * function checks if the pause time was reached and clear it. */ int clientsArePaused() { if (server.clients_paused && server.clients_pause_end_time < server.mstime) { listNode *ln; client *c; server.clients_paused = 0; /* Put all the clients in the unblocked clients queue in order to * force the re-processing of the input buffer if any. */ listIter li(server.clients); while ((ln = li.listNext()) != NULL) { c = (client *)ln->listNodeValue(); /* Don't touch slaves and blocked clients. The latter pending * requests be processed when unblocked. */ if (c->m_flags & (CLIENT_SLAVE|CLIENT_BLOCKED)) continue; c->m_flags |= CLIENT_UNBLOCKED; server.unblocked_clients->listAddNodeTail(c); } } return server.clients_paused; } /* This function is called by Redis in order to process a few events from * time to time while blocked into some not interruptible operation. * This allows to reply to clients with the -LOADING error while loading the * data set at startup or after a full resynchronization with the master * and so forth. * * It calls the event loop in order to process a few events. Specifically we * try to call the event loop 4 times as long as we receive acknowledge that * some event was processed, in order to go forward with the accept, read, * write, close sequence needed to serve a client. * * The function returns the total number of events processed. */ int processEventsWhileBlocked() { int iterations = 4; /* See the function top-comment. */ int count = 0; while (iterations--) { int events = 0; events += server.el->aeProcessEvents(AE_FILE_EVENTS|AE_DONT_WAIT); events += handleClientsWithPendingWrites(); if (!events) break; count += events; } return count; }
37.79708
266
0.620357
shaishasag
304094067961de4e65ca6ff7ce353748b9da1303
4,556
cpp
C++
main.cpp
dcblack/systemc-main
96d6d9e829bf7841e30e40c0bdb282291f0b1ddc
[ "Apache-2.0" ]
null
null
null
main.cpp
dcblack/systemc-main
96d6d9e829bf7841e30e40c0bdb282291f0b1ddc
[ "Apache-2.0" ]
null
null
null
main.cpp
dcblack/systemc-main
96d6d9e829bf7841e30e40c0bdb282291f0b1ddc
[ "Apache-2.0" ]
1
2021-03-01T14:57:20.000Z
2021-03-01T14:57:20.000Z
//FILE main.cpp (systemc) // $Info: Entry point for executing simulation for 'basic'.$ // Copyright 2018 Doulos Inc. All rights reserved. // Licensed under Apache 2.0 - see accompanying LICENSE FILE. //----------------------------------------------------------------------------- #include "top.hpp" #include "wallclock.hpp" #if __cplusplus >= 201103L # include <memory> #endif #include "report.hpp" namespace { const char* MSGID = "/Doulos Inc/SystemC-Example/main"; double elaboration_cpuTime=-1.0, starting_cpuTime=-1.0, finished_cpuTime=-1.0; int summary(); //< Used in sc_main return to display summary provide PASS/FAIL return value } using namespace sc_core; using namespace std; // We don't always use argc and argv, but this is the only allowed // syntax for sc_main. Moreover, if we desire to use argc and argv // elsewhere, we simply use sc_core::sc_argc() and sc_core::sc_argv(), // which have been captured prior to calling here. #if __cplusplus < 201703L #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunused-parameter" #endif #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" #endif int sc_main(int argc, char *argv[]) //< main entry-point to SystemC { #ifdef __clang__ # pragma clang diagnostic pop #endif #ifdef __GNUC__ # pragma GCC diagnostic pop #endif #else int sc_main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) //< main entry-point to SystemC { #endif // Pointer to top-level module #if __cplusplus < 201103L Top* top; #else std::unique_ptr<Top> top; #endif // Elaborate elaboration_cpuTime = get_cpu_time(); //< Capture start of elaboration try { // Construct top-level #if __cplusplus < 201103L top = new Top("top"); #else top = std::make_unique<Top>("top"); #endif } catch (sc_core::sc_exception& e) { REPORT(INFO,"\n" << e.what() << "\n\n*** Please fix elaboration errors and retry. ***"); return summary(); } catch (...) { REPORT(INFO,"\n Error: *** Caught unknown exception during elaboration. ***"); return summary(); } // Simulate sc_core::sc_time finished_simTime; try { REPORT(INFO,"Starting kernel"); starting_cpuTime = get_cpu_time(); //< Capture start of simulation sc_core::sc_start(); finished_simTime = sc_core::sc_time_stamp(); finished_cpuTime = get_cpu_time(); } catch (sc_core::sc_exception& e) { REPORT(WARNING,"\n\nCaught exception during active simulation.\n" << e.what()); } catch (...) { REPORT(WARNING,"Error: Caught unknown exception during active simulation."); } REPORT(INFO,"Exited kernel at " << finished_simTime); // Clean up if (! sc_core::sc_end_of_simulation_invoked()) { try { REPORT(INFO,"ERROR: Simulation stopped without explicit sc_stop()"); } catch(sc_core::sc_exception& e) { REPORT(INFO,"\n\n" << e.what()); } sc_core::sc_stop(); //< this will invoke end_of_simulation() callbacks }//endif return summary(); } //----------------------------------------------------------------------------- namespace { // Summarize results int summary() { string kind = "Simulation"; if ( starting_cpuTime < 0.0 ) { kind = "Elaboration"; starting_cpuTime = finished_cpuTime = get_cpu_time(); } if ( finished_cpuTime < 0.0 ) { finished_cpuTime = get_cpu_time(); } auto errors = sc_report_handler::get_count(SC_ERROR) + sc_report_handler::get_count(SC_FATAL); REPORT(INFO, "\n" << string(80,'#') << "\nSummary for " << sc_argv()[0] << ":\n " << "CPU elaboration time " << setprecision(4) << (starting_cpuTime - elaboration_cpuTime) << " sec\n " << "CPU simulation time " << setprecision(4) << (finished_cpuTime - starting_cpuTime) << " sec\n " << setw(2) << sc_report_handler::get_count(SC_INFO) << " informational messages" << "\n " << setw(2) << sc_report_handler::get_count(SC_WARNING) << " warnings" << "\n " << setw(2) << sc_report_handler::get_count(SC_ERROR) << " errors" << "\n " << setw(2) << sc_report_handler::get_count(SC_FATAL) << " fatalities" << "\n\n" << kind << " " << (errors?"FAILED":"PASSED") ); return (errors?1:0); } } /////////////////////////////////////////////////////////////////////////////// // Copyright 2018 Doulos Inc. All rights reserved. // Licensed under Apache 2.0 - see accompanying LICENSE FILE. // -*- C++ -*- vim:sw=2:tw=0:fdm=marker:fmr=<<<,>>> //END main.cpp $Id$ >>>}
34.515152
109
0.622476
dcblack
3059d86d26b2f84cc68e6aa312b1dc00d3aedaf5
290
cpp
C++
Codeforces/Codeforces Round #509/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
Codeforces/Codeforces Round #509/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
Codeforces/Codeforces Round #509/A.cpp
itsmevanessi/Competitive-Programming
e14208c0e0943d0dec90757368f5158bb9c4bc17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(void){ int n; cin >> n; int arr[n]; for(int i = 0; i < n; ++i){ cin >> arr[i]; } sort(arr, arr + n); int ans = 0; for(int i = 1; i < n; ++i){ ans += (arr[i] - arr[i - 1] - 1); } cout << ans; }
16.111111
39
0.434483
itsmevanessi
305d66b8d22288ebdea375048bea1bd845799096
15,879
hpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/platform/driver/lcd/LCD1bpp.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
3
2019-12-30T21:16:50.000Z
2021-05-11T05:28:25.000Z
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/platform/driver/lcd/LCD1bpp.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
1
2020-11-14T16:53:09.000Z
2020-11-14T16:53:09.000Z
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/platform/driver/lcd/LCD1bpp.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
3
2020-03-15T14:35:38.000Z
2021-04-07T14:55:42.000Z
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef LCD1BPP_HPP #define LCD1BPP_HPP #include <touchgfx/hal/Types.hpp> #include <touchgfx/hal/HAL.hpp> #include <touchgfx/lcd/LCD.hpp> #include <touchgfx/Font.hpp> #include <touchgfx/Bitmap.hpp> #include <touchgfx/Unicode.hpp> #include <touchgfx/TextProvider.hpp> #include <stdarg.h> namespace touchgfx { #undef LCD /** * @class LCD1bpp LCD1bpp.hpp platform/driver/lcd/LCD1bpp.hpp * * @brief This class contains the various low-level drawing routines for drawing bitmaps, texts and * rectangles. * * This class contains the various low-level drawing routines for drawing bitmaps, texts * and rectangles on 1 bits per pixel displays. * * @note All coordinates are expected to be in absolute coordinates! * * @see LCD */ class LCD1bpp : public LCD { public: virtual ~LCD1bpp() {} /** * @fn virtual void LCD1bpp::drawPartialBitmap(const Bitmap& bitmap, int16_t x, int16_t y, const Rect& rect, uint8_t alpha = 255, bool useOptimized = true); * * @brief Draws a portion of a bitmap. * * Draws a portion of a bitmap. * * @param bitmap The bitmap to draw. * @param x The absolute x coordinate to place pixel (0, 0) on the screen. * @param y The absolute y coordinate to place pixel (0, 0) on the screen. * @param rect A rectangle describing what region of the bitmap is to be drawn. * @param alpha Optional alpha value (0 = invisible, otherwise solid). Default is 255 * (solid). * @param useOptimized if false, do not attempt to substitute (parts of) this bitmap with * faster fillrects. */ virtual void drawPartialBitmap(const Bitmap& bitmap, int16_t x, int16_t y, const Rect& rect, uint8_t alpha = 255, bool useOptimized = true); /** * @fn virtual void LCD1bpp::blitCopy(const uint16_t* sourceData, const Rect& source, const Rect& blitRect, uint8_t alpha, bool hasTransparentPixels); * * @brief Blits a 2D source-array to the frame buffer. * * Blits a 2D source-array to the frame buffer unless alpha is zero. * * @param sourceData The source-array pointer (points to the beginning of the * data). The sourceData must be stored as 16-bits RGB565 * values. * @param source The location and dimension of the source. * @param blitRect A rectangle describing what region is to be drawn. * @param alpha The alpha value to use for blending (0 = invisible, otherwise * solid). * @param hasTransparentPixels If true, this data copy contains transparent pixels and * require hardware support for that to be enabled. */ virtual void blitCopy(const uint16_t* sourceData, const Rect& source, const Rect& blitRect, uint8_t alpha, bool hasTransparentPixels); /** * @fn virtual void LCD1bpp::blitCopy(const uint8_t* sourceData, Bitmap::BitmapFormat sourceFormat, const Rect& source, const Rect& blitRect, uint8_t alpha, bool hasTransparentPixels); * * @brief Blits a 2D source-array to the framebuffer while converting the format. * * Blits a 2D source-array to the framebuffer perfoming alpha-blending (and * tranparency keying) as specified. Performs a software blend if HAL does not * support BLIT_COPY_WITH_ALPHA and alpha != 255. * * @param sourceData The source-array pointer (points to the beginning of the * data). The sourceData must be stored in a format suitable for * the selected display. * @param sourceFormat The bitmap format used in the source data. * @param source The location and dimension of the source. * @param blitRect A rectangle describing what region is to be drawn. * @param alpha The alpha value to use for blending (255 = solid, no blending) * @param hasTransparentPixels Ignored */ virtual void blitCopy(const uint8_t* sourceData, Bitmap::BitmapFormat sourceFormat, const Rect& source, const Rect& blitRect, uint8_t alpha, bool hasTransparentPixels); /** * @fn virtual uint16_t* LCD1bpp::copyFrameBufferRegionToMemory(const Rect& region, const BitmapId bitmap = BITMAP_ANIMATION_STORAGE) = 0; * * @brief Copies a part of the frame buffer. * * Copies a part of the frame buffer to a bitmap. * * @param region The part to copy. * @param bitmap The bitmap to store the data in. Default value is Animation Storage. * * @return A pointer to the copy. * */ virtual uint16_t* copyFrameBufferRegionToMemory(const Rect& region, const BitmapId bitmap = BITMAP_ANIMATION_STORAGE); /** * @fn virtual void LCD1bpp::fillRect(const Rect& rect, colortype color, uint8_t alpha = 255); * * @brief Draws a filled rectangle in the specified color. * * Draws a filled rectangle in the specified color. * * @param rect The rectangle to draw in absolute coordinates. * @param color The rectangle color (values other than 0 or 1 are treated as being 1). * @param alpha The rectangle opacity (0 = invisible, otherwise solid). Default is 255 * (solid). */ virtual void fillRect(const Rect& rect, colortype color, uint8_t alpha = 255); /** * @fn virtual uint8_t LCD1bpp::bitDepth() const * * @brief Number of bits per pixel used by the display. * * Number of bits per pixel used by the display. * * @return 1. */ virtual uint8_t bitDepth() const { return 1; } protected: /** * @fn virtual void LCD1bpp::drawTextureMapScanLine(const DrawingSurface& dest, const Gradients& gradients, const Edge* leftEdge, const Edge* rightEdge, const TextureSurface& texture, const Rect& absoluteRect, const Rect& dirtyAreaAbsolute, RenderingVariant renderVariant, uint8_t alpha, uint16_t subDivisionSize) * * @brief Draw scan line. Not supported for 1bpp. * * @param dest The description of where the texture is drawn - can be used to * issue a draw off screen. * @param gradients The gradients using in interpolation across the scan line. * @param leftEdge The left edge of the scan line. * @param rightEdge The right edge of the scan line. * @param texture The texture. * @param absoluteRect The containing rectangle in absolute coordinates. * @param dirtyAreaAbsolute The dirty area in absolute coordinates. * @param renderVariant The render variant - includes the algorithm and the pixel format. * @param alpha The alpha. * @param subDivisionSize The size of the subdivisions of the scan line. A value of 1 will * give a completely perspective correct texture mapped scan line. A * large value will give an affine texture mapped scan line. */ virtual void drawTextureMapScanLine(const DrawingSurface& dest, const Gradients& gradients, const Edge* leftEdge, const Edge* rightEdge, const TextureSurface& texture, const Rect& absoluteRect, const Rect& dirtyAreaAbsolute, RenderingVariant renderVariant, uint8_t alpha, uint16_t subDivisionSize) { assert(0 && "Texture mapping not supported for 1bpp"); } /** * @fn static int LCD1bpp::nextPixel(bool portrait, TextRotation rotation); * * @brief Find out how much to advance in the display buffer to get to the next pixel. * * Find out how much to advance in the display buffer to get to the next pixel. * * @param portrait Is the display running in portrait mode? * @param rotation Rotation to perform. * * @return How much to advance to get to the next pixel. */ static int nextPixel(bool portrait, TextRotation rotation); /** * @fn static int LCD1bpp::nextLine(bool portrait, TextRotation rotation); * * @brief Find out how much to advance in the display buffer to get to the next line. * * Find out how much to advance in the display buffer to get to the next line. * * @param portrait Is the display running in portrait mode? * @param rotation Rotation to perform. * * @return How much to advance to get to the next line. */ static int nextLine(bool portrait, TextRotation rotation); /** * @fn virtual void LCD1bpp::drawGlyph(uint16_t* wbuf, Rect widgetArea, int16_t x, int16_t y, uint16_t offsetX, uint16_t offsetY, const Rect& invalidatedArea, const GlyphNode* glyph, const uint8_t* glyphData, colortype color, uint8_t bitsPerPixel, uint8_t alpha, TextRotation rotation = TEXT_ROTATE_0); * * @brief Private version of draw-glyph with explicit destination buffer pointer argument. * * Private version of draw-glyph with explicit destination buffer pointer argument. * For all parameters (except the buffer pointer) see the public version of * drawGlyph() * * @param [in] wbuf The destination (frame) buffer to draw to. * @param widgetArea The canvas to draw the glyph inside. * @param x Horizontal offset to start drawing the glyph. * @param y Vertical offset to start drawing the glyph. * @param offsetX Horizontal offset in the glyph to start drawing from. * @param offsetY Vertical offset in the glyph to start drawing from. * @param invalidatedArea The area to draw within. * @param glyph Specifications of the glyph to draw. * @param glyphData Data containing the actual glyph (dense format) * @param color The color of the glyph. * @param bitsPerPixel Bit depth of the glyph. * @param alpha The transparency of the glyph. * @param rotation Rotation to do before drawing the glyph. */ virtual void drawGlyph(uint16_t* wbuf, Rect widgetArea, int16_t x, int16_t y, uint16_t offsetX, uint16_t offsetY, const Rect& invalidatedArea, const GlyphNode* glyph, const uint8_t* glyphData, colortype color, uint8_t bitsPerPixel, uint8_t alpha, TextRotation rotation = TEXT_ROTATE_0); /** * @fn static void LCD1bpp::fillMemory(void* RESTRICT dst, colortype color, uint16_t bytesToFill); * * @brief Fill memory efficiently. * * Fill memory efficiently. Try to get 32bit aligned or 16bit aligned and then copy * as quickly as possible. * * @param [out] dst Pointer to memory to fill. * @param color Color to write to memory, either 0 => 0x00000000 or 1 => 0xFFFFFFFF. * @param bytesToFill Number of bytes to fill. */ static void fillMemory(void* RESTRICT dst, colortype color, uint16_t bytesToFill); /** * @fn virtual void LCD1bpp::blitCopyRLE(const uint16_t* _sourceData, const Rect& source, const Rect& blitRect, uint8_t alpha); * * @brief Blits a run-length encoded 2D source-array to the frame buffer. * * Blits a run-length encoded2D source-array to the frame buffer unless alpha is * zero. * * @param _sourceData The source-array pointer (points to the beginning of the data). Data * stored in RLE format, where each byte indicates number of pixels with * certain color, alternating between black and white. First byte * represents black. * @param source The location and dimension of the source. * @param blitRect A rectangle describing what region is to be drawn. * @param alpha The alpha value to use for blending (0 = invisible, otherwise solid). */ virtual void blitCopyRLE(const uint16_t* _sourceData, const Rect& source, const Rect& blitRect, uint8_t alpha); private: class bwRLEdata { public: bwRLEdata(const uint8_t* src = 0) : data(src), rleByte(0), firstHalfByte(true), color(0) { init(src); } void init(const uint8_t* src) { data = src; rleByte = 0; firstHalfByte = true; color = 0; if (src != 0) { // Read two half-bytes ahead thisHalfByte = getNextHalfByte(); nextHalfByte = getNextHalfByte(); length = getNextLength(); } } uint32_t getNextLength() { uint32_t length = thisHalfByte; // Length is the next byte // update read ahead buffer thisHalfByte = nextHalfByte; nextHalfByte = getNextHalfByte(); // If number after 'length' is 0 while (thisHalfByte == 0) { length <<= 4; // Multiply length by 16 and length += nextHalfByte; // add the number after 0 // We have used the next two half bytes, read two new ones thisHalfByte = getNextHalfByte(); nextHalfByte = getNextHalfByte(); } return length; } void skipNext(uint32_t skip) { while (skip > 0) // Are there more pixels to skip? { if (length > skip) // is the current length enough? { length -= skip; // Reduce the length skip = 0; // No more to skip } else { skip -= length; // Skip the entire run length = getNextLength(); // Read length of next run color = ~color; // Update the color of next run } } } uint8_t getColor() const { return color; } uint32_t getLength() const { return length; } private: uint8_t getNextHalfByte() { if (firstHalfByte) // Start of new byte, read data from BW_RLE stream { rleByte = *data++; } uint8_t length = rleByte & 0xF; // Read lower half rleByte >>= 4; // Shift upper half down to make it ready firstHalfByte = !firstHalfByte; // Toggle 'start of byte' return length; } const uint8_t* data; // Pointer to compressed data (BW_RLE) uint8_t thisHalfByte; // The next half byte from the input uint8_t nextHalfByte; // The next half byte after 'thisHalfByte' uint8_t rleByte; // Byte read from compressed data bool firstHalfByte; // Are we about to process first half byte of rleByte? uint8_t color; // Current color uint32_t length; // Number of pixels with the given color }; friend class PainterBWBitmap; }; } // namespace touchgfx #endif // LCD1BPP_HPP
45.368571
317
0.613704
ramkumarkoppu
306a95807ecf337a98c822c9ed5ee071ce31aa0c
843
cpp
C++
bzoj/3674.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/3674.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/3674.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #include <ext/rope> using namespace std; using namespace __gnu_cxx; rope<int> *rp[200010]; int n, m, a[200100], f, x, y, lastans; int find(int i, int x){ int fa = rp[i] -> at(x); if(fa==x) return x; int f = find(i, fa); if(f==fa) return f; rp[i] -> replace(x, f); return f; } int main(){ scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) a[i] = i; rp[0] = new rope<int>(a, a+n+1); for(int i = 1; i <= m; i++){ rp[i] = new rope<int>(*rp[i-1]); scanf("%d", &f); if(f == 1){ scanf("%d%d", &x, &y); x^=lastans, y^=lastans; x = find(i,x); y = find(i,y); if(x != y) rp[i] -> replace(y, x); } else if(f == 2){ scanf("%d", &x); x^=lastans; rp[i] = rp[x]; } else{ scanf("%d%d", &x, &y); x^=lastans, y^=lastans; printf("%d\n", lastans=find(i,x)==find(i,y)); } } }
20.560976
48
0.489917
swwind
306b30bb72a958ad546946b6cf58cb8271439611
855
cpp
C++
202203/0303_reversePrint.cpp
talentwill/CardCoding
1fcd20f3a76cec85845552a8917847971d9aeeb1
[ "MIT" ]
null
null
null
202203/0303_reversePrint.cpp
talentwill/CardCoding
1fcd20f3a76cec85845552a8917847971d9aeeb1
[ "MIT" ]
null
null
null
202203/0303_reversePrint.cpp
talentwill/CardCoding
1fcd20f3a76cec85845552a8917847971d9aeeb1
[ "MIT" ]
1
2022-03-10T05:28:19.000Z
2022-03-10T05:28:19.000Z
// 剑指 Offer 06. 从尾到头打印链表 // 22/02/13 堆栈缓存 class Solution { public: vector<int> reversePrint(ListNode* head) { auto node = head; std::stack<ListNode*> nodes; while(node != nullptr) { nodes.push(node); node = node->next; } vector<int> result; while(!nodes.empty()) { node = nodes.top(); result.emplace_back(node->val); nodes.pop(); } return result; } }; // 21/12/25 递归输出 struct Solution { std::vector<int> results; void addNode(ListNode *node) { if (node !=nullptr) { addNode(node->next); results.emplace_back(node->val); } } std::vector<int> reversePrint(ListNode *head) { addNode(head); return results; } };
17.8125
49
0.491228
talentwill
306ddb38058244ed0fe5b7304fae0eb339769105
1,189
hpp
C++
src/lattices/square/nearest_neighbor.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
1
2019-09-25T05:35:07.000Z
2019-09-25T05:35:07.000Z
src/lattices/square/nearest_neighbor.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
null
null
null
src/lattices/square/nearest_neighbor.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
null
null
null
#ifndef LATTICES_SQUARE_NEAREST_NEIGHBOR_HPP #define LATTICES_SQUARE_NEAREST_NEIGHBOR_HPP #include "lattice.hpp" #include "offset.hpp" #include <type_traits> namespace lattices { namespace square { template <typename S> struct NearestNeighborCat { typedef S VSize; typedef LatticeCat<VSize> LatticeCat; typedef typename LatticeCat::Lattice Lattice; typedef typename LatticeCat::Vertex Vertex; typedef typename LatticeCat::Vid Vid; typedef OffsetCat<VSize> OffsetCat; typedef typename OffsetCat::Offset Offset; typedef std::integral_constant<unsigned char, 4> coordinationNumber; static const Offset neighborOffsets[] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; static Vertex neighbor(const Vertex& v0, unsigned char i, const Lattice& lattice) { Vertex v1 = v0; OffsetCat::shift(v1, neighborOffsets[i], lattice); return v1; } static Vid neighbor(Vid v0, unsigned char i, const Lattice& lattice) { Vertex vv0 = LatticeCat::vertex(v0, lattice); Vertex v1 = neighbor(vv0, i, lattice); return LatticeCat::vid(v1, lattice); } }; } } #endif
25.847826
63
0.667788
yangqi137
306ec46656b4c6406ef6831c00292ad852cb4c87
704
hpp
C++
Jabbo/Source/BuildOrderManager.hpp
Jabbo16/Jabbo
8f662610967e7393662df5ce979898be02679b1e
[ "MIT" ]
4
2018-07-21T06:06:26.000Z
2020-01-26T14:46:36.000Z
Jabbo/Source/BuildOrderManager.hpp
Jabbo16/Jabbo
8f662610967e7393662df5ce979898be02679b1e
[ "MIT" ]
null
null
null
Jabbo/Source/BuildOrderManager.hpp
Jabbo16/Jabbo
8f662610967e7393662df5ce979898be02679b1e
[ "MIT" ]
null
null
null
#pragma once #include <BWAPI.h> #include <vector> #include <string> #include <variant> using namespace BWAPI; using namespace std; enum buildingPlacement { Default, Proxy, Hidden }; enum wallPlacement { Main, Natural }; struct BOItem { int supply{}; variant<UnitType, TechType, UpgradeType> type; int amount = 1; buildingPlacement placement = Default; }; struct BuildOrder { vector<BOItem> itemsBO; string name; Race myRace; Race enemyRace; wallPlacement wallPlacement = Main; }; class BuildOrderManager { public: BuildOrderManager(); static BuildOrderManager& instance(); BuildOrder myBo; void bioBuild(); void bbs(); void onStart(); };
16
48
0.690341
Jabbo16
30756379820fbd7d3358e9ca2fb67f931a6ba3b9
4,020
hpp
C++
sdk/include/xuxml.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/xuxml.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/xuxml.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
#pragma once namespace Hxsoft{ namespace XUtil { namespace Xml { template <class Ch> inline bool IsSpaceLetter(Ch ch) { return ch==' '||ch=='\t'||ch=='\r'||ch=='n'; } template <class Ch> inline bool IsDigits(Ch ch) { return ch>='0' && ch<='9'; } template <class Ch> bool IsIdentLetter(Ch ch) { return ch >= 0x100 ||(ch >='a' && ch <='z') ||(ch >='A' && ch <='Z') || (ch=='_' || ch=='$'); } template <class Ch> inline const Ch* SkipSpace(const Ch * xmlText) { while(IsSpaceLetter(*xmlText))xmlText++; return xmlText; } template <class Ch> const Ch* SkipComment(const Ch* xmlText) { while(*xmlText) { if(xmlText[0]=='-'||xmlText[1]=='-'||xmlText[2]=='>') { xmlText+=3; break; } xmlText++; } return xmlText; } template <class Ch> const Ch* SkipPI(const Ch* xmlText) { if(xmlText[0]=='<' && xmlText[1]=='?') { xmlText +=2; }else return xmlText; while(*++xmlText) { if(xmlText[0]=='?' && xmlText[1]=='>') { xmlText+=2; break; } xmlText++; } return xmlText; } //only eat text content template <class Ch> const Ch* SkipElementContent(const Ch* xmlText) { xmlText = SkipSpace(xmlText); while(*xmlText) { if(*xmlText=='<') { //skip pcdata if(xmlText[1]=='!' && xmlText[2]=='[' && xmlText[3]=='C' && xmlText[4]=='D' && xmlText[5]=='A' && xmlText[6]=='T' && xmlText[7]=='A' && xmlText[8]=='[') { xmlText += 9; while(*xmlText) { if(xmlText[0]==']' && xmlText[1]==']' && xmlText[2]=='>') { xmlText += 3; break; } xmlText++; } }else break; } else break; } return xmlText; } //skip attribute, child element node, child content node template <class Ch> const Ch* SkipElement(const Ch * xmlText) { //skip element head while(*xmlText) { if(*xmlText=='>')break; if(*xmlText=='/') { *xmlText++; xmlText = SkipSpace(xmlText); if(*xmlText=='>') { //found element tail return ++xmlText; } } xmlText++; } if(!xmlText) return xmlText; while(*xmlText) { //skip content xmlText = SkipElementContent(xmlText); if(*xmlText=='<') { //skip comment if(xmlText[1]=='!' && xmlText[2]=='-' && xmlText[3]=='-') xmlText = SkipComment(xmlText); else { xmlText = SkipSpace(xmlText + 1); //skip element tail then exit if(*xmlText=='/') { while(*++xmlText != '>'); if(*xmlText)xmlText++; break; }else xmlText = SkipElement(xmlText); } } else xmlText++; } return xmlText; } template <class Ch> const Ch * FirstChildElement(const Ch * xmlText ,bool skipOwnerHead ) { //skip ownwe head if(skipOwnerHead) { while(*xmlText) { if(*xmlText=='>')break; if(*xmlText=='/') { *xmlText++; xmlText = SkipSpace(xmlText); if(*xmlText=='>') { //found element tail ,then none child element return NULL; } } xmlText++; } } if(!xmlText) return xmlText; while(*xmlText) { //skip content xmlText = SkipElementContent(xmlText); if(*xmlText=='<') { //skip comment if(xmlText[1]=='!' && xmlText[2]=='-' && xmlText[3]=='-') xmlText = SkipComment(xmlText); else { //meet element tail no child element if(SkipSpace(xmlText + 1)[0]=='/') return NULL; //found return xmlText; } } xmlText++; } return xmlText; } template <class Ch > const Ch * NextSblingElement(const Ch * xmlText) { xmlText = SkipElement(xmlText); while(*xmlText) { //skip content xmlText = SkipElementContent(xmlText); if(*xmlText=='<') { //skip comment if(xmlText[1]=='!' && xmlText[2]=='-' && xmlText[3]=='-') xmlText = SkipComment(xmlText); else { //meet element tail no child element if(SkipSpace(xmlText + 1)[0]=='/') return NULL; //found return xmlText; } } xmlText++; } return xmlText; } }}}
18.611111
96
0.54005
qianxj
3076fab8c07f64957ca32495ece5e907408b0f08
1,149
cpp
C++
ArcDelay/Performance_Process.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ArcDelay/Performance_Process.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ArcDelay/Performance_Process.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Performance_Process.cpp - read the link delay file //********************************************************* #include "ArcDelay.hpp" #include "In_Polygon.hpp" //--------------------------------------------------------- // Performance_Processing //--------------------------------------------------------- bool ArcDelay::Performance_Processing (Db_File *fh) { //---- check the subarea polygon ---- if (subarea_flag) { Delay_File *file = (Delay_File *) fh; if (!file->Nest ()) { int link; Node_Data *node_ptr; Link_Data *link_ptr; link = file->Link (); if (link < 0) link = -link; link_ptr = link_data.Get (link); if (link_ptr == NULL) return (false); node_ptr = node_data.Get (link_ptr->Anode ()); if (!In_Polygon (UnRound (node_ptr->X ()), UnRound (node_ptr->Y ()), &select_subarea.points)) { node_ptr = node_data.Get (link_ptr->Bnode ()); if (!In_Polygon (UnRound (node_ptr->X ()), UnRound (node_ptr->Y ()), &select_subarea.points)) { return (false); } } } } return (Demand_Service::Performance_Processing (fh)); }
26.113636
99
0.507398
kravitz
30779f2c0de78d888d3427a2895c7ce1f734c7fe
469
cpp
C++
example/e-HelloWorld.cpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
3
2021-12-07T06:16:31.000Z
2021-12-22T14:12:36.000Z
example/e-HelloWorld.cpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
null
null
null
example/e-HelloWorld.cpp
iboB/jalog
d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9
[ "MIT" ]
null
null
null
// jalog // Copyright (c) 2021-2022 Borislav Stanimirov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #include <jalog/Instance.hpp> #include <jalog/sinks/ColorSink.hpp> #include <jalog/Log.hpp> int main() { jalog::Instance jl; jl.setup().add<jalog::sinks::ColorSink>(); JALOG(Debug, "Perparing to greet world"); JALOG(Info, "Hello, world"); return 0; }
21.318182
47
0.686567
iboB
307ea48b058298277076e114728a8fc64378239c
739
cpp
C++
epikjjh/baekjoon/11403.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
3
2019-05-19T13:44:39.000Z
2019-07-03T11:15:20.000Z
epikjjh/baekjoon/11403.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
7
2019-05-06T02:37:26.000Z
2019-06-29T07:28:02.000Z
epikjjh/baekjoon/11403.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
1
2019-07-28T06:24:54.000Z
2019-07-28T06:24:54.000Z
#include <bits/stdc++.h> using namespace std; int n; vector<vector<int> > adj; vector<vector<int> > ret; vector<bool> visited; void dfs(int cur){ visited[cur] = true; for(int nxt: adj[cur]) if(!visited[nxt]) dfs(nxt); } int con(int s, int e){ for(int t: adj[s]){ if(!visited[t]) dfs(t); } if(visited[e]) return 1; else return 0; } int main(){ int t; cin >> n; adj.resize(n); ret.resize(n); visited.resize(n); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin >> t; if(t) adj[i].push_back(j); } } for(int i=0;i<n;i++) sort(adj[i].begin(),adj[i].end()); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout << con(i,j) << " "; fill(visited.begin(),visited.end(),false); } cout << endl; } return 0; }
16.065217
56
0.564276
15ers
307eb5edd09f583a865100f709b6026b08818399
745
hpp
C++
include/flx/flx.hpp
jfalcou/fluxion
7b845d2b5e0b97754ce09bd2bfca1f45913ea8df
[ "MIT" ]
null
null
null
include/flx/flx.hpp
jfalcou/fluxion
7b845d2b5e0b97754ce09bd2bfca1f45913ea8df
[ "MIT" ]
null
null
null
include/flx/flx.hpp
jfalcou/fluxion
7b845d2b5e0b97754ce09bd2bfca1f45913ea8df
[ "MIT" ]
null
null
null
//================================================================================================== /* Fluxion - Post-Modern Automatic Derivation Copyright : Fluxion Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once //================================================================================================== //! @namespace flx //! @brief Main fluxion namespace //================================================================================================== namespace flx { } #include <flx/analytic/analytic.hpp> #include <flx/derivative/derivative.hpp> #include <flx/differential/differential.hpp>
33.863636
100
0.344966
jfalcou
3089698fce6dc5838f443d759b46695153e8fa72
3,679
cpp
C++
src/game/shared/hl2mp/weapons/weapon_357.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/hl2mp/weapons/weapon_357.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/hl2mp/weapons/weapon_357.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
 //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "npcevent.h" #include "in_buttons.h" #ifdef CLIENT_DLL #include "c_hl2mp_player.h" #else #include "hl2mp_player.h" #endif #include "weapon_hl2mpbasehlmpcombatweapon.h" #ifdef CLIENT_DLL #define CWeapon357 C_Weapon357 #endif //----------------------------------------------------------------------------- // CWeapon357 //----------------------------------------------------------------------------- class CWeapon357 : public CBaseHL2MPCombatWeapon { DECLARE_CLASS(CWeapon357, CBaseHL2MPCombatWeapon); public: CWeapon357(void); void PrimaryAttack(void); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); #ifndef CLIENT_DLL DECLARE_ACTTABLE(); #endif private: CWeapon357(const CWeapon357 &); }; IMPLEMENT_NETWORKCLASS_ALIASED(Weapon357, DT_Weapon357) BEGIN_NETWORK_TABLE(CWeapon357, DT_Weapon357) END_NETWORK_TABLE () BEGIN_PREDICTION_DATA(CWeapon357) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS(weapon_357, CWeapon357); PRECACHE_WEAPON_REGISTER(weapon_357); #ifndef CLIENT_DLL acttable_t CWeapon357::m_acttable[] = { { ACT_HL2MP_IDLE, ACT_HL2MP_IDLE_PISTOL, false }, { ACT_HL2MP_RUN, ACT_HL2MP_RUN_PISTOL, false }, { ACT_HL2MP_IDLE_CROUCH, ACT_HL2MP_IDLE_CROUCH_PISTOL, false }, { ACT_HL2MP_WALK_CROUCH, ACT_HL2MP_WALK_CROUCH_PISTOL, false }, { ACT_HL2MP_GESTURE_RANGE_ATTACK, ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL, false }, { ACT_HL2MP_GESTURE_RELOAD, ACT_HL2MP_GESTURE_RELOAD_PISTOL, false }, { ACT_HL2MP_JUMP, ACT_HL2MP_JUMP_PISTOL, false }, { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_PISTOL, false }, }; IMPLEMENT_ACTTABLE( CWeapon357 ); #endif //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CWeapon357::CWeapon357(void) { m_bReloadsSingly = false; m_bFiresUnderwater = false; } void CWeapon357::PrimaryAttack(void) { // Only the player fires this way so we can cast CBasePlayer *pPlayer = ToBasePlayer(GetOwner()); if (!pPlayer) { return; } if (m_iClip1 <= 0) { if (!m_bFireOnEmpty) { Reload(); } else { WeaponSound(EMPTY); m_flNextPrimaryAttack = 0.15; } return; } WeaponSound(SINGLE); pPlayer->DoMuzzleFlash(); SendWeaponAnim(ACT_VM_PRIMARYATTACK); pPlayer->SetAnimation(PLAYER_ATTACK1); m_flNextPrimaryAttack = gpGlobals->curtime + 0.75; m_flNextSecondaryAttack = gpGlobals->curtime + 0.75; m_iClip1--; Vector vecSrc = pPlayer->Weapon_ShootPosition(); Vector vecAiming = pPlayer->GetAutoaimVector(AUTOAIM_5DEGREES); FireBulletsInfo_t info(1, vecSrc, vecAiming, vec3_origin, MAX_TRACE_LENGTH, m_iPrimaryAmmoType); info.m_pAttacker = pPlayer; // Fire the bullets, and force the first shot to be perfectly accuracy pPlayer->FireBullets(info); //Disorient the player QAngle angles = pPlayer->GetLocalAngles(); angles.x += random->RandomInt(-1, 1); angles.y += random->RandomInt(-1, 1); angles.z = 0; #ifndef CLIENT_DLL pPlayer->SnapEyeAngles( angles ); #endif pPlayer->ViewPunch(QAngle(-8, random->RandomFloat(-2, 2), 0)); if (!m_iClip1 && pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0) { // HEV suit - indicate out of ammo condition pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0); } }
25.19863
100
0.619734
cstom4994
30958c0c05dc3d5c78ded364a3c62eddf821149f
6,551
cpp
C++
src/escposprinter.cpp
ceciletti/escpos-qt
682017930ae99cc96c16fc050fb4e88a0f4b2c57
[ "MIT" ]
8
2020-05-09T19:52:54.000Z
2021-09-02T03:41:46.000Z
src/escposprinter.cpp
ceciletti/escpos-qt
682017930ae99cc96c16fc050fb4e88a0f4b2c57
[ "MIT" ]
1
2020-10-05T08:03:46.000Z
2021-03-25T00:15:02.000Z
src/escposprinter.cpp
ceciletti/escpos-qt
682017930ae99cc96c16fc050fb4e88a0f4b2c57
[ "MIT" ]
4
2020-05-09T19:53:00.000Z
2022-03-21T01:51:46.000Z
#include "escposprinter.h" #include <QIODevice> #include <QDataStream> #include <QLoggingCategory> #include <QTextCodec> Q_LOGGING_CATEGORY(EPP, "esc_pos") static const char ESC = 0x1B; static const char GS = 0x1D; EscPosPrinter::EscPosPrinter(QIODevice *device, QObject *parent) : QObject(parent) , m_device(device) { m_codec = QTextCodec::codecForLocale(); connect(m_device, &QIODevice::readyRead, this, [=] { const QByteArray data = m_device->readAll(); qCDebug(EPP) << "GOT" << data << data.toHex(); }); } EscPosPrinter::EscPosPrinter(QIODevice *device, const QByteArray &codecName, QObject *parent) : QObject(parent) , m_device(device) { m_codec = QTextCodec::codecForName(codecName); connect(m_device, &QIODevice::readyRead, this, [=] { const QByteArray data = m_device->readAll(); qCDebug(EPP) << "GOT" << data << data.toHex(); }); } EscPosPrinter &EscPosPrinter::operator<<(PrintModes i) { return mode(i); } EscPosPrinter &EscPosPrinter::operator<<(EscPosPrinter::Justification i) { return align(i); } EscPosPrinter &EscPosPrinter::operator<<(EscPosPrinter::Encoding i) { return encode(i); } EscPosPrinter &EscPosPrinter::operator<<(EscPosPrinter::_feed lines) { return paperFeed(lines._lines); } EscPosPrinter &EscPosPrinter::operator<<(const char *s) { return raw(s); } EscPosPrinter &EscPosPrinter::operator<<(const QByteArray &s) { return raw(s); } EscPosPrinter &EscPosPrinter::operator<<(const EscPosPrinter::QRCode &qr) { write(qr.data); return *this; } EscPosPrinter &EscPosPrinter::operator<<(const QString &s) { return text(s); } EscPosPrinter &EscPosPrinter::operator<<(void (*pf)()) { if (pf == EscPosPrinter::eol) { write("\n", 1); } else if (pf == EscPosPrinter::init) { return initialize(); } else if (pf == EscPosPrinter::standardMode) { return modeStandard(); } else if (pf == EscPosPrinter::pageMode) { return modePage(); } return *this; } void EscPosPrinter::debug() { qCDebug(EPP) << "DEBUG" << m_buffer; } void EscPosPrinter::write(const QByteArray &data) { m_device->write(data); } void EscPosPrinter::write(const char *data, int size) { m_device->write(data, size); } EscPosPrinter &EscPosPrinter::initialize() { const char str[] = { ESC, '@'}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::encode(EscPosPrinter::Encoding codec) { switch (codec) { case EncodingPC850: m_codec = QTextCodec::codecForName("IBM 850"); break; case EncodingPC866: m_codec = QTextCodec::codecForName("IBM 866"); break; case EncodingISO8859_2: m_codec = QTextCodec::codecForName("ISO8859-2"); break; case EncodingISO8859_15: m_codec = QTextCodec::codecForName("ISO8859-15"); break; default: m_codec = nullptr; } if (!m_codec) { qCWarning(EPP) << "Could not find a Qt Codec for" << codec; } const char str[] = { ESC, 't', char(codec)}; qCDebug(EPP) << "encoding" << codec << QByteArray(str, sizeof(str)).toHex() << m_codec; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::mode(EscPosPrinter::PrintModes pm) { qCDebug(EPP) << "print modes" << pm; const char str[] = { ESC, '!', char(pm)}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::modeStandard() { const char str[] = { ESC, 'L'}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::modePage() { const char str[] = { ESC, 'S'}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::partialCut() { const char str[] = { ESC, 'm'}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::printAndFeedPaper(quint8 n) { const char str[] = { ESC, 'J', char(n)}; write(str, sizeof(str)); return *this; } EscPosPrinter &EscPosPrinter::align(EscPosPrinter::Justification i) { const char str[] = { ESC, 'a', char(i)}; qCDebug(EPP) << "justification" << i << QByteArray(str, 3).toHex(); write(str, 3);// TODO doesn't work on DR700 return *this; } EscPosPrinter &EscPosPrinter::paperFeed(int lines) { const char str[] = { ESC, 'd', char(lines)}; qCDebug(EPP) << "line feeds" << lines << QByteArray(str, 3).toHex(); write(str, 3); return *this; } EscPosPrinter &EscPosPrinter::text(const QString &text) { qCDebug(EPP) << "string" << text << text.toLatin1() << m_codec->fromUnicode(text); if (m_codec) { write(m_codec->fromUnicode(text)); } else { write(text.toLatin1()); } return *this; } EscPosPrinter &EscPosPrinter::raw(const QByteArray &data) { qCDebug(EPP) << "bytearray" << data; write(data); return *this; } EscPosPrinter &EscPosPrinter::raw(const char *s) { qCDebug(EPP) << "char *s" << QByteArray(s); write(s, int(strlen(s))); return *this; } EscPosPrinter &EscPosPrinter::raw(const char *s, int size) { qCDebug(EPP) << "char *s" << QByteArray(s) << size; write(s, size); return *this; } EscPosPrinter &EscPosPrinter::qr(const EscPosPrinter::QRCode &code) { write(code.data); return *this; } void EscPosPrinter::getStatus() { } EscPosPrinter::QRCode::QRCode(EscPosPrinter::QRCode::Model model, int moduleSize, EscPosPrinter::QRCode::ErrorCorrection erroCorrection, const QByteArray &_data) { qCDebug(EPP) << "QRCode" << model << moduleSize << erroCorrection << _data; // Model f165 // 49 - model1 // 50 - model2 // 51 - micro qr code const char mT[] = { GS, '(', 'k', 0x04, 0x00, 0x31, 0x41, char(model), 0x00}; data.append(mT, sizeof(mT)); // Module Size f167 const char mS[] = { GS, '(', 'k', 0x03, 0x00, 0x31, 0x43, char(moduleSize)}; data.append(mS, sizeof(mS)); // Error Level f169 // L = 0, M = 1, Q = 2, H = 3 const char eL[] = { GS, '(', 'k', 0x03, 0x00, 0x31, 0x45, char(erroCorrection)}; data.append(eL, sizeof(eL)); // truncate data f180 int len = _data.length() + 3;// 3 header bytes if (len > 7092) { len = 7092; } // data header const char dH[] = { GS, '(', 'k', char(len), char(len >> 8), 0x31, 0x50, 0x30}; data.append(dH, sizeof(dH)); data.append(_data.mid(0, 7092)); // Print f181 const char pT[] = { GS, '(', 'k', 0x03, 0x00, 0x31, 0x51, 0x30}; data.append(pT, sizeof(pT)); }
23.564748
161
0.621127
ceciletti
30a021161744cae8c17671562632954559855571
280
cpp
C++
Razor/src/Editor/EditorTool.cpp
0zirix/Razor
b902d316da058caa636efce15da405beb73d9f73
[ "MIT" ]
2
2021-09-25T02:44:02.000Z
2021-10-03T09:37:54.000Z
Razor/src/Editor/EditorTool.cpp
0zirix/Razor
b902d316da058caa636efce15da405beb73d9f73
[ "MIT" ]
null
null
null
Razor/src/Editor/EditorTool.cpp
0zirix/Razor
b902d316da058caa636efce15da405beb73d9f73
[ "MIT" ]
null
null
null
#include "rzpch.h" #include "EditorTool.h" #include "Editor/Editor.h" namespace Razor { EditorTool::EditorTool(Editor* editor) : editor(editor), dirty(true), active(true) { } EditorTool::~EditorTool() { } Editor* EditorTool::getEditor() { return editor; } }
11.666667
42
0.660714
0zirix
dd64e1e4732d38e2e714b1d8ae4a958fd4712d2e
3,477
hpp
C++
include/aikido/io/KinBodyParser.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
include/aikido/io/KinBodyParser.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
include/aikido/io/KinBodyParser.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#ifndef AIKIDO_IO_KINBODYPARSER_HPP_ #define AIKIDO_IO_KINBODYPARSER_HPP_ #include <dart/dart.hpp> namespace aikido { namespace io { /// Read skeleton from a string of OpenRAVE's custom XML format /// /// This function only parses a subset of the format assuming only one body node /// in a kinbody file. /// /// The following are the available fields that this parser can read. /// \code /// kinbody - attributes: name /// body - attributes: name /// geom - attributes: name, type* (none, box, sphere, trimesh, cylinder), /// render /// data* (or collision) - file* scale [for trimesh] (see below for the /// detail) /// extents* - 3 float [for box] /// height* - float [for cylinder] /// radius* - float [for cylinder and sphere] /// render - file* scale (see below for the detail) /// \endcode /// Elements marked with `*` are required. /// /// "<render>", "<data>", or "<collision>" contain the relative path to a mesh /// file /// and optionally a single float (for all three axes) or three float's (for the /// x, y, and z-axes) for the scale. /// /// Example forms: /// "<Render>my/mesh/file.stl<Render>" /// "<Render>my/mesh/file.stl 0.25<Render> <!--scale for all three axes-->" /// "<Render>my/mesh/file.stl 0.25 0.5 2.0<Render>" /// /// If the scale is not provided then (1, 1, 1) is used by default. /// /// The detail of the format can be found at: /// http://openrave.programmingvision.com/wiki/index.php/Format:XML. /// /// \param[in] kinBodyString The KinBody XML string. /// \param[in] baseUri The base URI of the mesh files in the KinBody XML string. /// If an empty URI, which is the default, is passed, the mesh URIs in the /// KinBody XML string should be absolute URIs or paths. /// \param[in] retriever A DART retriever for the mesh URIs in the KinBody XML /// string. If nullptr is passed, this function uses a local file resource /// retriever which only can parse absolute file paths or file URIs /// (e.g., file://path/to/local/file.kinbody.xml). /// \return The parsed DART skeleton; returns nullptr on failure. /// /// \sa readKinbody dart::dynamics::SkeletonPtr readKinbodyString( const std::string& kinBodyString, const dart::common::Uri& baseUri = "", const dart::common::ResourceRetrieverPtr& retriever = nullptr); /// Read skeleton from a file of OpenRAVE's custom XML format /// /// This function only parses a subset of the format assuming only one body node /// in a kinbody file. /// /// The detail of the format can be found at: /// http://openrave.programmingvision.com/wiki/index.php/Format:XML. /// /// \param[in] kinBodyUri The URI to a KinBody file. If the URI scheme is not /// file (i.e., file://), a relevant ResourceRetriever should be passed to /// retrieve the KinBody file. /// \param[in] retriever A DART retriever for the URI to a KinBody. The /// retriever is also used to read the mesh URI in the KinBody file. If nullptr /// is passed, this function uses a local file resource retriever which only can /// parse absolute file paths or file URIs /// (e.g., file://path/to/local/file.kinbody.xml). /// \return The parsed DART skeleton; returns nullptr on failure. /// /// \sa readKinbodyString dart::dynamics::SkeletonPtr readKinbody( const dart::common::Uri& kinBodyUri, const dart::common::ResourceRetrieverPtr& retriever = nullptr); } // namespace io } // namespace aikido #endif // AIKIDO_IO_KINBODYPARSER_HPP_
39.965517
80
0.686511
usc-csci-545
dd6812ee4af2752197b29a1016814df87c82e81f
131
cpp
C++
src/my_imp/tick_handler.cpp
SlausB/fos
75c647da335925fd5e0bb956acc4db895004fc79
[ "MIT" ]
null
null
null
src/my_imp/tick_handler.cpp
SlausB/fos
75c647da335925fd5e0bb956acc4db895004fc79
[ "MIT" ]
null
null
null
src/my_imp/tick_handler.cpp
SlausB/fos
75c647da335925fd5e0bb956acc4db895004fc79
[ "MIT" ]
null
null
null
 #include "handlers.h" using namespace fos; void TickHandler(const double elapsedSeconds, TickTime* tickTime) { }
10.916667
66
0.679389
SlausB
dd6bf4947d17f01a7159921cb97466edefe762d2
1,372
cpp
C++
Algorithms/Bit_manipulation/chef_got_recipies.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
11
2020-03-20T17:24:28.000Z
2022-01-08T02:43:24.000Z
Algorithms/Bit_manipulation/chef_got_recipies.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
1
2021-07-25T11:24:46.000Z
2021-07-25T12:09:25.000Z
Algorithms/Bit_manipulation/chef_got_recipies.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
4
2020-03-20T17:24:36.000Z
2021-12-07T19:22:59.000Z
#include <iostream> #include <cstring> using namespace std; int main() { long long int F[32]; int t, n; string st; cin>>t; while(t--) { cin>>n; for(int i=0; i<32; i++) { F[i] = 0; } for(int i=1; i<=n; i++) { cin>>st; int mask=0; for(char ch : st) { if(ch == 'a') { mask = mask | (1 << 0); } if(ch == 'e') { mask = mask | (1 << 1); } if(ch == 'i') { mask = mask | (1 << 2); } if(ch == 'o') { mask = mask | (1 << 3); } if(ch == 'u') { mask = mask | (1 << 4); } } F[mask] += 1; } long long int result = 0; for(int i=1;i<32;i++) { for(int j=i+1; j<32; j++) { if((i | j) == 31) { result = result + F[i] * F[j]; } } } result = result + (F[31] * (F[31] - 1)) / 2; cout<<result<<endl; } return 0; }
21.107692
52
0.241254
abhishekjha786
dd7497903be0a0c2dccaee8ae188c6a69a890c15
28,715
cpp
C++
src/construction/ConstructionIO.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
3
2021-09-08T07:28:13.000Z
2022-03-02T21:12:40.000Z
src/construction/ConstructionIO.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
1
2021-09-21T14:40:55.000Z
2021-09-26T01:19:38.000Z
src/construction/ConstructionIO.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
null
null
null
// // Created by James Noeckel on 1/23/21. // #include "Construction.h" #include <igl/opengl/glfw/Viewer.h> #include <imgui/imgui.h> #include <igl/opengl/glfw/imgui/ImGuiMenu.h> //#include <igl/opengl/glfw/imgui/ImGuiHelpers.h> #include "utils/colorAtIndex.h" //#include "utils/color_conversion.hpp" #include "utils/macros.h" #include "test/testUtils/curveFitUtils.h" #include <igl/readOBJ.h> #include "geometry/primitives3/Multimesh.h" using namespace Eigen; using namespace boost; void Construction::visualize(double displacement, const std::string &connector_mesh, double spacing, double scale) const { igl::opengl::glfw::Viewer viewer; viewer.data().point_size = 5; viewer.data().show_overlay = true; viewer.data().label_color.head(3) = Vector3f(1, 1, 1); Multimesh cMesh; cMesh.AddMesh(std::make_pair(std::get<0>(mesh), std::get<1>(mesh))); if (!connector_mesh.empty()) { cMesh.AddMesh(connectorMesh(connector_mesh, spacing, scale)); } auto cMeshOut = cMesh.GetTotalMesh(); MatrixX3d C = MatrixX3d::Ones(cMeshOut.second.rows(), 3) * 0.5; for (size_t i=0; i<std::get<1>(mesh).rows(); ++i) { C.row(i) = colorAtIndex(std::get<2>(mesh)(i), partData.size()); } viewer.data().set_mesh(cMeshOut.first, cMeshOut.second); viewer.data().set_colors(C); std::cout << "labeling parts" << std::endl; for (size_t c=0; c<partData.size(); ++c) { if (w_[c]) { MatrixX2d points = getShape(c).cutPath->points(); MatrixX3d points3d(points.rows(), 3); for (size_t r=0; r<points.rows(); ++r) { points3d.row(r) = (partData[c].rot * Vector3d(points(r, 0), points(r, 1), 0) + partData[c].pos).transpose(); } RowVector3d centroid = 0.5 * (points3d.colwise().maxCoeff() + points3d.colwise().minCoeff()); viewer.data().add_label(centroid, "PART " + std::to_string(c)); viewer.data().add_points(centroid, RowVector3d(0, 0, 1)); viewer.data().add_edges(centroid, centroid + partData[c].normal().transpose() * getStock(c).thickness, RowVector3d(0, 0, 1)); std::cout << "part " << c << " guides: "; for (const auto &pair : getShape(c).guides) { for (const auto &guide : pair.second) { std::cout << pair.first << ", "; RowVector3d ptA = partData[c].unproject(guide.edge.first.transpose()); RowVector3d ptB = partData[c].unproject(guide.edge.second.transpose()); viewer.data().add_edges(ptA, ptB, RowVector3d(0.5, 0.5, 0.5)); } } std::cout << std::endl; std::cout << "part " << c << " connection constraint edges: "; for (const auto &pair : getShape(c).connectionConstraints) { for (const auto &constraint : pair.second) { std::cout << pair.first << " ("; if (constraint.inside) std::cout << "I"; if (constraint.outside) std::cout << "O"; std::cout << "), "; RowVector3d ptA = partData[c].unproject(constraint.edge.first.transpose()); RowVector3d ptB = partData[c].unproject(constraint.edge.second.transpose()); ptA += partData[c].normal() * displacement; ptB += partData[c].normal() * displacement; viewer.data().add_edges(ptA, ptB, colorAtIndex(c, partData.size()) * 0.5); viewer.data().add_points(ptA, colorAtIndex(c, partData.size()) * 0.5); } } std::cout << std::endl; std::cout << "part " << c << " shape constraint edges: "; for (const auto &sc : getShape(c).shapeConstraints) { for (const auto &constraint : sc.second) { std::cout << sc.first << " ("; std::cout << (constraint.convex ? 'x' : 'v'); if (constraint.inside) std::cout << "I"; if (constraint.outside) std::cout << "O"; std::cout << "), "; RowVector3d ptA = partData[c].unproject(constraint.edge.first.transpose()); RowVector3d ptB = partData[c].unproject(constraint.edge.second.transpose()); if (constraint.opposing) { ptA -= partData[c].normal() * getStock(c).thickness; ptB -= partData[c].normal() * getStock(c).thickness; ptA -= partData[c].normal() * displacement; ptB -= partData[c].normal() * displacement; } else { ptA += partData[c].normal() * displacement; ptB += partData[c].normal() * displacement; } viewer.data().add_edges(ptA, ptB, colorAtIndex(c, partData.size())); } } std::cout << std::endl; } } edge_iter ei, eb; std::cout << "connections: " << std::endl; for (boost::tie(ei, eb) = edges(g); ei != eb; ++ei) { Edge e = *ei; Vertex v1 = vertex(g[e].part1, g); Vertex v2 = vertex(g[e].part2, g); size_t partIdx1 = g[v1].partIdx; size_t partIdx2 = g[v2].partIdx; const auto &pd1 = partData[partIdx1]; const auto &pd2 = partData[partIdx2]; Vector3d n1 = pd1.normal(); Vector3d n2 = pd2.normal(); RowVector3d offset = (n1 + n2).transpose() * displacement; //visualize closeness /*RowVector3d point1 = partMeshes[partIdx1].first.colwise().mean(); RowVector3d point2 = partMeshes[partIdx2].first.colwise().mean();*/ RowVector3d point1, point2; // double dist = distanceBetweenParts(partIdx1, partIdx2, point1, point2); viewer.data().add_edges(point1, point2, colorAtIndex(partIdx1, partData.size())); viewer.data().add_edges(point1 + offset, point2 + offset, colorAtIndex(partIdx2, partData.size())); viewer.data().add_label(0.5 * (point1 + point2), "(n.n=" + std::to_string(n1.dot(n2)) + ")"); //visualize connections if (g[e].type == ConnectionEdge::CET_UNKNOWN) { continue; } std::cout << "connection [" << partIdx1 << '-' << partIdx2 << "] type " << g[e].type << " backface1: " << g[e].backface1 << "; backface2: " << g[e].backface2 << std::endl; if (g[e].type == ConnectionEdge::CET_CUT_TO_CUT) { // std::cout << "building interface plane meshes" << std::endl; for (const auto &interface : g[e].interfaces) { Eigen::Vector3d up(0, 0, 0); int ind = 0; double mincomp = std::abs(interface.d[0]); for (int i = 1; i < 3; i++) { double abscomp = std::abs(interface.d[i]); if (abscomp < mincomp) { ind = i; mincomp = abscomp; } } up[ind] = 1.0f; Eigen::Matrix<double, 2, 3> basis; basis.row(1) = interface.d.cross(up).normalized(); basis.row(0) = basis.row(1).transpose().cross(interface.d).normalized(); MatrixX3d V1(4, 3); MatrixX3d V2(4, 3); V1.row(0) = interface.o.transpose() - basis.row(0) * displacement - basis.row(1) * displacement; V1.row(1) = interface.o.transpose() - basis.row(0) * displacement + basis.row(1) * displacement; V1.row(2) = interface.o.transpose() + basis.row(0) * displacement + basis.row(1) * displacement; V1.row(3) = interface.o.transpose() + basis.row(0) * displacement - basis.row(1) * displacement; V2.block(0, 0, 3, 3) = V1.block(1, 0, 3, 3); V2.row(3) = V1.row(0); viewer.data().add_edges(V1, V2, RowVector3d(1.0, 0.5, 0.0)); } } else { for (size_t edgeIndex=0; edgeIndex < g[e].innerEdge.ranges.size(); ++edgeIndex) { Edge3d edge3d = g[e].innerEdge.getEdge(edgeIndex); viewer.data().add_edges(edge3d.first.transpose() + offset, edge3d.second.transpose() + offset, RowVector3d(1, 0.5, 1)); Edge3d edge1 = edge3d; Edge3d edge2 = edge3d; Vector3d surfaceNormal1 = n1; Vector3d surfaceNormal2 = n2; if (g[e].backface1) { surfaceNormal1 = -surfaceNormal1; } if (!g[e].backface2) { surfaceNormal2 = -surfaceNormal2; } edge2.first += surfaceNormal1 * getStock(partIdx1).thickness; edge2.second += surfaceNormal1 * getStock(partIdx1).thickness; if (g[e].type == ConnectionEdge::CET_CORNER) { edge1.first -= surfaceNormal1 * getStock(partIdx1).thickness; edge1.second -= surfaceNormal1 * getStock(partIdx1).thickness; } std::cout << "building plane meshes" << std::endl; MatrixX3d V1(5, 3); MatrixX3d V2(5, 3); V1.row(0) = edge1.first; V1.row(1) = edge1.second; V1.row(2) = edge2.second; V1.row(3) = edge2.first; V2.block(0, 0, 3, 3) = V1.block(1, 0, 3, 3); V2.row(3) = V1.row(0); V1.row(4) = edge1.first; V2.row(4) = edge2.second; viewer.data().add_edges(V1, V2, RowVector3d(0.0, 0.5, 1.0)); } } } std::cout << "displaying" << std::endl; viewer.core().background_color = {1, 1, 1, 0}; // if (openWindow) { igl::opengl::glfw::imgui::ImGuiMenu menu; menu.callback_draw_viewer_window = []() {}; viewer.plugins.push_back(&menu); viewer.launch(); // } } bool Construction::exportMesh(const std::string &filename, const std::string &connectorFilename, double connectorSpacing, double connectorScale) const { std::cout << "exporting mesh to " << filename << std::endl; Multimesh cmesh; cmesh.AddMesh(std::make_pair(std::get<0>(mesh), std::get<1>(mesh))); if (!connectorFilename.empty()) { cmesh.AddMesh(connectorMesh(connectorFilename, connectorSpacing, connectorScale)); } auto cmesho = cmesh.GetTotalMesh(); return igl::writeOBJ(filename, cmesho.first, cmesho.second); } void writeCurve(std::ostream &file, const CombinedCurve &curves) { for (size_t j=0; j<curves.size(); ++j) { const auto &curve = curves.getCurve(j); file << "<segment type=\"" << static_cast<std::underlying_type<CurveTypes>::type>(curve.type()) << "\">" << std::endl; MatrixX2d points = curve.uniformSample(20); for (int k=0; k < points.rows(); k++) { file << "<point2 value=\"" << points.row(k) << "\"/>" << std::endl; } file << "<point2 value=\"" << curve.sample(1).transpose() << "\"/>" << std::endl; file << "</segment>" << std::endl; } } bool Construction::exportPart(size_t partIdx, std::ofstream &of, LoadMode mode) const { IndexMap index = get(vertex_index, g); const auto &pd = partData[partIdx]; if (mode == SELECTION) { of << (w_[partIdx] ? 1 : 0) << std::endl; } std::cout << "saving thickness " << getStock(partIdx).thickness << std::endl; of << getStock(partIdx).thickness; if (mode == SEGMENTATION) { of << " " << getShape(partIdx).gridSpacing; } of << std::endl; of << pd.rot.w() << " " << pd.rot.x() << " " << pd.rot.y() << " " << pd.rot.z() << std::endl; of << pd.pos.transpose() << std::endl; const auto &shape = getShape(partIdx).cutPath; if (!shape->curves().exportPlaintext(of)) { std::cout << "failed exporting curve for part " << partIdx << std::endl; return false; } const auto &children = shape->children(); of << children.size() << " children" << std::endl; for (const auto &child : children) { if (!child->curves().exportPlaintext(of)) { std::cout << "failed exporting child of part " << partIdx << std::endl; return false; } } const auto &shapeConstraints=getShape(partIdx).shapeConstraints; size_t numSC = 0; for (const auto &pair : shapeConstraints) { numSC += pair.second.size(); } if (mode != BASIC && mode != BASICPLUS) { of << numSC << " shape constraints" << std::endl; for (const auto &pair : shapeConstraints) { int id; if (mode == SELECTION) { id = pair.first; } else { auto v = partIdxToVertex(pair.first); id = v.second ? (int) index[v.first] : -1; } for (const auto &sc : pair.second) { of << id << " " << sc.convex << " " << sc.edge.first.transpose() << " " << sc.edge.second.transpose() << " " << sc.inside << " " << sc.opposing << " " << sc.otherOpposing << std::endl; } } } return true; } bool Construction::exportPlaintext(const std::string &filename, LoadMode mode) const { std::cout << "saved checkpoint file at " << filename << std::endl; std::ofstream of(filename); if (of) { of << std::setprecision(20); if (mode == SELECTION) { size_t N = partData.size(); of << N << std::endl; for (size_t i=0; i<N; ++i) { if (!exportPart(i, of, mode)) return false; } } else { size_t N = num_vertices(g); of << N << " parts" << std::endl; for (size_t i = 0; i < N; ++i) { Vertex v = vertex(i, g); size_t partIdx = g[v].partIdx; if (!exportPart(partIdx, of, mode)) return false; } size_t N_c = 0; edge_iter ei, eb; for (boost::tie(ei, eb) = edges(g); ei != eb; ++ei) { Edge e = *ei; if (g[e].type != ConnectionEdge::CET_UNKNOWN) { ++N_c; } } of << N_c << " connections" << std::endl; for (boost::tie(ei, eb) = edges(g); ei != eb; ++ei) { Edge e = *ei; if (g[e].type != ConnectionEdge::CET_UNKNOWN) { of << g[e].part1 << " " << g[e].part2 << " " << g[e].type << " " << g[e].backface1 << " " << g[e].backface2 << std::endl; const auto &innerEdge = g[e].innerEdge; of << innerEdge.o.transpose() << " " << innerEdge.d.transpose() << std::endl; of << innerEdge.size() << std::endl; for (int i = 0; i < innerEdge.size(); ++i) { of << innerEdge.ranges[i].first << " " << innerEdge.ranges[i].second << std::endl; } } } } } else { std::cout << "could not export plaintext to " << filename << std::endl; return false; } std::cout << "saved checkpoint file at " << filename << std::endl; return true; } bool Construction::loadPlaintext(const std::string &filename, LoadMode mode) { bool curveConstraints = (mode != BASIC); std::cout << "loading from file " << filename << std::endl; std::ifstream ifs(filename); if (ifs) { size_t N; std::string line; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> N; } std::cout << "loading " << N << " parts" << std::endl; partData.reserve(N); shapeData.reserve(N); stockData.reserve(N); w_ = std::vector<bool>(N, true); if (mode != SELECTION) { g = Graph(N); } for (int i=0; i<N; ++i) { std::cout << "loading part " << i << std::endl; if (mode != SELECTION) { Vertex v = vertex(i, g); g[v].partIdx = i; } else { int isUsed; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> isUsed; LINE_FAIL("failed to read used state"); } w_[i] = isUsed; } PartData pd; pd.shapeIdx = i; if (i== N-1) pd.groundPlane = true; ShapeData sd; sd.stockIdx = i; StockData stock; //get thickness std::getline(ifs, line); { std::istringstream is_line(line); is_line >> stock.thickness; LINE_FAIL("failed to parse thickness"); std::cout << "thickness: " << stock.thickness << std::endl; if (mode == SEGMENTATION) { is_line >> sd.gridSpacing; // LINE_FAIL("failed to parse grid spacing"); } } //get rotation std::getline(ifs, line); { std::istringstream is_line(line); is_line >> pd.rot.w() >> pd.rot.x() >> pd.rot.y() >> pd.rot.z(); } //get translation std::getline(ifs, line); { std::istringstream is_line(line); is_line >> pd.pos.x() >> pd.pos.y() >> pd.pos.z(); } CombinedCurve outerCurve; if (!outerCurve.loadPlaintext(ifs, curveConstraints)) { std::cout << "failed loading curve for part " << i << std::endl; return false; } size_t numChildren; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> numChildren; } std::cout << numChildren << " child curves for part " << i << std::endl; std::vector<std::shared_ptr<Primitive>> holes; for (size_t j=0; j<numChildren; ++j) { CombinedCurve childCurve; if (!childCurve.loadPlaintext(ifs, curveConstraints)) { std::cout << "failed loading curve for part " << i << " child " << j << std::endl; return false; } holes.emplace_back(new PolyCurveWithHoles(childCurve)); } sd.cutPath = std::make_shared<PolyCurveWithHoles>(outerCurve, std::move(holes)); if (mode != BASIC && mode != BASICPLUS) { size_t numShapeConstraints = 0; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> numShapeConstraints; } std::cout << "loading " << numShapeConstraints << " shape constraints" << std::endl; for (size_t j=0; j<numShapeConstraints; ++j) { ShapeConstraint sc; int id; std::getline(ifs, line); { std::istringstream is_line(line); int convex, inside, opposing, otherOpposing; is_line >> id >> convex >> sc.edge.first.x() >> sc.edge.first.y() >> sc.edge.second.x() >> sc.edge.second.y() >> inside >> opposing >> otherOpposing; sc.convex = convex; sc.inside = inside; sc.opposing = opposing; sc.otherOpposing = otherOpposing; LINE_FAIL("failed reading shape constraint"); } if (id < 0) { std::cout << "shape constraint " << j << " is " << id << std::endl; } sd.shapeConstraints[id].push_back(std::move(sc)); } } partData.push_back(std::move(pd)); shapeData.push_back(std::move(sd)); stockData.push_back(std::move(stock)); } if (mode != SELECTION) { size_t N_c; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> N_c; } std::cout << N_c << " connections" << std::endl; for (size_t i = 0; i < N_c; ++i) { int id1, id2, type; int backface1, backface2; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> id1 >> id2 >> type >> backface1 >> backface2; LINE_FAIL("failed to parse connection " + std::to_string(i)); } std::cout << "connection " << i << ": " << id1 << '-' << id2 << " type " << type; std::cout << '(' << line << ')' << std::endl; std::cout << "backface1: " << backface1 << "; backface2: " << backface2 << std::endl; MultiRay3d innerEdge; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> innerEdge.o.x() >> innerEdge.o.y() >> innerEdge.o.z() >> innerEdge.d.x() >> innerEdge.d.y() >> innerEdge.d.z(); } size_t numEdges; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> numEdges; } std::cout << "num edges: " << numEdges << std::endl; for (size_t j = 0; j < numEdges; ++j) { std::pair<double, double> range; std::getline(ifs, line); { std::istringstream is_line(line); is_line >> range.first >> range.second; } innerEdge.ranges.push_back(range); } Edge e; bool inserted; Vertex v1 = vertex(id1, g); Vertex v2 = vertex(id2, g); boost::tie(e, inserted) = add_edge(v1, v2, g); if (!inserted) { std::cout << "failed to insert edge" << std::endl; } g[e].innerEdge = std::move(innerEdge); g[e].part1 = id1; g[e].part2 = id2; g[e].backface1 = backface1; g[e].backface2 = backface2; g[e].optimizeStage = 1; g[e].type = static_cast<ConnectionEdge::ConnectionType>(type); } } } else { std::cout << "failed to open " << filename << std::endl; return false; } return true; } bool Construction::exportModel(const std::string &filename) const { std::cout << "exporting model to " << filename << std::endl; std::ofstream file(filename); if (file) { file << "<solution>" << std::endl; size_t N = num_vertices(g); for (size_t i=0; i<N; ++i) { Vertex v = vertex(i, g); size_t partIdx = g[v].partIdx; const auto &pd = partData[partIdx]; file << "<part id=\"" << partIdx << "\" depth=\"" << getStock(partIdx).thickness << "\" rotation=\"" << pd.rot.w() << " " << pd.rot.x() << " " << pd.rot.y() << " " << pd.rot.z() << "\" translation=\"" << pd.pos.x() << " " << pd.pos.y() << " " << pd.pos.z() << "\">" << std::endl; file << "<shape>" << std::endl; { const auto &curves = getShape(partIdx).cutPath->curves(); CombinedCurve backCurves = getBackCurve(partIdx); std::ofstream svgFile(filename + "-part" + std::to_string(partIdx) + ".svg"); svgFile << R"(<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">)" << std::endl; std::cout << "exporting SVG for part " << partIdx << std::endl; curves.exportSVG(svgFile); curves.exportSVG(file); backCurves.exportSVG(svgFile); const auto &children = getShape(partIdx).cutPath->children(); for (const auto &child : children) { file << "<hole>" << std::endl; child->curves().exportSVG(svgFile); child->curves().exportSVG(file); // writeCurve(file, child->curves()); file << "</hole>" << std::endl; } svgFile << "</svg>" << std::endl; } file << "</shape>"; // writeCurve(file, curves); file << "</part>" << std::endl; } edge_iter ei, eb; for (boost::tie(ei, eb) = edges(g); ei != eb; ++ei) { Edge e = *ei; if (g[e].type != ConnectionEdge::CET_UNKNOWN) { Vertex v1 = vertex(g[e].part1, g); Vertex v2 = vertex(g[e].part2, g); file << "<connection id1=\"" << g[v1].partIdx << "\" id2=\"" << g[v2].partIdx << "\" type=\"" << g[e].type << "\"/>" << std::endl; } } file << "</solution>" << std::endl; } else { std::cout << "could not open file " << filename << std::endl; return false; } return true; } void Construction::saveShapes() const { size_t N = num_vertices(g); for (size_t i=0; i<N; ++i) { Vertex v = vertex(i, g); size_t partIdx = g[v].partIdx; CombinedCurve curve = getShape(partIdx).cutPath->curves(); Vector2d minPt; double scale = computeScale(curve, minPt); std::string name = "part_" + std::to_string(i) + "_curve.png"; cv::Mat img = display_curve(name, curve, scale, minPt); cv::imwrite(name, img); } } std::pair<Eigen::MatrixX3d, Eigen::MatrixX3i> Construction::connectorMesh(const std::string &connectorOBJ, double spacingd, double scale) const { Eigen::MatrixXd V; Eigen::MatrixXi F; Multimesh cmesh; if (!igl::readOBJ(connectorOBJ, V, F)) { std::cout << "failed to load connector OBJ file " << connectorOBJ << std::endl; return {V, F}; } V.array() *= scale; edge_iter ei, eb; for (boost::tie(ei, eb) = edges(g); ei != eb; ++ei) { Edge e = *ei; Vertex v1 = vertex(g[e].part1, g); Vertex v2 = vertex(g[e].part2, g); size_t partIdx1 = g[v1].partIdx; size_t partIdx2 = g[v2].partIdx; const auto &pd1 = partData[partIdx1]; const auto &pd2 = partData[partIdx2]; if (pd2.groundPlane) continue; Vector3d n1 = pd1.normal(); Vector3d n2 = pd2.normal(); double thickness = getStock(partIdx1).thickness; double thickness2 = getStock(partIdx2).thickness; Vector3d cutDir = (n1 - n1.dot(n2) * n2).normalized(); Vector3d nailDir = (n2 - n2.dot(n1) * n1).normalized(); if (g[e].backface2) nailDir = -nailDir; const auto &innerEdge = g[e].innerEdge; double angSin = n1.cross(n2).norm(); double midCut = 0.5 * thickness / angSin; double nailDepth = thickness2 / angSin; Eigen::Quaterniond rot = Eigen::Quaterniond::FromTwoVectors(Vector3d(0, 0, 1), nailDir); for (int i=0; i<innerEdge.ranges.size(); ++i) { double len = innerEdge.ranges[i].second - innerEdge.ranges[i].first; if (len < spacingd*2) { continue; } for (int j=0; j<2; ++j) { double startOffset; if (j == 0) { startOffset = spacingd; } else { startOffset = len - spacingd; } Vector3d currPos = innerEdge.o + innerEdge.d * (innerEdge.ranges[i].first + startOffset) - cutDir * midCut; MatrixXd nailV = V; nailV.col(2).array() -= nailDepth; for (int r=0; r<V.rows(); ++r) { Vector3d p = nailV.row(r).transpose(); nailV.row(r) = (rot * p).transpose(); } nailV.rowwise() += currPos.transpose(); cmesh.AddMesh(std::make_pair(nailV, F)); } } } return cmesh.GetTotalMesh(); }
43.180451
180
0.488908
ShnitzelKiller
dd764e499254b5e2ec28a018f029f4120abd5c0d
1,061
hpp
C++
FFN.hpp
wimacod/Feed-Forward-Neural-Network
968c16101f08a3bcb7d9124a148452c187611342
[ "MIT" ]
7
2019-03-12T22:05:45.000Z
2022-02-16T06:10:52.000Z
FFN.hpp
wimacod/Feed-Forward-Neural-Network
968c16101f08a3bcb7d9124a148452c187611342
[ "MIT" ]
2
2019-02-27T18:46:04.000Z
2022-01-19T22:50:13.000Z
FFN.hpp
wimacod/Feed-Forward-Neural-Network
968c16101f08a3bcb7d9124a148452c187611342
[ "MIT" ]
6
2017-12-06T07:27:59.000Z
2020-12-03T04:29:23.000Z
// // FFN.hpp // Neural Networks // // Created by Alexis Louis on 15/03/2016. // Copyright © 2016 Alexis Louis. All rights reserved. // #ifndef FFN_hpp #define FFN_hpp #include "Header.h" using namespace std; class Layer; class FFN{ public: FFN(); void initFFN(int nb_inputs, int nb_hidden_neurons, int nb_outputs); void sim(vector<float> inputs); void test(vector<vector<float>> Xtest, vector<vector<float>> Tt); void train_by_iteration(vector<vector<float>> inputs, vector<vector<float>> targets, int target_iteration); void train_by_error(vector<vector<float>> inputs, vector<vector<float>> targets, float target_error); void about(); vector<float> get_ffn_outputs(); void set_targets(vector<float> tar); vector<float> get_targets(void){return targets;}; int get_nb_layers(){return layers.size();}; Layer* get_layer_at(int indice){return layers[indice];}; private: vector<Layer*> layers; vector<float> targets; void add_layer(Layer* l); }; #endif /* FFN_hpp */
23.065217
111
0.68426
wimacod
dd77d60cf3526d109f37884f54d907f4e9072ef1
10,603
cpp
C++
src/mod/mvm/set_credit_team.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
33
2016-02-18T04:27:53.000Z
2022-01-15T18:59:53.000Z
src/mod/mvm/set_credit_team.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2018-01-10T18:41:38.000Z
2020-10-01T13:34:53.000Z
src/mod/mvm/set_credit_team.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
14
2017-08-06T23:02:49.000Z
2021-08-24T00:24:16.000Z
#include "mod.h" #include "stub/baseplayer.h" namespace Mod::MvM::Set_Credit_Team { int GetCreditTeamNum() { extern ConVar cvar_enable; return cvar_enable.GetInt(); } constexpr uint8_t s_Buf_CCurrencyPack_MyTouch[] = { 0x8b, 0x06, // +0000 mov eax,[esi] 0x89, 0x34, 0x24, // +0002 mov [esp],esi 0xff, 0x90, 0x00, 0x00, 0x00, 0x00, // +0005 call dword ptr [eax+VToff(CBasePlayer::IsBot)] }; struct CPatch_CCurrencyPack_MyTouch : public CPatch { CPatch_CCurrencyPack_MyTouch() : CPatch(sizeof(s_Buf_CCurrencyPack_MyTouch)) {} virtual const char *GetFuncName() const override { return "CCurrencyPack::MyTouch"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0070; } // @ +0x0052 virtual bool GetVerifyInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CCurrencyPack_MyTouch); static VTOffFinder vtoff_CBasePlayer_IsBot(TypeName<CBasePlayer>(), "CBasePlayer::IsBot"); if (!vtoff_CBasePlayer_IsBot.IsValid()) return false; buf.SetDword(0x05 + 2, vtoff_CBasePlayer_IsBot); return true; } virtual bool GetPatchInfo(ByteBuf& buf, ByteBuf& mask) const override { /* overwrite the call with 'xor eax, eax; nop; nop; nop; nop' */ buf[0x05 + 0] = 0x31; buf[0x05 + 1] = 0xc0; buf[0x05 + 2] = 0x90; buf[0x05 + 3] = 0x90; buf[0x05 + 4] = 0x90; buf[0x05 + 5] = 0x90; mask.SetRange(0x05, 6, 0xff); return true; } }; constexpr uint8_t s_Buf_CTFPowerup_ValidTouch[] = { 0x89, 0x34, 0x24, // +0000 mov [esp],esi 0xe8, 0x00, 0x00, 0x00, 0x00, // +0003 call CBaseEntity::GetTeamNumber 0x83, 0xf8, 0x03, // +0008 cmp eax,TF_TEAM_BLUE 0x0f, 0x84, // +000B jz -0xXXXXXXXX }; struct CPatch_CTFPowerup_ValidTouch : public CPatch { CPatch_CTFPowerup_ValidTouch() : CPatch(sizeof(s_Buf_CTFPowerup_ValidTouch)) {} virtual const char *GetFuncName() const override { return "CTFPowerup::ValidTouch"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x00c0; } // @ +0x00a8 virtual bool GetVerifyInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CTFPowerup_ValidTouch); mask.SetDword(0x03 + 1, 0x00000000); return true; } virtual bool GetPatchInfo(ByteBuf& buf, ByteBuf& mask) const override { /* for now, replace the comparison operand with TEAM_INVALID */ buf[0x08 + 2] = (uint8_t)TEAM_INVALID; /* reverse the jump condition from 'jz' to 'jnz' */ buf[0x0b + 1] = 0x85; mask[0x08 + 2] = 0xff; mask[0x0b + 1] = 0xff; return true; } virtual bool AdjustPatchInfo(ByteBuf& buf) const override { /* set the comparison operand to the actual user-requested teamnum */ buf[0x08 + 2] = (uint8_t)GetCreditTeamNum(); return true; } }; constexpr uint8_t s_Buf_RadiusCurrencyCollectionCheck[] = { 0x8b, 0x87, 0x00, 0x00, 0x00, 0x00, // +0000 mov exx,[exx+m_pOuter] 0x89, 0x04, 0x24, // +0006 mov [esp],exx 0xe8, 0x00, 0x00, 0x00, 0x00, // +0009 call CBaseEntity::GetTeamNumber 0x83, 0xf8, 0x02, // +000E cmp eax,TF_TEAM_RED }; struct CPatch_RadiusCurrencyCollectionCheck : public CPatch { CPatch_RadiusCurrencyCollectionCheck() : CPatch(sizeof(s_Buf_RadiusCurrencyCollectionCheck)) {} virtual const char *GetFuncName() const override { return "CTFPlayerShared::RadiusCurrencyCollectionCheck"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0020; } // @ +0x000c virtual bool GetVerifyInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_RadiusCurrencyCollectionCheck); int off_CTFPlayerShared_m_pOuter; if (!Prop::FindOffset(off_CTFPlayerShared_m_pOuter, "CTFPlayerShared", "m_pOuter")) return false; buf.SetDword(0x00 + 2, off_CTFPlayerShared_m_pOuter); /* allow any 3-bit source or destination register code */ mask[0x00 + 1] = 0b11000000; /* allow any 3-bit source register code */ mask[0x06 + 1] = 0b11000111; mask.SetDword(0x09 + 1, 0x00000000); return true; } virtual bool GetPatchInfo(ByteBuf& buf, ByteBuf& mask) const override { /* for now, replace the comparison operand with TEAM_INVALID */ buf[0x0e + 2] = (uint8_t)TEAM_INVALID; mask[0x0e + 2] = 0xff; return true; } virtual bool AdjustPatchInfo(ByteBuf& buf) const override { /* set the comparison operand to the actual user-requested teamnum */ buf[0x0e + 2] = (uint8_t)GetCreditTeamNum(); return true; } }; constexpr uint8_t s_Buf_CTFGameRules_DistributeCurrencyAmount[] = { 0xc7, 0x44, 0x24, 0x0c, 0x00, 0x00, 0x00, 0x00, // +0000 mov dword ptr [esp+0xc],false 0xc7, 0x44, 0x24, 0x08, 0x00, 0x00, 0x00, 0x00, // +0008 mov dword ptr [esp+0x8],false 0xc7, 0x44, 0x24, 0x04, 0x02, 0x00, 0x00, 0x00, // +0010 mov dword ptr [esp+0x4],TF_TEAM_RED 0x89, 0x04, 0x24, // +0018 mov [esp],exx 0x89, 0x45, 0xc0, // +001B mov [ebp-0xXX],exx 0xe8, // +001E call CollectPlayers<CTFPlayer> }; struct CPatch_CTFGameRules_DistributeCurrencyAmount : public CPatch { CPatch_CTFGameRules_DistributeCurrencyAmount() : CPatch(sizeof(s_Buf_CTFGameRules_DistributeCurrencyAmount)) {} virtual const char *GetFuncName() const override { return "CTFGameRules::DistributeCurrencyAmount"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0100; } // @ +0x00d3 virtual bool GetVerifyInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CTFGameRules_DistributeCurrencyAmount); /* allow any 3-bit source register code */ mask[0x18 + 1] = 0b11000111; mask[0x1b + 1] = 0b11000111; return true; } virtual bool GetPatchInfo(ByteBuf& buf, ByteBuf& mask) const override { /* for now, replace the teamnum argument with TEAM_INVALID */ buf.SetDword(0x10 + 4, TEAM_INVALID); mask.SetDword(0x10 + 4, 0xffffffff); return true; } virtual bool AdjustPatchInfo(ByteBuf& buf) const override { /* set the teamnum argument to the actual user-requested teamnum */ buf.SetDword(0x10 + 4, GetCreditTeamNum()); return true; } }; constexpr uint8_t s_Buf_CPopulationManager_OnCurrencyCollected[] = { 0xc7, 0x44, 0x24, 0x0c, 0x00, 0x00, 0x00, 0x00, // +0000 mov dword ptr [esp+0xc],false 0xc7, 0x44, 0x24, 0x08, 0x00, 0x00, 0x00, 0x00, // +0008 mov dword ptr [esp+0x8],false 0xc7, 0x44, 0x24, 0x04, 0x02, 0x00, 0x00, 0x00, // +0010 mov dword ptr [esp+0x4],TF_TEAM_RED 0x89, 0x04, 0x24, // +0018 mov [esp],exx 0xc7, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, // +001B mov [ebp-0xXXX],0x00000000 0xc7, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, // +0022 mov [ebp-0xXXX],0x00000000 0xc7, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, // +0029 mov [ebp-0xXXX],0x00000000 0xc7, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, // +0030 mov [ebp-0xXXX],0x00000000 0xe8, // +0037 call CollectPlayers<CTFPlayer> }; struct CPatch_CPopulationManager_OnCurrencyCollected : public CPatch { CPatch_CPopulationManager_OnCurrencyCollected() : CPatch(sizeof(s_Buf_CPopulationManager_OnCurrencyCollected)) {} virtual const char *GetFuncName() const override { return "CPopulationManager::OnCurrencyCollected"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0200; } // @ +0x00af virtual bool GetVerifyInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CPopulationManager_OnCurrencyCollected); /* allow any 3-bit source register code */ mask[0x18 + 1] = 0b11000111; mask.SetDword(0x1b + 2, 0xfffff003); mask.SetDword(0x22 + 2, 0xfffff003); mask.SetDword(0x29 + 2, 0xfffff003); mask.SetDword(0x30 + 2, 0xfffff003); return true; } virtual bool GetPatchInfo(ByteBuf& buf, ByteBuf& mask) const override { /* for now, replace the teamnum argument with TEAM_INVALID */ buf.SetDword(0x10 + 4, TEAM_INVALID); mask.SetDword(0x10 + 4, 0xffffffff); return true; } virtual bool AdjustPatchInfo(ByteBuf& buf) const override { /* set the teamnum argument to the actual user-requested teamnum */ buf.SetDword(0x10 + 4, GetCreditTeamNum()); return true; } }; class CMod : public IMod { public: CMod() : IMod("MvM:Set_Credit_Team") { /* allow bots to touch currency packs */ this->AddPatch(new CPatch_CCurrencyPack_MyTouch()); /* set who can touch currency packs */ this->AddPatch(new CPatch_CTFPowerup_ValidTouch()); /* set who can do radius currency collection */ this->AddPatch(new CPatch_RadiusCurrencyCollectionCheck()); /* set which team receives credits when they're collected or given out */ this->AddPatch(new CPatch_CTFGameRules_DistributeCurrencyAmount()); /* set whose respec information gets updated when credits are collected */ this->AddPatch(new CPatch_CPopulationManager_OnCurrencyCollected()); } }; CMod s_Mod; ConVar cvar_enable("sig_mvm_set_credit_team", "0", FCVAR_NOTIFY, "Mod: change which team is allowed to collect MvM credits (normally hardcoded to TF_TEAM_RED)", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ auto var = static_cast<ConVar *>(pConVar); /* refresh patches with the new convar value if we do a nonzero --> nonzero transition */ if (s_Mod.IsEnabled() && var->GetBool()) { // REMOVE ME ConColorMsg(Color(0xff, 0x00, 0xff, 0xff), "sig_mvm_set_credit_team: toggling patches off and back on, for %s --> %s transition.\n", pOldValue, var->GetString()); s_Mod.ToggleAllPatches(false); s_Mod.ToggleAllPatches(true); } s_Mod.Toggle(var->GetBool()); }); }
34.763934
116
0.652174
fugueinheels
dd78bb02838ed79698690ad817cdb07b8bc87fca
576
cpp
C++
NSU Team Contest ( 12 October 2016 )/G - Cupboards.cpp
anirudha-ani/NSU-Problem-Solver
2f6312fe5823c0352358f5db654dd0e1a619ce75
[ "Apache-2.0" ]
null
null
null
NSU Team Contest ( 12 October 2016 )/G - Cupboards.cpp
anirudha-ani/NSU-Problem-Solver
2f6312fe5823c0352358f5db654dd0e1a619ce75
[ "Apache-2.0" ]
null
null
null
NSU Team Contest ( 12 October 2016 )/G - Cupboards.cpp
anirudha-ani/NSU-Problem-Solver
2f6312fe5823c0352358f5db654dd0e1a619ce75
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t , l , r , l_z = 0 , l_o = 0 , r_z = 0 , r_o = 0 , ans = 0 ; scanf("%d", &t); for(int i = 0 ; i < t ; i++) { scanf("%d %d", &l , &r); if(l == 0) { l_z++; } else { l_o++; } if(r == 0) { r_z++; } else { r_o++; } } ans = min(l_z , l_o) + min(r_z , r_o); printf("%d\n" , ans); return 0; }
15.567568
71
0.277778
anirudha-ani
dd7b7ac4680a63f80b4bbb31c7abba9c094fea4d
900
cpp
C++
Client/src/Command_batch.cpp
gsass1/Totally-Not-A-Virus
092019a292a8af9a897f092c57b1c7efaefdbefb
[ "WTFPL" ]
2
2021-07-30T09:34:53.000Z
2021-09-01T09:19:22.000Z
Client/src/Command_batch.cpp
gsass1/Totally-Not-A-Virus
092019a292a8af9a897f092c57b1c7efaefdbefb
[ "WTFPL" ]
null
null
null
Client/src/Command_batch.cpp
gsass1/Totally-Not-A-Virus
092019a292a8af9a897f092c57b1c7efaefdbefb
[ "WTFPL" ]
null
null
null
#include "Command_batch.h" #include "stdafx.h" #include "Logger.h" Command_batch::Command_batch() { } Command_batch::~Command_batch() { } bool Command_batch::OnExecute(const std::vector<std::wstring> &args) { if(!(args.size() > 1)) { VLog(LERROR, L"batch: missing argument"); return false; } std::wstring fileArgs = Util::join_at_index(args, L" ", 1); if(fileArgs.length() > _MAX_PATH) { VLog(LERROR, L"batch: filename too long"); return false; } PROCESS_INFORMATION pi; STARTUPINFO si; BOOL ret; ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); // Create a raw copy of fileArgs wchar_t fileArgsCopy[_MAX_PATH]; wcscpy_s(fileArgsCopy, fileArgs.c_str()); ret = CreateProcess(NULL, fileArgsCopy, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if(!ret) { VLog(LERROR, L"batch: Failed to create process"); return false; } return true; }
19.148936
85
0.683333
gsass1