text
stringlengths
54
60.6k
<commit_before>#include <assert.h> #include "global.h" #include "Level.h" #include "blocks.h" #include "2d/cube.h" void begin_compound(void *context, nbt::String name) { if (name.compare("Level") == 0) { ((Level*)context)->islevel = true; } } void register_int(void *context, nbt::String name, nbt::Int i) { if (name.compare("xPos") == 0) { ((Level *)context)->xPos = i; return; } if (name.compare("zPos") == 0) { ((Level *)context)->zPos = i; return; } } void register_byte_array(void *context, nbt::String name, nbt::ByteArray *byte_array) { if (name.compare("Blocks") == 0) { ((Level *)context)->blocks = byte_array; return; } if (name.compare("SkyLight") == 0) { ((Level *)context)->skylight = byte_array; return; } if (name.compare("HeightMap") == 0) { ((Level *)context)->heightmap = byte_array; return; } if (name.compare("BlockLight") == 0) { ((Level *)context)->blocklight = byte_array; return; } } void error_handler(void *context, size_t where, const char *why) { ((Level *)context)->grammar_error = true; ((Level *)context)->grammar_error_where = where; ((Level *)context)->grammar_error_why = why; } Level::~Level(){ if (!ignore_blocks && islevel) { delete blocks; delete skylight; delete heightmap; delete blocklight; } } Level::Level(const char *path, bool ignore_blocks) : path(path), ignore_blocks(ignore_blocks) { xPos = 0; zPos = 0; islevel = false; grammar_error = false; nbt::Parser parser(this); if (!ignore_blocks) { parser.register_byte_array = register_byte_array; } parser.register_int = register_int; parser.begin_compound = begin_compound; parser.error_handler = error_handler; try { parser.parse_file(path); } catch(nbt::bad_grammar &bg) { grammar_error = true; } } /** * Blocks[ z + ( y * ChunkSizeY(=128) + ( x * ChunkSizeY(=128) * ChunkSizeZ(=16) ) ) ]; */ nbt::Byte bget(nbt::ByteArray *blocks, int x, int z, int y) { assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); assert (p >= 0 && p < blocks->length); return blocks->values[p]; } nbt::Byte bsget(nbt::ByteArray *skylight, int x, int z, int y) { assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); int ap = p / 2; assert (ap >= 0 && ap < skylight->length); // force unsigned uint8_t bp = skylight->values[ap] & 0xff; if (p % 2 == 0) { return bp >> 4; } else { return bp & 0xf; } } void transform_xz(settings_t *s, int &x, int &z) { /*if (s->flip) { int t = x; x = z; z = mc::MapZ - t - 1; } if (s->invert) { z = mc::MapZ - z - 1; x = mc::MapX - x - 1; }*/ } inline void apply_shading(settings_t *s, int bl, int sl, int hm, int y, Color &c) { // if night, darken all colors not emitting light if (s->night) { c.darken((0xd0 * (16 - bl)) / 16); } c.darken((mc::MapY - y)); c.darken(sl); } inline bool cavemode_isopen(int bt) { switch(bt) { case mc::Air: return true; case mc::Leaves: return true; default: return false; } } inline bool cavemode_ignore_block(settings_t *s, int x, int z, int y, int bt, nbt::ByteArray *blocks, bool &cave_initial) { if (cave_initial) { if (!cavemode_isopen(bt)) { cave_initial = false; return true; } return true; } if (!cavemode_isopen(bt)) { if (y < s->top && cavemode_isopen(bget(blocks, x, z, y + 1))) { return false; } } return true; } class BlockRotation { private: settings_t *s; nbt::ByteArray *byte_array; void transform_xzy(int& x, int& z, int& y) { switch (s->rotation) { case 270: z = mc::MapZ - z - 1; x = mc::MapX - x - 1; { int t = x; x = z; z = mc::MapZ - t - 1; } break; case 180: z = mc::MapZ - z - 1; x = mc::MapX - x - 1; break; case 90: { int t = x; x = z; z = mc::MapZ - t - 1; } break; }; } public: BlockRotation(settings_t *s, nbt::ByteArray *byte_array) : s(s), byte_array(byte_array) {} uint8_t get8(int x, int z, int y) { transform_xzy(x, z, y); assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); assert (p >= 0 && p < byte_array->length); return byte_array->values[p]; } uint8_t get4(int x, int z, int y) { transform_xzy(x, z, y); assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); int ap = p / 2; assert (ap >= 0 && ap < byte_array->length); // force unsigned uint8_t bp = byte_array->values[ap] & 0xff; if (p % 2 == 0) { return bp >> 4; } else { return bp & 0xf; } } }; ImageBuffer *Level::get_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX, mc::MapZ, 1); if (!islevel) { return img; } img->set_reversed(true); // block type int bt; for (int x = 0, mz = mc::MapZ - 1; x < mc::MapX; x++, mz--) { for (int y = 0, mx = 0; y < mc::MapX; y++, mx++) { Color base(255, 255, 255, 0); bt = mc::Air; bool cave_initial = true; int my; BlockRotation blocks_r(s, blocks); BlockRotation blocklight_r(s, blocklight); BlockRotation skylight_r(s, skylight); // do incremental color fill until color is opaque for (my = s->top; my > s->bottom; my--) { bt = blocks_r.get8(mx, mz, my); if (s->cavemode && cavemode_ignore_block(s, mx, mz, my, bt, blocks, cave_initial)) { continue; } if (s->excludes[bt]) { continue; } Color bc(mc::MaterialColor[bt]); int bl = blocklight_r.get4(mx, mz, my); int sl = skylight_r.get4(mx, mz, my); apply_shading(s, bl, sl, 0, my, bc); base.underlay(bc); if (base.is_opaque()) { break; } } if (base.is_transparent()) { continue; } img->set_pixel(x, y, 0, base); } } return img; } ImageBuffer *Level::get_oblique_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX, mc::MapZ + mc::MapY, mc::MapY + mc::MapZ); if (!islevel) { return img; } Cube c(mc::MapX, mc::MapY, mc::MapZ); // block type int bt; for (int x = 0, mz = mc::MapZ - 1; x < mc::MapX; x++, mz--) { for (int y = 0, mx = 0; y < mc::MapX; y++, mx++) { bool cave_initial = true; int cavemode_top = s->top; if (s->cavemode) { for (int my = s->top; my > 0; my--) { bt = bget(blocks, mx, mz, y); if (!cavemode_isopen(bt)) { cavemode_top = my; break; } } } for (int my = s->bottom; my < s->top; my++) { point p(x, my, y); bt = bget(blocks, mx, mz, my); if (s->cavemode) { if (cavemode_ignore_block(s, mx, mz, my, bt, blocks, cave_initial) || my >= cavemode_top) { continue; } } if (s->excludes[bt]) { continue; } int bl = bsget(blocklight, mx, mz, my); int sl = bsget(skylight, mx, mz, my); int _px, _py; c.project_oblique(p, _px, _py); Color top(mc::MaterialColor[bt]); apply_shading(s, bl, sl, 0, my, top); img->add_pixel(_px, _py - 1, top); Color side(mc::MaterialSideColor[bt]); apply_shading(s, bl, sl, 0, my, side); img->add_pixel(_px, _py, side); } } } return img; } ImageBuffer *Level::get_obliqueangle_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX * 2 + 1, mc::MapX + mc::MapY + mc::MapZ, mc::MapY + mc::MapZ * 2); if (!islevel) { return img; } Cube c(mc::MapX, mc::MapY, mc::MapZ); // block type int bt; for (int z = 0; z < c.z; z++) { for (int x = 0; x < c.x; x++) { bool cave_initial = true; int cavemode_top = s->top; if (s->cavemode) { for (int y = s->top; y > 0; y--) { int _x = x, _z = z; transform_xz(s, _x, _z); bt = bget(blocks, _x, _z, y); if (!cavemode_isopen(bt)) { cavemode_top = y; break; } } } for (int y = s->bottom; y < s->top; y++) { point p(x, y, z); int _x = x, _z = z; transform_xz(s, _x, _z); bt = bget(blocks, _x, _z, y); if (s->cavemode) { if (cavemode_ignore_block(s, _x, _z, y, bt, blocks, cave_initial) || y >= cavemode_top) { continue; } } if (s->excludes[bt]) { continue; } int bl = bsget(blocklight, _x, _z, y); int sl = bsget(skylight, _x, _z, y); int _px, _py; c.project_obliqueangle(p, _px, _py); Color top(mc::MaterialColor[bt]); apply_shading(s, bl, sl, 0, y, top); Color side(mc::MaterialSideColor[bt]); apply_shading(s, bl, sl, 0, y, side); switch(mc::MaterialModes[bt]) { case mc::Block: img->add_pixel(_px, _py - 1, top); img->add_pixel(_px + 1, _py - 1, top); img->add_pixel(_px, _py, side); img->add_pixel(_px + 1, _py, side); break; case mc::HalfBlock: img->add_pixel(_px, _py, top); img->add_pixel(_px + 1, _py, top); break; } } } } return img; } <commit_msg>Finally, working rotation with proxy blocks and pre-calculating of new positions, CHECK IT OUT!<commit_after>#include <assert.h> #include "global.h" #include "Level.h" #include "blocks.h" #include "2d/cube.h" void begin_compound(void *context, nbt::String name) { if (name.compare("Level") == 0) { ((Level*)context)->islevel = true; } } void register_int(void *context, nbt::String name, nbt::Int i) { if (name.compare("xPos") == 0) { ((Level *)context)->xPos = i; return; } if (name.compare("zPos") == 0) { ((Level *)context)->zPos = i; return; } } void register_byte_array(void *context, nbt::String name, nbt::ByteArray *byte_array) { if (name.compare("Blocks") == 0) { ((Level *)context)->blocks = byte_array; return; } if (name.compare("SkyLight") == 0) { ((Level *)context)->skylight = byte_array; return; } if (name.compare("HeightMap") == 0) { ((Level *)context)->heightmap = byte_array; return; } if (name.compare("BlockLight") == 0) { ((Level *)context)->blocklight = byte_array; return; } } void error_handler(void *context, size_t where, const char *why) { ((Level *)context)->grammar_error = true; ((Level *)context)->grammar_error_where = where; ((Level *)context)->grammar_error_why = why; } Level::~Level(){ if (!ignore_blocks && islevel) { delete blocks; delete skylight; delete heightmap; delete blocklight; } } Level::Level(const char *path, bool ignore_blocks) : path(path), ignore_blocks(ignore_blocks) { xPos = 0; zPos = 0; islevel = false; grammar_error = false; nbt::Parser parser(this); if (!ignore_blocks) { parser.register_byte_array = register_byte_array; } parser.register_int = register_int; parser.begin_compound = begin_compound; parser.error_handler = error_handler; try { parser.parse_file(path); } catch(nbt::bad_grammar &bg) { grammar_error = true; } } /** * Blocks[ z + ( y * ChunkSizeY(=128) + ( x * ChunkSizeY(=128) * ChunkSizeZ(=16) ) ) ]; */ nbt::Byte bget(nbt::ByteArray *blocks, int x, int z, int y) { assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); assert (p >= 0 && p < blocks->length); return blocks->values[p]; } nbt::Byte bsget(nbt::ByteArray *skylight, int x, int z, int y) { assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); int ap = p / 2; assert (ap >= 0 && ap < skylight->length); // force unsigned uint8_t bp = skylight->values[ap] & 0xff; if (p % 2 == 0) { return bp >> 4; } else { return bp & 0xf; } } void transform_xz(settings_t *s, int &x, int &z) { /*if (s->flip) { int t = x; x = z; z = mc::MapZ - t - 1; } if (s->invert) { z = mc::MapZ - z - 1; x = mc::MapX - x - 1; }*/ } inline void apply_shading(settings_t *s, int bl, int sl, int hm, int y, Color &c) { // if night, darken all colors not emitting light if (s->night) { c.darken((0xd0 * (16 - bl)) / 16); } c.darken((mc::MapY - y)); c.darken(sl); } inline bool cavemode_isopen(int bt) { switch(bt) { case mc::Air: return true; case mc::Leaves: return true; default: return false; } } inline bool cavemode_ignore_block(settings_t *s, int x, int z, int y, int bt, nbt::ByteArray *blocks, bool &cave_initial) { if (cave_initial) { if (!cavemode_isopen(bt)) { cave_initial = false; return true; } return true; } if (!cavemode_isopen(bt)) { if (y < s->top && cavemode_isopen(bget(blocks, x, z, y + 1))) { return false; } } return true; } class BlockRotation { private: settings_t *s; nbt::ByteArray *byte_array; void transform_xzy(int& x, int& z, int& y) { switch (s->rotation) { case 270: z = mc::MapZ - z - 1; x = mc::MapX - x - 1; { int t = x; x = z; z = mc::MapZ - t - 1; } break; case 180: z = mc::MapZ - z - 1; x = mc::MapX - x - 1; break; case 90: { int t = x; x = z; z = mc::MapZ - t - 1; } break; }; } public: BlockRotation(settings_t *s, nbt::ByteArray *byte_array) : s(s), byte_array(byte_array) {} uint8_t get8(int x, int z, int y) { transform_xzy(x, z, y); assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); assert (p >= 0 && p < byte_array->length); return byte_array->values[p]; } uint8_t get4(int x, int z, int y) { transform_xzy(x, z, y); assert(x >= 0 && x < mc::MapX); assert(z >= 0 && z < mc::MapZ); assert(y >= 0 && y < mc::MapY); int p = y + (z * mc::MapY + (x * mc::MapY * mc::MapZ)); int ap = p / 2; assert (ap >= 0 && ap < byte_array->length); // force unsigned uint8_t bp = byte_array->values[ap] & 0xff; if (p % 2 == 0) { return bp >> 4; } else { return bp & 0xf; } } }; ImageBuffer *Level::get_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX, mc::MapZ, 1); if (!islevel) { return img; } img->set_reversed(true); // block type int bt; for (int x = 0, mz = mc::MapZ - 1; x < mc::MapX; x++, mz--) { for (int y = 0, mx = 0; y < mc::MapX; y++, mx++) { Color base(255, 255, 255, 0); bt = mc::Air; bool cave_initial = true; int my; BlockRotation blocks_r(s, blocks); BlockRotation blocklight_r(s, blocklight); BlockRotation skylight_r(s, skylight); // do incremental color fill until color is opaque for (my = s->top; my > s->bottom; my--) { bt = blocks_r.get8(mx, mz, my); if (s->cavemode && cavemode_ignore_block(s, mx, mz, my, bt, blocks, cave_initial)) { continue; } if (s->excludes[bt]) { continue; } Color bc(mc::MaterialColor[bt]); int bl = blocklight_r.get4(mx, mz, my); int sl = skylight_r.get4(mx, mz, my); apply_shading(s, bl, sl, 0, my, bc); base.underlay(bc); if (base.is_opaque()) { break; } } if (base.is_transparent()) { continue; } img->set_pixel(x, y, 0, base); } } return img; } ImageBuffer *Level::get_oblique_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX, mc::MapZ + mc::MapY, mc::MapY + mc::MapZ); if (!islevel) { return img; } Cube c(mc::MapX, mc::MapY, mc::MapZ); // block type int bt; BlockRotation blocks_r(s, blocks); BlockRotation blocklight_r(s, blocklight); BlockRotation skylight_r(s, skylight); for (int x = 0, mz = mc::MapZ - 1; x < mc::MapX; x++, mz--) { for (int y = 0, mx = 0; y < mc::MapX; y++, mx++) { bool cave_initial = true; int cavemode_top = s->top; if (s->cavemode) { for (int my = s->top; my > 0; my--) { bt = blocks_r.get8(mx, mz, y); if (!cavemode_isopen(bt)) { cavemode_top = my; break; } } } for (int my = s->bottom; my < s->top; my++) { point p(x, my, y); bt = blocks_r.get8(mx, mz, my); if (s->cavemode) { if (cavemode_ignore_block(s, mx, mz, my, bt, blocks, cave_initial) || my >= cavemode_top) { continue; } } if (s->excludes[bt]) { continue; } int bl = blocklight_r.get4(mx, mz, my); int sl = skylight_r.get4(mx, mz, my); int _px, _py; c.project_oblique(p, _px, _py); Color top(mc::MaterialColor[bt]); apply_shading(s, bl, sl, 0, my, top); img->add_pixel(_px, _py - 1, top); Color side(mc::MaterialSideColor[bt]); apply_shading(s, bl, sl, 0, my, side); img->add_pixel(_px, _py, side); } } } return img; } ImageBuffer *Level::get_obliqueangle_image(settings_t *s) { ImageBuffer *img = new ImageBuffer(mc::MapX * 2 + 1, mc::MapX + mc::MapY + mc::MapZ, mc::MapY + mc::MapZ * 2); if (!islevel) { return img; } Cube c(mc::MapX, mc::MapY, mc::MapZ); // block type int bt; BlockRotation blocks_r(s, blocks); BlockRotation blocklight_r(s, blocklight); BlockRotation skylight_r(s, skylight); for (int z = 0; z < c.z; z++) { for (int x = 0; x < c.x; x++) { bool cave_initial = true; int cavemode_top = s->top; if (s->cavemode) { for (int y = s->top; y > 0; y--) { int _x = x, _z = z; transform_xz(s, _x, _z); bt = blocks_r.get8(_x, _z, y); if (!cavemode_isopen(bt)) { cavemode_top = y; break; } } } for (int y = s->bottom; y < s->top; y++) { point p(x, y, z); int _x = x, _z = z; transform_xz(s, _x, _z); bt = blocks_r.get8(_x, _z, y); if (s->cavemode) { if (cavemode_ignore_block(s, _x, _z, y, bt, blocks, cave_initial) || y >= cavemode_top) { continue; } } if (s->excludes[bt]) { continue; } int bl = skylight_r.get4(_x, _z, y); int sl = blocklight_r.get4(_x, _z, y); int _px, _py; c.project_obliqueangle(p, _px, _py); Color top(mc::MaterialColor[bt]); apply_shading(s, bl, sl, 0, y, top); Color side(mc::MaterialSideColor[bt]); apply_shading(s, bl, sl, 0, y, side); switch(mc::MaterialModes[bt]) { case mc::Block: img->add_pixel(_px, _py - 1, top); img->add_pixel(_px + 1, _py - 1, top); img->add_pixel(_px, _py, side); img->add_pixel(_px + 1, _py, side); break; case mc::HalfBlock: img->add_pixel(_px, _py, top); img->add_pixel(_px + 1, _py, top); break; } } } } return img; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsVBComment(Accessor &styler, int pos, int len) { return len>0 && styler[pos]=='\''; } inline bool IsTypeCharacter(const int ch) { return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; } inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_B_OPERATOR) { sc.SetState(SCE_B_DEFAULT); } else if (sc.state == SCE_B_KEYWORD) { if (!IsAWordChar(sc.ch)) { if (vbScriptSyntax || !IsTypeCharacter(sc.ch)) { if (sc.ch == ']') sc.Forward(); char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_B_COMMENT); if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else { sc.SetState(SCE_B_DEFAULT); } } else { sc.ChangeState(SCE_B_IDENTIFIER); sc.SetState(SCE_B_DEFAULT); } } } } else if (sc.state == SCE_B_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_STRING) { // VB doubles quotes to preserve them, so just end this string // state now as a following quote will start again if (sc.ch == '\"') { if (tolower(sc.chNext) == 'c') { sc.Forward(); } sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_PREPROCESSOR) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_DATE) { if (sc.ch == '#') { sc.ForwardSetState(SCE_B_DEFAULT); } } if (sc.state == SCE_B_DEFAULT) { if (sc.ch == '\'') { sc.SetState(SCE_B_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_B_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_B_PREPROCESSOR); } else if (sc.ch == '#') { int n = 1; int chSeek = ' '; while (chSeek == ' ' || chSeek == '\t') { chSeek = sc.GetRelative(n); n++; } if (IsADigit(chSeek)) { sc.SetState(SCE_B_DATE); } else { sc.SetState(SCE_B_OPERATOR); } } else if (sc.ch == '&' && tolower(sc.chNext) == 'h') { sc.SetState(SCE_B_NUMBER); } else if (sc.ch == '&' && tolower(sc.chNext) == 'o') { sc.SetState(SCE_B_NUMBER); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_B_NUMBER); } else if (IsAWordStart(sc.ch) || (sc.ch == '[')) { sc.SetState(SCE_B_KEYWORD); } else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) { sc.SetState(SCE_B_OPERATOR); } } if (sc.atLineEnd) { visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldVBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { int endPos = startPos + length; // Backtrack to previous line in case need to fix its fold status int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); } } int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); char chNext = styler[startPos]; for (int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false); } static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true); } LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc); LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc); <commit_msg>Made file handle constants in statements such as "close #1" work by styling them in the date literal style.<commit_after>// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsVBComment(Accessor &styler, int pos, int len) { return len>0 && styler[pos]=='\''; } inline bool IsTypeCharacter(const int ch) { return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; } inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool IsADateCharacter(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '|' || ch == '-' || ch == '/' || ch == ':' || ch == ' ' || ch == '\t'); } static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_B_OPERATOR) { sc.SetState(SCE_B_DEFAULT); } else if (sc.state == SCE_B_KEYWORD) { if (!IsAWordChar(sc.ch)) { if (vbScriptSyntax || !IsTypeCharacter(sc.ch)) { if (sc.ch == ']') sc.Forward(); char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_B_COMMENT); if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else { sc.SetState(SCE_B_DEFAULT); } } else { sc.ChangeState(SCE_B_IDENTIFIER); sc.SetState(SCE_B_DEFAULT); } } } } else if (sc.state == SCE_B_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_STRING) { // VB doubles quotes to preserve them, so just end this string // state now as a following quote will start again if (sc.ch == '\"') { if (tolower(sc.chNext) == 'c') { sc.Forward(); } sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_PREPROCESSOR) { if (sc.atLineEnd) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_DATE) { if (sc.ch == '#' || !IsADateCharacter(sc.chNext)) { sc.ForwardSetState(SCE_B_DEFAULT); } } if (sc.state == SCE_B_DEFAULT) { if (sc.ch == '\'') { sc.SetState(SCE_B_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_B_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_B_PREPROCESSOR); } else if (sc.ch == '#') { int n = 1; int chSeek = ' '; while (chSeek == ' ' || chSeek == '\t') { chSeek = sc.GetRelative(n); n++; } if (IsADigit(chSeek)) { sc.SetState(SCE_B_DATE); } else { sc.SetState(SCE_B_OPERATOR); } } else if (sc.ch == '&' && tolower(sc.chNext) == 'h') { sc.SetState(SCE_B_NUMBER); } else if (sc.ch == '&' && tolower(sc.chNext) == 'o') { sc.SetState(SCE_B_NUMBER); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_B_NUMBER); } else if (IsAWordStart(sc.ch) || (sc.ch == '[')) { sc.SetState(SCE_B_KEYWORD); } else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) { sc.SetState(SCE_B_OPERATOR); } } if (sc.atLineEnd) { visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldVBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { int endPos = startPos + length; // Backtrack to previous line in case need to fix its fold status int lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); } } int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); char chNext = styler[startPos]; for (int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { int lev = indentCurrent; int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false); } static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true); } LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc); LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc); <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 9:04:32 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << 0 << endl; exit(0); } int main() { ll N; vector<ll> D(N); for (auto i = 0; i < N; i++) { cin >> D[i]; } vector<ll> A(N, 0LL); if (D[0] != 0) { No(); } A[0] = 1; for (auto i = 1; i < N; i++) { if (D[i] == 0) { No(); } A[D[i]]++; } mint ans{1LL}; ll sum{1LL}; for (auto i = 1; i < N; i++) { ans *= mint{A[i - 1]}.power(A[i]); sum += A[i]; if (sum == N) { break; } } cout << ans << endl; }<commit_msg>submit B.cpp to 'B - Counting of Trees' (nikkei2019-2-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 9:04:32 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << 0 << endl; exit(0); } int main() { ll N; cin >> N; vector<ll> D(N); for (auto i = 0; i < N; i++) { cin >> D[i]; } vector<ll> A(N, 0LL); if (D[0] != 0) { No(); } A[0] = 1; for (auto i = 1; i < N; i++) { if (D[i] == 0) { No(); } A[D[i]]++; } mint ans{1LL}; ll sum{1LL}; for (auto i = 1; i < N; i++) { ans *= mint{A[i - 1]}.power(A[i]); sum += A[i]; if (sum == N) { break; } } cout << ans << endl; }<|endoftext|>
<commit_before><commit_msg>Fix invalid string access<commit_after><|endoftext|>
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <getopt.h> #include "server.h" #include "logger.h" #include "libconfig.h++" #include "initConfig.h" #include "singletonConfig.h" #include "watcherd.h" using namespace std; using namespace watcher; using namespace libconfig; option Options[] = { { "help", 0, NULL, 'h' }, { "config", 1, NULL, 'c' }, { "read-only", 1, NULL, 'r' }, { 0, 0, NULL, 0 } }; void usage(const char *progName, bool exitp) { cout << "Usage: " << basename(progName) << " [-c config filename]" << endl; cout << "Args: " << endl; cout << " -h, show this messsage and exit." << endl; cout << " -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl; cout << " -r, --read-only - do not write events to the database." << endl; cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl; if (exitp) exit(EXIT_FAILURE); } DECLARE_GLOBAL_LOGGER("watcherdMain"); int main(int argc, char* argv[]) { TRACE_ENTER(); int i; bool readOnly = false; while ((i = getopt_long(argc, argv, "hc:r", Options, NULL)) != -1) { switch (i) { case 'c': //handled below break; case 'r': readOnly = true; break; default: usage(argv[0], true); } } string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); string address("glory"); string port("8095"); size_t numThreads=8; std::string dbPath("event.db"); if (!config.lookupValue("server", address)) { LOG_INFO("'server' not found in the configuration file, using default: " << address << " and adding this to the configuration file."); config.getRoot().add("server", libconfig::Setting::TypeString) = address; } if (!config.lookupValue("port", port)) { LOG_INFO("'port' not found in the configuration file, using default: " << port << " and adding this to the configuration file."); config.getRoot().add("port", libconfig::Setting::TypeString)=port; } if (!config.lookupValue("serverThreadNum", numThreads)) { LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads << " and adding this to the configuration file."); config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads); } if (!config.lookupValue("databasePath", dbPath)) { LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath << " and adding this to the configuration file."); config.getRoot().add("databasePath", libconfig::Setting::TypeString)=dbPath; } WatcherdPtr theWatcherDaemon(new Watcherd(readOnly)); try { theWatcherDaemon->run(address, port, (int)numThreads); } catch (std::exception &e) { LOG_FATAL("Caught exception in main(): " << e.what()); std::cerr << "exception: " << e.what() << "\n"; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <commit_msg>allow -d database on the command line in the watcherd. command line overrides cfg files settings. This makes it faster to switch between playing back different event database.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <getopt.h> #include "server.h" #include "logger.h" #include "libconfig.h++" #include "initConfig.h" #include "singletonConfig.h" #include "watcherd.h" using namespace std; using namespace watcher; using namespace libconfig; option Options[] = { { "help", 0, NULL, 'h' }, { "config", 1, NULL, 'c' }, { "database", 1, NULL, 'd' }, { "read-only", 1, NULL, 'r' }, { 0, 0, NULL, 0 } }; void usage(const char *progName, bool exitp) { cout << "Usage: " << basename(progName) << " [-c config filename]" << endl; cout << "Args: " << endl; cout << " -h, show this messsage and exit." << endl; cout << " -d database, use this event database when running watcherd" << endl; cout << " -c configfile - If not given a filename of the form \""<< basename(progName) << ".cfg\" is assumed." << endl; cout << " -r, --read-only - do not write events to the database." << endl; cout << "If a configuration file is not found on startup, a default one will be created, used, and saved on program exit." << endl; if (exitp) exit(EXIT_FAILURE); } DECLARE_GLOBAL_LOGGER("watcherdMain"); int main(int argc, char* argv[]) { TRACE_ENTER(); int i; bool readOnly = false; std::string dbPath; while ((i = getopt_long(argc, argv, "hc:d:r", Options, NULL)) != -1) { switch (i) { case 'c': //handled below break; case 'r': readOnly = true; break; case 'd': dbPath=string(optarg); break; default: usage(argv[0], true); } } string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); string address("glory"); string port("8095"); size_t numThreads=8; if (!config.lookupValue("server", address)) { LOG_INFO("'server' not found in the configuration file, using default: " << address << " and adding this to the configuration file."); config.getRoot().add("server", libconfig::Setting::TypeString) = address; } if (!config.lookupValue("port", port)) { LOG_INFO("'port' not found in the configuration file, using default: " << port << " and adding this to the configuration file."); config.getRoot().add("port", libconfig::Setting::TypeString)=port; } if (!config.lookupValue("serverThreadNum", numThreads)) { LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads << " and adding this to the configuration file."); config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads); } std::string tmpDBPath("event.db"); if (!config.lookupValue("databasePath", tmpDBPath)) { LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath << " and adding this to the configuration file."); config.getRoot().add("databasePath", libconfig::Setting::TypeString)=tmpDBPath; } if (dbPath.size()) config.getRoot()["databasePath"]=dbPath; WatcherdPtr theWatcherDaemon(new Watcherd(readOnly)); try { theWatcherDaemon->run(address, port, (int)numThreads); } catch (std::exception &e) { LOG_FATAL("Caught exception in main(): " << e.what()); std::cerr << "exception: " << e.what() << "\n"; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <|endoftext|>
<commit_before>/// /// @file P2.cpp /// @brief 2nd partial sieve function. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <ptypes.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace P2 { /// @return previous_prime or -1 if old <= 2 inline int64_t get_previous_prime(primesieve::iterator* iter, int64_t old) { return (old > 2) ? iter->previous_prime() : -1; } /// For each prime calculate its first multiple >= low vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<int32_t>& primes) { vector<int64_t> next; next.reserve(size); next.push_back(0); for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ceil_div(low, prime) * prime; next_multiple += prime * (~next_multiple & 1); next_multiple = max(prime * prime, next_multiple); next.push_back(next_multiple); } return next; } template <typename T> T P2_thread(T x, int64_t y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, int64_t& pix, int64_t& pix_count, vector<int32_t>& primes) { pix = 0; pix_count = 0; low += thread_num * segments_per_thread * segment_size; limit = min(low + segments_per_thread * segment_size, limit); int64_t size = pi_bsearch(primes, isqrt(limit)) + 1; int64_t start = (int64_t) max((int64_t) (x / limit + 1), y); int64_t stop = (int64_t) min(x / low, isqrt(x)); T P2_thread = 0; // P2_thread = \sum_{i=pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1) // We use a reverse prime iterator to calculate P2_thread primesieve::iterator iter(stop + 1, start); int64_t previous_prime = get_previous_prime(&iter, stop + 1); int64_t xp = (int64_t) (x / previous_prime); vector<int64_t> next = generate_next_multiples(low, size, primes); BitSieve sieve(segment_size); // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { // current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t sqrt = isqrt(high - 1); int64_t j = 0; sieve.memset(low); // cross-off multiples for (int64_t i = 2; i < size && primes[i] <= sqrt; i++) { int64_t k; int64_t p2 = primes[i] * 2; for (k = next[i]; k < high; k += p2) sieve.unset(k - low); next[i] = k; } while (previous_prime >= start && xp < high) { pix += sieve.count(j, xp - low); j = xp - low + 1; pix_count++; P2_thread += pix; previous_prime = get_previous_prime(&iter, previous_prime); xp = (int64_t) (x / previous_prime); } pix += sieve.count(j, (high - 1) - low); } return P2_thread; } /// 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime, a = pi(y). /// Space complexity: O((x / y)^(1/2)). /// template <typename T> T P2(T x, int64_t y, int threads) { T a = pi_legendre(y, 1); T b = pi_legendre((int64_t) isqrt(x), 1); if (x < 4 || a >= b) return 0; if (print_status()) { cout << endl; cout << "=== P2(x, y) ===" << endl; cout << "Computation of the 2nd partial sieve function" << endl; } double time = get_wtime(); int64_t low = 2; int64_t limit = (int64_t)(x / max<int64_t>(1, y)); int64_t segment_size = max<int64_t>(1 << 12, isqrt(limit)); int64_t segments_per_thread = 1; threads = validate_threads(threads, limit); vector<int32_t> primes = generate_primes(isqrt(limit)); aligned_vector<int64_t> pix(threads); aligned_vector<int64_t> pix_counts(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1) // initialize with \sum_{i=a+1}^{b} -i + 1 T sum = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; T pix_total = 0; while (low < limit) { int64_t segments = ceil_div(limit - low, segment_size); threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads)); double seconds = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: sum) for (int i = 0; i < threads; i++) sum += P2_thread(x, y, segment_size, segments_per_thread, i, low, limit, pix[i], pix_counts[i], primes); low += segments_per_thread * threads * segment_size; seconds = get_wtime() - seconds; // Add missing sum contributions in order for (int i = 0; i < threads; i++) { sum += pix_total * pix_counts[i]; pix_total += pix[i]; } // Adjust thread load balancing if (seconds < 10) segments_per_thread *= 2; else if (seconds > 30 && segments_per_thread > 1) segments_per_thread /= 2; if (print_status()) cout << "\rStatus: " << get_percent(low, limit) << '%' << flush; } if (print_status()) print_result("P2", sum, time); return sum; } } // namespace P2 } // namespace namespace primecount { int64_t P2(int64_t x, int64_t y, int threads) { return P2::P2(x, y, threads); } #ifdef HAVE_INT128_T int128_t P2(int128_t x, int64_t y, int threads) { return P2::P2(x, y, threads); } #endif /// 2nd partial sieve function. /// P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. This implementation is /// optimized for small values of a < pi(x^(1/3)) which requires /// sieving up to a large limit (x / primes[a]). Sieving is done in /// parallel using primesieve (segmented sieve of Eratosthenes). /// Space complexity: O(pi(sqrt(x))). /// int64_t P2_lehmer(int64_t x, int64_t a, int threads) { if (print_status()) { cout << endl; cout << "=== P2_lehmer(x, a) ===" << endl; cout << "Computation of the 2nd partial sieve function" << endl; } double time = get_wtime(); vector<int32_t> primes = generate_primes(isqrt(x)); vector<int64_t> counts(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; #pragma omp parallel for num_threads(validate_threads(threads)) schedule(dynamic) for (int64_t i = b; i > a; i--) { int64_t prev = (i == b) ? 0 : x / primes[i + 1] + 1; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } if (print_status()) print_result("P2", sum, time); return sum; } } // namespace primecount <commit_msg>Improved P2 load balancer<commit_after>/// /// @file P2.cpp /// @brief 2nd partial sieve function. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <ptypes.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace P2 { /// @return previous_prime or -1 if old <= 2 inline int64_t get_previous_prime(primesieve::iterator* iter, int64_t old) { return (old > 2) ? iter->previous_prime() : -1; } /// For each prime calculate its first multiple >= low vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<int32_t>& primes) { vector<int64_t> next; next.reserve(size); next.push_back(0); for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ceil_div(low, prime) * prime; next_multiple += prime * (~next_multiple & 1); next_multiple = max(prime * prime, next_multiple); next.push_back(next_multiple); } return next; } template <typename T> T P2_thread(T x, int64_t y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, int64_t& pix, int64_t& pix_count, vector<int32_t>& primes) { pix = 0; pix_count = 0; low += thread_num * segments_per_thread * segment_size; limit = min(low + segments_per_thread * segment_size, limit); int64_t size = pi_bsearch(primes, isqrt(limit)) + 1; int64_t start = (int64_t) max((int64_t) (x / limit + 1), y); int64_t stop = (int64_t) min(x / low, isqrt(x)); T P2_thread = 0; // P2_thread = \sum_{i=pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1) // We use a reverse prime iterator to calculate P2_thread primesieve::iterator iter(stop + 1, start); int64_t previous_prime = get_previous_prime(&iter, stop + 1); int64_t xp = (int64_t) (x / previous_prime); vector<int64_t> next = generate_next_multiples(low, size, primes); BitSieve sieve(segment_size); // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { // current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t sqrt = isqrt(high - 1); int64_t j = 0; sieve.memset(low); // cross-off multiples for (int64_t i = 2; i < size && primes[i] <= sqrt; i++) { int64_t k; int64_t p2 = primes[i] * 2; for (k = next[i]; k < high; k += p2) sieve.unset(k - low); next[i] = k; } while (previous_prime >= start && xp < high) { pix += sieve.count(j, xp - low); j = xp - low + 1; pix_count++; P2_thread += pix; previous_prime = get_previous_prime(&iter, previous_prime); xp = (int64_t) (x / previous_prime); } pix += sieve.count(j, (high - 1) - low); } return P2_thread; } void balanceLoad(int64_t* segments_per_thread, double seconds1, double time1) { double time2 = get_wtime(); double seconds = time2 - seconds1; double time = time2 - time1; double increase_threshold = in_between(0.3, time / 100, 20); if (seconds < increase_threshold) *segments_per_thread += *segments_per_thread * 3; else if (*segments_per_thread >= 4) *segments_per_thread -= *segments_per_thread / 4; } /// 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime, a = pi(y). /// Space complexity: O((x / y)^(1/2)). /// template <typename T> T P2(T x, int64_t y, int threads) { T a = pi_legendre(y, 1); T b = pi_legendre((int64_t) isqrt(x), 1); if (x < 4 || a >= b) return 0; if (print_status()) { cout << endl; cout << "=== P2(x, y) ===" << endl; cout << "Computation of the 2nd partial sieve function" << endl; } double time = get_wtime(); int64_t low = 2; int64_t limit = (int64_t)(x / max<int64_t>(1, y)); int64_t segment_size = max<int64_t>(1 << 12, isqrt(limit)); int64_t segments_per_thread = 1; threads = validate_threads(threads, limit); vector<int32_t> primes = generate_primes(isqrt(limit)); aligned_vector<int64_t> pix(threads); aligned_vector<int64_t> pix_counts(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1) // initialize with \sum_{i=a+1}^{b} -i + 1 T sum = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; T pix_total = 0; while (low < limit) { int64_t segments = ceil_div(limit - low, segment_size); threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads)); double seconds = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: sum) for (int i = 0; i < threads; i++) sum += P2_thread(x, y, segment_size, segments_per_thread, i, low, limit, pix[i], pix_counts[i], primes); low += segments_per_thread * threads * segment_size; balanceLoad(&segments_per_thread, seconds, time); // Add missing sum contributions in order for (int i = 0; i < threads; i++) { sum += pix_total * pix_counts[i]; pix_total += pix[i]; } if (print_status()) cout << "\rStatus: " << get_percent(low, limit) << '%' << flush; } if (print_status()) print_result("P2", sum, time); return sum; } } // namespace P2 } // namespace namespace primecount { int64_t P2(int64_t x, int64_t y, int threads) { return P2::P2(x, y, threads); } #ifdef HAVE_INT128_T int128_t P2(int128_t x, int64_t y, int threads) { return P2::P2(x, y, threads); } #endif /// 2nd partial sieve function. /// P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. This implementation is /// optimized for small values of a < pi(x^(1/3)) which requires /// sieving up to a large limit (x / primes[a]). Sieving is done in /// parallel using primesieve (segmented sieve of Eratosthenes). /// Space complexity: O(pi(sqrt(x))). /// int64_t P2_lehmer(int64_t x, int64_t a, int threads) { if (print_status()) { cout << endl; cout << "=== P2_lehmer(x, a) ===" << endl; cout << "Computation of the 2nd partial sieve function" << endl; } double time = get_wtime(); vector<int32_t> primes = generate_primes(isqrt(x)); vector<int64_t> counts(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; #pragma omp parallel for num_threads(validate_threads(threads)) schedule(dynamic) for (int64_t i = b; i > a; i--) { int64_t prev = (i == b) ? 0 : x / primes[i + 1] + 1; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } if (print_status()) print_result("P2", sum, time); return sum; } } // namespace primecount <|endoftext|>
<commit_before>/******************************** ** Tsunagari Tile Engine ** ** file-type.cpp ** ** Copyright 2016 Paul Merrill ** ********************************/ // ********** // 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 "pack/file-type.h" #include <string> static const std::string textExtensions[] = { ".json" }; static const std::string mediaExtensions[] = { ".oga", ".png" }; FileType determineFileType(const std::string& path) { auto dot = path.rfind('.'); std::string extension = path.substr(dot); for (auto& textExtension : textExtensions) { if (extension == textExtension) { return FT_TEXT; } } for (auto& mediaExtension : mediaExtensions) { if (extension == mediaExtension) { return FT_MEDIA; } } return FT_UNKNOWN; } <commit_msg>pack/file-type: Fix out-of-bounds error<commit_after>/******************************** ** Tsunagari Tile Engine ** ** file-type.cpp ** ** Copyright 2016 Paul Merrill ** ********************************/ // ********** // 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 "pack/file-type.h" #include <string> static const std::string textExtensions[] = { ".json" }; static const std::string mediaExtensions[] = { ".oga", ".png" }; FileType determineFileType(const std::string& path) { auto dot = path.rfind('.'); if (dot == -1) { return FT_UNKNOWN; } std::string extension = path.substr(dot); for (auto& textExtension : textExtensions) { if (extension == textExtension) { return FT_TEXT; } } for (auto& mediaExtension : mediaExtensions) { if (extension == mediaExtension) { return FT_MEDIA; } } return FT_UNKNOWN; } <|endoftext|>
<commit_before>/// /// @file P2.cpp /// @brief 2nd partial sieve function. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <pi_bsearch.hpp> #include <pmath.hpp> #include <utils.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int64_t P2_thread(int64_t x, int64_t y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, int64_t& pix, int64_t& pix_count, vector<int32_t>& primes) { pix = 0; pix_count = 0; low += thread_num * segments_per_thread * segment_size; limit = min(low + segments_per_thread * segment_size, limit); int64_t size = pi_bsearch(primes, isqrt(limit)) + 1; int64_t P2_thread = 0; int64_t start = max(x / limit + 1, y); int64_t stop = in_between(2, x / low, isqrt(x)); vector<char> sieve(segment_size); vector<int64_t> pi_input; vector<int64_t> next; next.push_back(0); next.reserve(size); // P2_thread = \sum_{i=pi[start]}^{pi[stop]} pi(x / primes[i]) primesieve::generate_primes(start, stop, &pi_input); // reverse iterator auto iter = pi_input.rbegin(); auto rend = pi_input.rend(); for (size_t i = 0; i < pi_input.size(); i++) pi_input[i] = x / pi_input[i]; // initialize next multiples for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ((low + prime - 1) / prime) * prime; next_multiple = max(isquare(prime), next_multiple + (~next_multiple & 1) * prime); next.push_back(next_multiple); } // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { fill(sieve.begin(), sieve.end(), 1); // current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t sqrt = isqrt(high - 1); int64_t j = ~low & 1; // cross-off multiples for (int64_t i = 2; i < size && primes[i] <= sqrt; i++) { int64_t k; int64_t p2 = primes[i] * 2; for (k = next[i]; k < high; k += p2) sieve[k - low] = 0; next[i] = k; } for (; iter != rend && *iter < high; iter++) { for (int64_t xil = *iter - low; j <= xil; j += 2) pix += sieve[j]; // P2_thread += pi(x / primes[i]) P2_thread += pix; pix_count++; } for (; j < high - low; j += 2) pix += sieve[j]; } return P2_thread; } } // namespace namespace primecount { /// 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime, a = pi(y). /// Space complexity: O((x / y)^(1/2)). /// int64_t P2(int64_t x, int64_t y, int threads) { int64_t a = pi_legendre(y, 1); int64_t b = pi_legendre(isqrt(x), 1); if (x < 4 || a >= b) return 0; threads = validate_threads(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1) // initialize with \sum_{i=a+1}^{b} -i + 1 int64_t sum = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; int64_t pix_total = 1; int64_t low = 3; int64_t limit = (y > 0) ? x / y : x; int64_t sqrt_limit = isqrt(limit); int64_t min_segment_size = 64; int64_t segment_size = max(min_segment_size, sqrt_limit); int64_t segments_per_thread = 1; vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(sqrt_limit, &primes); vector<int64_t> pix_counts(threads); vector<int64_t> pix(threads); while (low < limit) { int64_t segments = (limit - low + segment_size - 1) / segment_size; threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads); double seconds = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: sum) for (int i = 0; i < threads; i++) sum += P2_thread(x, y, segment_size, segments_per_thread, i, low, limit, pix[i], pix_counts[i], primes); seconds = get_wtime() - seconds; low += segments_per_thread * threads * segment_size; // Adjust thread load balancing if (seconds < 10) segments_per_thread *= 2; else if (seconds > 30 && segments_per_thread > 1) segments_per_thread /= 2; // Add the missing sum contributions in order for (int i = 0; i < threads; i++) { sum += pix_total * pix_counts[i]; pix_total += pix[i]; } } return sum; } /// 2nd partial sieve function. /// P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. This implementation is /// optimized for small values of a < pi(x^(1/3)) which requires /// sieving up to a large limit (x / primes[a]). Sieving is done in /// parallel using primesieve (segmented sieve of Eratosthenes). /// Space complexity: O(pi(sqrt(x))). /// int64_t P2_lehmer(int64_t x, int64_t a, int threads) { vector<int32_t> primes; vector<int64_t> counts; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); counts.resize(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; #pragma omp parallel for num_threads(validate_threads(threads)) schedule(dynamic) for (int64_t i = b; i > a; i--) { int64_t prev = (i == b) ? 0 : x / primes[i + 1] + 1; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } return sum; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file P2.cpp /// @brief 2nd partial sieve function. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <pi_bsearch.hpp> #include <pmath.hpp> #include <utils.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int64_t P2_thread(int64_t x, int64_t y, int64_t segment_size, int64_t segments_per_thread, int64_t thread_num, int64_t low, int64_t limit, int64_t& pix, int64_t& pix_count, vector<int32_t>& primes) { pix = 0; pix_count = 0; low += thread_num * segments_per_thread * segment_size; limit = min(low + segments_per_thread * segment_size, limit); int64_t size = pi_bsearch(primes, isqrt(limit)) + 1; int64_t P2_thread = 0; int64_t start = max(x / limit + 1, y); int64_t stop = in_between(2, x / low, isqrt(x)); vector<char> sieve(segment_size); vector<int64_t> pi_input; vector<int64_t> next; next.push_back(0); next.reserve(size); // P2_thread = \sum_{i=pi[start]}^{pi[stop]} pi(x / primes[i]) primesieve::generate_primes(start, stop, &pi_input); // reverse iterator auto iter = pi_input.rbegin(); auto rend = pi_input.rend(); for (size_t i = 0; i < pi_input.size(); i++) pi_input[i] = x / pi_input[i]; // initialize next multiples for (int64_t b = 1; b < size; b++) { int64_t prime = primes[b]; int64_t next_multiple = ((low + prime - 1) / prime) * prime; next_multiple = max(isquare(prime), next_multiple + (~next_multiple & 1) * prime); next.push_back(next_multiple); } // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { fill(sieve.begin(), sieve.end(), 1); // current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t sqrt = isqrt(high - 1); int64_t j = ~low & 1; // cross-off multiples for (int64_t i = 2; i < size && primes[i] <= sqrt; i++) { int64_t k; int64_t p2 = primes[i] * 2; for (k = next[i]; k < high; k += p2) sieve[k - low] = 0; next[i] = k; } for (; iter != rend && *iter < high; iter++) { for (int64_t xi = *iter - low; j <= xi; j += 2) pix += sieve[j]; // P2_thread += pi(x / primes[i]) P2_thread += pix; pix_count++; } for (; j < high - low; j += 2) pix += sieve[j]; } return P2_thread; } } // namespace namespace primecount { /// 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime, a = pi(y). /// Space complexity: O((x / y)^(1/2)). /// int64_t P2(int64_t x, int64_t y, int threads) { int64_t a = pi_legendre(y, 1); int64_t b = pi_legendre(isqrt(x), 1); if (x < 4 || a >= b) return 0; threads = validate_threads(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1) // initialize with \sum_{i=a+1}^{b} -i + 1 int64_t sum = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; int64_t pix_total = 1; int64_t low = 3; int64_t limit = (y > 0) ? x / y : x; int64_t sqrt_limit = isqrt(limit); int64_t min_segment_size = 64; int64_t segment_size = max(min_segment_size, sqrt_limit); int64_t segments_per_thread = 1; vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(sqrt_limit, &primes); vector<int64_t> pix_counts(threads); vector<int64_t> pix(threads); while (low < limit) { int64_t segments = (limit - low + segment_size - 1) / segment_size; threads = in_between(1, threads, segments); segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads); double seconds = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: sum) for (int i = 0; i < threads; i++) sum += P2_thread(x, y, segment_size, segments_per_thread, i, low, limit, pix[i], pix_counts[i], primes); seconds = get_wtime() - seconds; low += segments_per_thread * threads * segment_size; // Adjust thread load balancing if (seconds < 10) segments_per_thread *= 2; else if (seconds > 30 && segments_per_thread > 1) segments_per_thread /= 2; // Add the missing sum contributions in order for (int i = 0; i < threads; i++) { sum += pix_total * pix_counts[i]; pix_total += pix[i]; } } return sum; } /// 2nd partial sieve function. /// P2_lehmer(x, a) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. This implementation is /// optimized for small values of a < pi(x^(1/3)) which requires /// sieving up to a large limit (x / primes[a]). Sieving is done in /// parallel using primesieve (segmented sieve of Eratosthenes). /// Space complexity: O(pi(sqrt(x))). /// int64_t P2_lehmer(int64_t x, int64_t a, int threads) { vector<int32_t> primes; vector<int64_t> counts; primes.push_back(0); primesieve::generate_primes(isqrt(x), &primes); counts.resize(primes.size()); int64_t b = pi_bsearch(primes, isqrt(x)); int64_t sum = 0; int64_t pix = 0; #pragma omp parallel for num_threads(validate_threads(threads)) schedule(dynamic) for (int64_t i = b; i > a; i--) { int64_t prev = (i == b) ? 0 : x / primes[i + 1] + 1; int64_t xi = x / primes[i]; counts[i] = primesieve::count_primes(prev, xi); } for (int64_t i = b; i > a; i--) { pix += counts[i]; sum += pix - (i - 1); } return sum; } } // namespace primecount <|endoftext|>
<commit_before>#include "archivewidget.h" WARNINGS_DISABLE #include <QAction> #include <QComboBox> #include <QCursor> #include <QDateTime> #include <QEvent> #include <QKeyEvent> #include <QKeySequence> #include <QLabel> #include <QMenu> #include <QModelIndex> #include <QModelIndexList> #include <QSortFilterProxyModel> #include <QStringList> #include <QTableView> #include <QVariant> #include <Qt> #include "ui_archivewidget.h" WARNINGS_ENABLE #include "TElidedLabel.h" #include "messages/archiverestoreoptions.h" #include "basetask.h" #include "elidedclickablelabel.h" #include "filetablemodel.h" #include "persistentmodel/archive.h" #include "restoredialog.h" #include "utils.h" #define EMPTY_TAR_ARCHIVE_BYTES 2000 ArchiveDetailsWidget::ArchiveDetailsWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::ArchiveDetailsWidget), _contentsModel(new FileTableModel(this)), _proxyModel(new QSortFilterProxyModel(_contentsModel)), _fileMenu(new QMenu(this)) { _ui->setupUi(this); updateUi(); // Set up filter UI. _ui->filterComboBox->hide(); _proxyModel->setDynamicSortFilter(false); _proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); _proxyModel->setSourceModel(_contentsModel); _ui->archiveContentsTableView->setModel(_proxyModel); _ui->archiveContentsTableView->setContextMenuPolicy(Qt::CustomContextMenu); // Set up other UI. _fileMenu->addAction(_ui->actionRestoreFiles); // Connections for UI functionality. connect(_ui->archiveContentsTableView, &QTableView::customContextMenuRequested, this, &ArchiveDetailsWidget::showContextMenu); connect(_ui->actionRestoreFiles, &QAction::triggered, this, &ArchiveDetailsWidget::restoreFiles); connect(_ui->archiveContentsTableView, &QTableView::activated, this, &ArchiveDetailsWidget::restoreFiles); connect(_ui->hideButton, &QPushButton::clicked, this, &ArchiveDetailsWidget::close); connect(_contentsModel, &FileTableModel::taskRequested, this, &ArchiveDetailsWidget::taskRequested); connect(_ui->archiveJobLabel, &ElidedClickableLabel::clicked, [this]() { emit jobClicked(_archive->jobRef()); }); // Connection to reset the model. connect(_contentsModel, &FileTableModel::modelReset, [this]() { _ui->archiveContentsTableView->resizeColumnsToContents(); _ui->archiveContentsLabel->setText( tr("Contents (%1)").arg(_contentsModel->rowCount())); }); // Connections for filtering connect(_ui->filterComboBox, &QComboBox::editTextChanged, _proxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(_ui->filterComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), [this]() { _ui->archiveContentsTableView->setFocus(); }); connect(_ui->filterButton, &QPushButton::toggled, [this](const bool checked) { _ui->filterComboBox->setVisible(checked); if(checked) _ui->filterComboBox->setFocus(); else _ui->filterComboBox->clearEditText(); }); } ArchiveDetailsWidget::~ArchiveDetailsWidget() { delete _proxyModel; delete _contentsModel; delete _ui; } void ArchiveDetailsWidget::setArchive(ArchivePtr archive) { // Remove previous connections (if applicable). if(_archive) { disconnect(_archive.data(), &Archive::changed, this, &ArchiveDetailsWidget::updateDetails); disconnect(_archive.data(), &Archive::purged, this, &ArchiveDetailsWidget::close); } // Store pointer. _archive = archive; // Set up new connections and refresh the display. if(_archive) { connect(_archive.data(), &Archive::changed, this, &ArchiveDetailsWidget::updateDetails); connect(_archive.data(), &Archive::purged, this, &ArchiveDetailsWidget::close); updateDetails(); } else { // No need to store info about the previous Archive. _contentsModel->reset(); } } void ArchiveDetailsWidget::updateDetails() { // Bail (if applicable). if(!_archive) return; { // Show basic archive info. _ui->archiveNameLabel->setText(_archive->name()); _ui->archiveDateLabel->setText( _archive->timestamp().toString(Qt::DefaultLocaleLongDate)); // Show info about a linked Job (if applicable). if(_archive->jobRef().isEmpty()) { _ui->archiveJobLabel->hide(); _ui->archiveJobLabelField->hide(); _ui->archiveIconLabel->setStyleSheet( "image: url(:/logos/tarsnap-icon-big.png)"); } else { _ui->archiveJobLabel->show(); _ui->archiveJobLabelField->show(); _ui->archiveJobLabel->setText(_archive->jobRef()); _ui->archiveIconLabel->setStyleSheet( "image: url(:/icons/hard-drive-big.png)"); } // Show size info about the archive. _ui->archiveSizeLabel->setText( Utils::humanBytes(_archive->sizeTotal())); _ui->archiveSizeLabel->setToolTip(_archive->archiveStats()); _ui->archiveUniqueDataLabel->setText( Utils::humanBytes(_archive->sizeUniqueCompressed())); _ui->archiveUniqueDataLabel->setToolTip(_archive->archiveStats()); // Show other info about the archive. _ui->archiveCommandLineEdit->setText(_archive->command()); _ui->archiveCommandLineEdit->setToolTip( _archive->command().prepend("<p>").append("</p>")); _ui->archiveCommandLineEdit->setCursorPosition(0); // Warn about partial archives. if(_archive->truncated()) { _ui->infoLabel->setText(tr("This archive is truncated," " data may be incomplete")); _ui->infoLabel->setToolTip(_archive->truncatedInfo()); _ui->infoLabel->show(); } else if(_archive->contents().isEmpty() && (_archive->sizeTotal() < EMPTY_TAR_ARCHIVE_BYTES)) { // Warn about a potentially empty archive. _ui->infoLabel->setText(tr("This archive looks empty," " no file data may be contained" " besides the TAR header")); _ui->infoLabel->show(); } else _ui->infoLabel->hide(); // Show files in the archive. _contentsModel->setArchive(_archive); } } void ArchiveDetailsWidget::closeEvent(QCloseEvent *event) { Q_UNUSED(event) setArchive(ArchivePtr()); // Release memory held by the contents widget emit hidden(); } void ArchiveDetailsWidget::keyPressEvent(QKeyEvent *event) { // Special handling for Escape with filtering. if((event->key() == Qt::Key_Escape) && _ui->filterComboBox->isVisible()) { if(_ui->filterComboBox->currentText().isEmpty()) { _ui->filterButton->toggle(); } else { _ui->filterComboBox->clearEditText(); _ui->filterComboBox->setFocus(); } } else { // Normal handling. QWidget::keyPressEvent(event); } } void ArchiveDetailsWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); updateDetails(); } QWidget::changeEvent(event); } void ArchiveDetailsWidget::showContextMenu() { _fileMenu->popup(QCursor::pos()); } void ArchiveDetailsWidget::restoreFiles() { // Get selected items, and bail if there's none. QModelIndexList indexes = _ui->archiveContentsTableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; // Convert items to filenames. QStringList files; for(const QModelIndex &index : indexes) files << index.data().toString(); // Launch RestoreDialog. RestoreDialog *restoreDialog = new RestoreDialog(this, _archive, files); restoreDialog->displayTarOption(false); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] { emit restoreArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } void ArchiveDetailsWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); _ui->filterButton->setToolTip(_ui->filterButton->toolTip().arg( _ui->filterButton->shortcut().toString(QKeySequence::NativeText))); } <commit_msg>ArchiveDetailsWidget: adjust for early bail<commit_after>#include "archivewidget.h" WARNINGS_DISABLE #include <QAction> #include <QComboBox> #include <QCursor> #include <QDateTime> #include <QEvent> #include <QKeyEvent> #include <QKeySequence> #include <QLabel> #include <QMenu> #include <QModelIndex> #include <QModelIndexList> #include <QSortFilterProxyModel> #include <QStringList> #include <QTableView> #include <QVariant> #include <Qt> #include "ui_archivewidget.h" WARNINGS_ENABLE #include "TElidedLabel.h" #include "messages/archiverestoreoptions.h" #include "basetask.h" #include "elidedclickablelabel.h" #include "filetablemodel.h" #include "persistentmodel/archive.h" #include "restoredialog.h" #include "utils.h" #define EMPTY_TAR_ARCHIVE_BYTES 2000 ArchiveDetailsWidget::ArchiveDetailsWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::ArchiveDetailsWidget), _contentsModel(new FileTableModel(this)), _proxyModel(new QSortFilterProxyModel(_contentsModel)), _fileMenu(new QMenu(this)) { _ui->setupUi(this); updateUi(); // Set up filter UI. _ui->filterComboBox->hide(); _proxyModel->setDynamicSortFilter(false); _proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); _proxyModel->setSourceModel(_contentsModel); _ui->archiveContentsTableView->setModel(_proxyModel); _ui->archiveContentsTableView->setContextMenuPolicy(Qt::CustomContextMenu); // Set up other UI. _fileMenu->addAction(_ui->actionRestoreFiles); // Connections for UI functionality. connect(_ui->archiveContentsTableView, &QTableView::customContextMenuRequested, this, &ArchiveDetailsWidget::showContextMenu); connect(_ui->actionRestoreFiles, &QAction::triggered, this, &ArchiveDetailsWidget::restoreFiles); connect(_ui->archiveContentsTableView, &QTableView::activated, this, &ArchiveDetailsWidget::restoreFiles); connect(_ui->hideButton, &QPushButton::clicked, this, &ArchiveDetailsWidget::close); connect(_contentsModel, &FileTableModel::taskRequested, this, &ArchiveDetailsWidget::taskRequested); connect(_ui->archiveJobLabel, &ElidedClickableLabel::clicked, [this]() { emit jobClicked(_archive->jobRef()); }); // Connection to reset the model. connect(_contentsModel, &FileTableModel::modelReset, [this]() { _ui->archiveContentsTableView->resizeColumnsToContents(); _ui->archiveContentsLabel->setText( tr("Contents (%1)").arg(_contentsModel->rowCount())); }); // Connections for filtering connect(_ui->filterComboBox, &QComboBox::editTextChanged, _proxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(_ui->filterComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), [this]() { _ui->archiveContentsTableView->setFocus(); }); connect(_ui->filterButton, &QPushButton::toggled, [this](const bool checked) { _ui->filterComboBox->setVisible(checked); if(checked) _ui->filterComboBox->setFocus(); else _ui->filterComboBox->clearEditText(); }); } ArchiveDetailsWidget::~ArchiveDetailsWidget() { delete _proxyModel; delete _contentsModel; delete _ui; } void ArchiveDetailsWidget::setArchive(ArchivePtr archive) { // Remove previous connections (if applicable). if(_archive) { disconnect(_archive.data(), &Archive::changed, this, &ArchiveDetailsWidget::updateDetails); disconnect(_archive.data(), &Archive::purged, this, &ArchiveDetailsWidget::close); } // Store pointer. _archive = archive; // Set up new connections and refresh the display. if(_archive) { connect(_archive.data(), &Archive::changed, this, &ArchiveDetailsWidget::updateDetails); connect(_archive.data(), &Archive::purged, this, &ArchiveDetailsWidget::close); updateDetails(); } else { // No need to store info about the previous Archive. _contentsModel->reset(); } } void ArchiveDetailsWidget::updateDetails() { // Bail (if applicable). if(!_archive) return; // Show basic archive info. _ui->archiveNameLabel->setText(_archive->name()); _ui->archiveDateLabel->setText( _archive->timestamp().toString(Qt::DefaultLocaleLongDate)); // Show info about a linked Job (if applicable). if(_archive->jobRef().isEmpty()) { _ui->archiveJobLabel->hide(); _ui->archiveJobLabelField->hide(); _ui->archiveIconLabel->setStyleSheet( "image: url(:/logos/tarsnap-icon-big.png)"); } else { _ui->archiveJobLabel->show(); _ui->archiveJobLabelField->show(); _ui->archiveJobLabel->setText(_archive->jobRef()); _ui->archiveIconLabel->setStyleSheet( "image: url(:/icons/hard-drive-big.png)"); } // Show size info about the archive. _ui->archiveSizeLabel->setText(Utils::humanBytes(_archive->sizeTotal())); _ui->archiveSizeLabel->setToolTip(_archive->archiveStats()); _ui->archiveUniqueDataLabel->setText( Utils::humanBytes(_archive->sizeUniqueCompressed())); _ui->archiveUniqueDataLabel->setToolTip(_archive->archiveStats()); // Show other info about the archive. _ui->archiveCommandLineEdit->setText(_archive->command()); _ui->archiveCommandLineEdit->setToolTip( _archive->command().prepend("<p>").append("</p>")); _ui->archiveCommandLineEdit->setCursorPosition(0); // Warn about partial archives. if(_archive->truncated()) { _ui->infoLabel->setText(tr("This archive is truncated," " data may be incomplete")); _ui->infoLabel->setToolTip(_archive->truncatedInfo()); _ui->infoLabel->show(); } else if(_archive->contents().isEmpty() && (_archive->sizeTotal() < EMPTY_TAR_ARCHIVE_BYTES)) { // Warn about a potentially empty archive. _ui->infoLabel->setText(tr("This archive looks empty," " no file data may be contained" " besides the TAR header")); _ui->infoLabel->show(); } else _ui->infoLabel->hide(); // Show files in the archive. _contentsModel->setArchive(_archive); } void ArchiveDetailsWidget::closeEvent(QCloseEvent *event) { Q_UNUSED(event) setArchive(ArchivePtr()); // Release memory held by the contents widget emit hidden(); } void ArchiveDetailsWidget::keyPressEvent(QKeyEvent *event) { // Special handling for Escape with filtering. if((event->key() == Qt::Key_Escape) && _ui->filterComboBox->isVisible()) { if(_ui->filterComboBox->currentText().isEmpty()) { _ui->filterButton->toggle(); } else { _ui->filterComboBox->clearEditText(); _ui->filterComboBox->setFocus(); } } else { // Normal handling. QWidget::keyPressEvent(event); } } void ArchiveDetailsWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); updateDetails(); } QWidget::changeEvent(event); } void ArchiveDetailsWidget::showContextMenu() { _fileMenu->popup(QCursor::pos()); } void ArchiveDetailsWidget::restoreFiles() { // Get selected items, and bail if there's none. QModelIndexList indexes = _ui->archiveContentsTableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; // Convert items to filenames. QStringList files; for(const QModelIndex &index : indexes) files << index.data().toString(); // Launch RestoreDialog. RestoreDialog *restoreDialog = new RestoreDialog(this, _archive, files); restoreDialog->displayTarOption(false); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] { emit restoreArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } void ArchiveDetailsWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); _ui->filterButton->setToolTip(_ui->filterButton->toolTip().arg( _ui->filterButton->shortcut().toString(QKeySequence::NativeText))); } <|endoftext|>
<commit_before>/* * predixy - A high performance and full features proxy for redis. * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com> * All rights reserved. */ #include <unistd.h> #include <signal.h> #include <time.h> #include <stdlib.h> #include <sys/types.h> #include <iostream> #include <thread> #include "Proxy.h" #include "Handler.h" #include "Socket.h" #include "Alloc.h" #include "ListenSocket.h" #include "AcceptSocket.h" #include "RequestParser.h" #include "Backtrace.h" static bool Running = false; static bool Abort = false; static bool Stop = false; static void abortHandler(int sig) { Abort = true; if (sig == SIGABRT) { traceInfo(); } if (!Running) { abort(); } } static void stopHandler(int sig) { Stop = true; if (!Running) { abort(); } } Proxy::Proxy(): mListener(nullptr), mDataCenter(nullptr), mServPool(nullptr), mStartTime(time(nullptr)), mStatsVer(0) { } Proxy::~Proxy() { for (auto h : mHandlers) { delete h; } delete mServPool; delete mDataCenter; delete mListener; delete mConf; } bool Proxy::init(int argc, char* argv[]) { signal(SIGPIPE, SIG_IGN); signal(SIGFPE, abortHandler); signal(SIGILL, abortHandler); signal(SIGSEGV, abortHandler); signal(SIGABRT, abortHandler); signal(SIGBUS, abortHandler); signal(SIGQUIT, abortHandler); signal(SIGHUP, abortHandler); signal(SIGINT, stopHandler); signal(SIGTERM, stopHandler); Command::init(); mConf = new Conf(); if (!mConf->init(argc, argv)) { return false; } Logger::gInst = new Logger(); Logger::gInst->setLogFile(mConf->log(), mConf->logRotateSecs(), mConf->logRotateBytes()); Logger::gInst->setAllowMissLog(mConf->allowMissLog()); for (int i = 0; i < LogLevel::Sentinel; ++i) { LogLevel::Type lvl = LogLevel::Type(i); Logger::gInst->setLogSample(lvl, mConf->logSample(lvl)); } Logger::gInst->start(); for (auto& ac : mConf->authConfs()) { mAuthority.add(ac); } if (!mConf->localDC().empty()) { mDataCenter = new DataCenter(); mDataCenter->init(mConf); } AllocBase::setMaxMemory(mConf->maxMemory()); if (mConf->bufSize() > 0) { Buffer::setSize(mConf->bufSize()); } mLatencyMonitorSet.init(mConf->latencyMonitors()); ListenSocket* s = new ListenSocket(mConf->bind(), SOCK_STREAM); if (!s->setNonBlock()) { logError("proxy listener set nonblock fail:%s", StrError()); Throw(InitFail, "listener set nonblock", StrError()); } s->listen(); mListener = s; logNotice("predixy listen in %s", mConf->bind()); switch (mConf->serverPoolType()) { case ServerPool::Cluster: { ClusterServerPool* p = new ClusterServerPool(this); p->init(mConf->clusterServerPool()); mServPool = p; } break; case ServerPool::Sentinel: { SentinelServerPool* p = new SentinelServerPool(this); p->init(mConf->sentinelServerPool()); mServPool = p; } break; default: Throw(InitFail, "unknown server pool type"); break; } for (int i = 0; i < mConf->workerThreads(); ++i) { Handler* h = new Handler(this); mHandlers.push_back(h); } return true; } int Proxy::run() { logNotice("predixy running with Name:%s Workers:%d", mConf->name(), (int)mHandlers.size()); std::vector<std::shared_ptr<std::thread>> tasks; for (auto h : mHandlers) { std::shared_ptr<std::thread> t(new std::thread([=](){h->run();})); tasks.push_back(t); } Running = true; bool stop = false; while (!stop) { if (Abort) { stop = true; abort(); } else if (Stop) { fprintf(stderr, "predixy will quit ASAP Bye!\n"); stop = true; } if (!stop) { sleep(1); TimerPoint::report(); } } for (auto h : mHandlers) { h->stop(); } for (auto t : tasks) { t->join(); } Logger::gInst->stop(); TimerPoint::report(); if (*mConf->bind() == '/') { unlink(mConf->bind()); } return 0; } <commit_msg>fix backtrace bug<commit_after>/* * predixy - A high performance and full features proxy for redis. * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com> * All rights reserved. */ #include <unistd.h> #include <signal.h> #include <time.h> #include <stdlib.h> #include <sys/types.h> #include <iostream> #include <thread> #include "Proxy.h" #include "Handler.h" #include "Socket.h" #include "Alloc.h" #include "ListenSocket.h" #include "AcceptSocket.h" #include "RequestParser.h" #include "Backtrace.h" static bool Running = false; static bool Abort = false; static bool Stop = false; static void abortHandler(int sig) { if (!Abort) { traceInfo(); } Abort = true; if (!Running) { abort(); } } static void stopHandler(int sig) { Stop = true; if (!Running) { abort(); } } Proxy::Proxy(): mListener(nullptr), mDataCenter(nullptr), mServPool(nullptr), mStartTime(time(nullptr)), mStatsVer(0) { } Proxy::~Proxy() { for (auto h : mHandlers) { delete h; } delete mServPool; delete mDataCenter; delete mListener; delete mConf; } bool Proxy::init(int argc, char* argv[]) { signal(SIGPIPE, SIG_IGN); signal(SIGFPE, abortHandler); signal(SIGILL, abortHandler); signal(SIGSEGV, abortHandler); signal(SIGABRT, abortHandler); signal(SIGBUS, abortHandler); signal(SIGQUIT, abortHandler); signal(SIGHUP, abortHandler); signal(SIGINT, stopHandler); signal(SIGTERM, stopHandler); Command::init(); mConf = new Conf(); if (!mConf->init(argc, argv)) { return false; } Logger::gInst = new Logger(); Logger::gInst->setLogFile(mConf->log(), mConf->logRotateSecs(), mConf->logRotateBytes()); Logger::gInst->setAllowMissLog(mConf->allowMissLog()); for (int i = 0; i < LogLevel::Sentinel; ++i) { LogLevel::Type lvl = LogLevel::Type(i); Logger::gInst->setLogSample(lvl, mConf->logSample(lvl)); } Logger::gInst->start(); for (auto& ac : mConf->authConfs()) { mAuthority.add(ac); } if (!mConf->localDC().empty()) { mDataCenter = new DataCenter(); mDataCenter->init(mConf); } AllocBase::setMaxMemory(mConf->maxMemory()); if (mConf->bufSize() > 0) { Buffer::setSize(mConf->bufSize()); } mLatencyMonitorSet.init(mConf->latencyMonitors()); ListenSocket* s = new ListenSocket(mConf->bind(), SOCK_STREAM); if (!s->setNonBlock()) { logError("proxy listener set nonblock fail:%s", StrError()); Throw(InitFail, "listener set nonblock", StrError()); } s->listen(); mListener = s; logNotice("predixy listen in %s", mConf->bind()); switch (mConf->serverPoolType()) { case ServerPool::Cluster: { ClusterServerPool* p = new ClusterServerPool(this); p->init(mConf->clusterServerPool()); mServPool = p; } break; case ServerPool::Sentinel: { SentinelServerPool* p = new SentinelServerPool(this); p->init(mConf->sentinelServerPool()); mServPool = p; } break; default: Throw(InitFail, "unknown server pool type"); break; } for (int i = 0; i < mConf->workerThreads(); ++i) { Handler* h = new Handler(this); mHandlers.push_back(h); } return true; } int Proxy::run() { logNotice("predixy running with Name:%s Workers:%d", mConf->name(), (int)mHandlers.size()); std::vector<std::shared_ptr<std::thread>> tasks; for (auto h : mHandlers) { std::shared_ptr<std::thread> t(new std::thread([=](){h->run();})); tasks.push_back(t); } Running = true; bool stop = false; while (!stop) { if (Abort) { stop = true; abort(); } else if (Stop) { fprintf(stderr, "predixy will quit ASAP Bye!\n"); stop = true; } if (!stop) { sleep(1); TimerPoint::report(); } } for (auto h : mHandlers) { h->stop(); } for (auto t : tasks) { t->join(); } Logger::gInst->stop(); TimerPoint::report(); if (*mConf->bind() == '/') { unlink(mConf->bind()); } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "pbge/exceptions/exceptions.h" #include "pbge/core/Manager.h" #include "pbge/gfx/Buffer.h" #include "pbge/gfx/Node.h" #include "pbge/gfx/Model.h" #include "pbge/gfx/Renderer.h" #include "pbge/gfx/TextureRendererFactory.h" #include "pbge/gfx/VBO.h" #include <GL/glew.h> #include <GL/glut.h> pbge::Node * root, * child; pbge::TransformationNode * cam_node; pbge::OpenGL * ogl = new pbge::OpenGL; pbge::Renderer renderer(ogl); pbge::SceneManager manager; pbge::Camera camera; pbge::OpenGL * gl; class UmModelo : public pbge::Model { public: UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) { vbo = _vbo; primitive = _primitive; } void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) { glEnable(GL_VERTEX_ARRAY); vbo->bind(ogl); glDrawArrays(primitive, 0, vbo->getNVertices()); vbo->unbind(ogl); glDisable(GL_VERTEX_ARRAY); } private: GLenum primitive; pbge::VertexBuffer * vbo; }; pbge::ModelInstance * vboModel = NULL; void display() { glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT); renderer.render(); GLenum error; while((error = glGetError()) != GL_NO_ERROR) { std::cout << gluErrorString(error) << std::endl; } glutSwapBuffers(); } void createNormalIndexes(std::vector<unsigned short> & ni) { unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4}; ni = std::vector<unsigned short>(indexes, indexes + 24); } std::vector<unsigned short> make(unsigned short * p, int n) { return std::vector<unsigned short>(p, p + n); } void createVertexIndexes(std::vector<unsigned short> & vi) { unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7}; vi = std::vector<unsigned short>(indexes, indexes + 24); } void createVBOInstance() { float v = 0.5f; std::vector<unsigned short> vIndexes; std::vector<unsigned short> nIndexes; createNormalIndexes(nIndexes); createVertexIndexes(vIndexes); pbge::VertexBufferBuilder builder(24); pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX); pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL); builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1); builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v); builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v); builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes); pbge::VertexBuffer * vbo = builder.done(); vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS)); } void setUp() { glewInit(); glEnable(GL_DEPTH_TEST); glClearColor(0,0,0,0); glColor3f(1,0,0); createVBOInstance(); pbge::TransformationNode * node = new pbge::TransformationNode; math3d::matrix44 m = math3d::identity44; root = new pbge::TransformationNode; cam_node = new pbge::TransformationNode; child = node; node->setTransformationMatrix(&m); root->addChild(child); root->addChild(cam_node); child->addModelInstance(vboModel); math3d::matrix44 cam_matrix = math3d::identity44; cam_matrix[2][3] = 8.0f; cam_node->setTransformationMatrix(&cam_matrix); camera.setParent(cam_node); camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1)); camera.frustum.setPerspective(30, 1, 0.1f, 10); manager.setSceneGraph(root); manager.addCamera(&camera); renderer.setScene(&manager); gl = pbge::Manager::getInstance()->getOpenGL(); } typedef unsigned short XXX; int main(int argc, char ** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE); glutInitWindowSize(500,500); glutCreateWindow("ahahah"); setUp(); glutDisplayFunc(display); glutMainLoop(); return 0; }<commit_msg>refactoring main_tester<commit_after>#include <iostream> #include "pbge/exceptions/exceptions.h" #include "pbge/core/Manager.h" #include "pbge/gfx/Buffer.h" #include "pbge/gfx/Node.h" #include "pbge/gfx/Model.h" #include "pbge/gfx/Renderer.h" #include "pbge/gfx/VBO.h" #include <GL/glew.h> #include <GL/glut.h> pbge::Node * root, * child; pbge::TransformationNode * cam_node; pbge::Renderer * renderer; pbge::SceneManager manager; pbge::Camera camera; class UmModelo : public pbge::Model { public: UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) { vbo = _vbo; primitive = _primitive; } void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) { glEnable(GL_VERTEX_ARRAY); vbo->bind(ogl); glDrawArrays(primitive, 0, vbo->getNVertices()); vbo->unbind(ogl); glDisable(GL_VERTEX_ARRAY); } private: GLenum primitive; pbge::VertexBuffer * vbo; }; pbge::ModelInstance * vboModel = NULL; void display() { glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT); renderer->render(); GLenum error; while((error = glGetError()) != GL_NO_ERROR) { std::cout << gluErrorString(error) << std::endl; } glutSwapBuffers(); } void createNormalIndexes(std::vector<unsigned short> & ni) { unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4}; ni = std::vector<unsigned short>(indexes, indexes + 24); } std::vector<unsigned short> make(unsigned short * p, int n) { return std::vector<unsigned short>(p, p + n); } void createVertexIndexes(std::vector<unsigned short> & vi) { unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7}; vi = std::vector<unsigned short>(indexes, indexes + 24); } void createVBOInstance() { float v = 0.5f; std::vector<unsigned short> vIndexes; std::vector<unsigned short> nIndexes; createNormalIndexes(nIndexes); createVertexIndexes(vIndexes); pbge::VertexBufferBuilder builder(24); pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX); pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL); builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1); builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v); builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v); builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes); pbge::VertexBuffer * vbo = builder.done(); vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS)); } void setUp() { glewInit(); glEnable(GL_DEPTH_TEST); glClearColor(0,0,0,0); glColor3f(1,0,0); createVBOInstance(); renderer = new pbge::Renderer(pbge::Manager::getInstance()->getOpenGL()); pbge::TransformationNode * node = new pbge::TransformationNode; math3d::matrix44 m = math3d::identity44; root = new pbge::TransformationNode; cam_node = new pbge::TransformationNode; child = node; node->setTransformationMatrix(&m); root->addChild(child); root->addChild(cam_node); child->addModelInstance(vboModel); math3d::matrix44 cam_matrix = math3d::identity44; cam_matrix[2][3] = 8.0f; cam_node->setTransformationMatrix(&cam_matrix); camera.setParent(cam_node); camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1)); camera.frustum.setPerspective(30, 1, 0.1f, 10); manager.setSceneGraph(root); manager.addCamera(&camera); renderer->setScene(&manager); } int main(int argc, char ** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE); glutInitWindowSize(500,500); glutCreateWindow("ahahah"); setUp(); glutDisplayFunc(display); glutMainLoop(); return 0; }<|endoftext|>
<commit_before>#include <Subsystems/ElevatorAutomatic.hpp> #include "Robot.hpp" #include <cmath> #include "DriverStation.h" #include <iostream> #include <iomanip> Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"), drive1Buttons(0), drive2Buttons(1), elevatorButtons(2), dsDisplay(DSDisplay::getInstance( settings.getInt("DS_Port"))), insight(Insight::getInstance(settings.getInt("Insight_Port"))), pidGraph(3513) { robotDrive = std::make_unique<DriveTrain>(); driveStick1 = std::make_unique<Joystick>(0); driveStick2 = std::make_unique<Joystick>(1); shootStick = std::make_unique<Joystick>(2); autonTimer = std::make_unique<Timer>(); displayTimer = std::make_unique<Timer>(); ev = std::make_unique<ElevatorAutomatic>(); dsDisplay.addAutonMethod("MotionProfile", &Robot::AutonMotionProfile, this); dsDisplay.addAutonMethod("Noop Auton", &Robot::NoopAuton, this); pidGraph.setSendInterval(10); displayTimer->Start(); } Robot::~Robot() { } void Robot::OperatorControl() { robotDrive->reloadPID(); ev->reloadPID(); while (IsEnabled() && IsOperatorControl()) { if (driveStick2->GetRawButton(2)) { robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(), true); } else { robotDrive->drive(driveStick1->GetY(), driveStick2->GetX()); } // Manual state machine if (elevatorButtons.releasedButton(2)) { ev->setManualMode(!ev->isManualMode()); } // Automatic preset buttons (7-12) if (elevatorButtons.releasedButton(7)) { ev->raiseElevator(0); } if (elevatorButtons.releasedButton(8)) { ev->raiseElevator(1); } if (elevatorButtons.releasedButton(9)) { ev->raiseElevator(2); } if (elevatorButtons.releasedButton(10)) { ev->raiseElevator(3); } if (elevatorButtons.releasedButton(11)) { ev->raiseElevator(4); } if (elevatorButtons.releasedButton(12)) { ev->raiseElevator(5); } // Set manual value ev->setManualLiftSpeed(shootStick->GetY()); if (elevatorButtons.releasedButton(1)) { ev->elevatorGrab(!ev->getElevatorGrab()); } if (elevatorButtons.releasedButton(5)) { ev->intakeGrab(!ev->getIntakeGrab()); } if (elevatorButtons.releasedButton(6)) { ev->stowIntake(!ev->isIntakeStowed()); } if (shootStick->GetPOV() == 180) { ev->setIntakeDirection(Elevator::S_FORWARD); } else if (shootStick->GetPOV() == 0) { ev->setIntakeDirection(Elevator::S_REVERSED); } else { ev->setIntakeDirection(Elevator::S_STOPPED); } if (drive2Buttons.releasedButton(12)) { ev->resetEncoder(); } // Opens intake if the elevator is at the same level as it if (ev->getHeight() < 11 && !ev->isManualMode() && ev->getIntakeGrab()) { ev->intakeGrab(false); } drive1Buttons.updateButtons(); drive2Buttons.updateButtons(); elevatorButtons.updateButtons(); DS_PrintOut(); Wait(0.01); } } void Robot::Autonomous() { autonTimer->Reset(); autonTimer->Start(); dsDisplay.execAutonomous(); autonTimer->Stop(); } void Robot::Disabled() { while (IsDisabled()) { DS_PrintOut(); Wait(0.1); } } void Robot::DS_PrintOut() { if (pidGraph.hasIntervalPassed()) { pidGraph.graphData(ev->getHeight(), "Distance (EV)"); pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)"); pidGraph.resetInterval(); } if (pidGraph.hasIntervalPassed()) { pidGraph.graphData(ev->getHeight(), "Distance (EV)"); pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)"); pidGraph.resetInterval(); } if (displayTimer->HasPeriodPassed(0.5)) { dsDisplay.clear(); dsDisplay.addData("EV_LEVEL_INCHES", ev->getHeight()); dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->getIntakeGrab()); dsDisplay.addData("ARMS_CLOSED", ev->getElevatorGrab()); dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist()); dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist()); std::cout << std::setw(40) << "EV_LEVEL_INCHES=" << ev->getHeight() << "INTAKE_ARMS_CLOSED" << ev->getIntakeGrab() << "ARMS_CLOSED" << ev->getElevatorGrab() << std::endl; std::string name("EL_LEVEL_"); for (int i = 0; i < 6; i++) { std::string name("EL_LEVEL_"); if (ev->getHeight() == ev->getLevel(i) && ev->onTarget()) { dsDisplay.addData(name + std::to_string(i), DSDisplay::active); } else if (ev->getHeight() < ev->getLevel(i + 1)) { dsDisplay.addData(name + std::to_string(i), DSDisplay::standby); dsDisplay.addData(name + std::to_string( i + 1), DSDisplay::standby); } else { dsDisplay.addData(name + std::to_string(i), DSDisplay::inactive); } } dsDisplay.sendToDS(); } dsDisplay.receiveFromDS(); insight.receiveFromDS(); } START_ROBOT_CLASS(Robot); <commit_msg>Reverted accidental duplication of graph data sending code<commit_after>#include <Subsystems/ElevatorAutomatic.hpp> #include "Robot.hpp" #include <cmath> #include "DriverStation.h" #include <iostream> #include <iomanip> Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"), drive1Buttons(0), drive2Buttons(1), elevatorButtons(2), dsDisplay(DSDisplay::getInstance( settings.getInt("DS_Port"))), insight(Insight::getInstance(settings.getInt("Insight_Port"))), pidGraph(3513) { robotDrive = std::make_unique<DriveTrain>(); driveStick1 = std::make_unique<Joystick>(0); driveStick2 = std::make_unique<Joystick>(1); shootStick = std::make_unique<Joystick>(2); autonTimer = std::make_unique<Timer>(); displayTimer = std::make_unique<Timer>(); ev = std::make_unique<ElevatorAutomatic>(); dsDisplay.addAutonMethod("MotionProfile", &Robot::AutonMotionProfile, this); dsDisplay.addAutonMethod("Noop Auton", &Robot::NoopAuton, this); pidGraph.setSendInterval(10); displayTimer->Start(); } Robot::~Robot() { } void Robot::OperatorControl() { robotDrive->reloadPID(); ev->reloadPID(); while (IsEnabled() && IsOperatorControl()) { if (driveStick2->GetRawButton(2)) { robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(), true); } else { robotDrive->drive(driveStick1->GetY(), driveStick2->GetX()); } // Manual state machine if (elevatorButtons.releasedButton(2)) { ev->setManualMode(!ev->isManualMode()); } // Automatic preset buttons (7-12) if (elevatorButtons.releasedButton(7)) { ev->raiseElevator(0); } if (elevatorButtons.releasedButton(8)) { ev->raiseElevator(1); } if (elevatorButtons.releasedButton(9)) { ev->raiseElevator(2); } if (elevatorButtons.releasedButton(10)) { ev->raiseElevator(3); } if (elevatorButtons.releasedButton(11)) { ev->raiseElevator(4); } if (elevatorButtons.releasedButton(12)) { ev->raiseElevator(5); } // Set manual value ev->setManualLiftSpeed(shootStick->GetY()); if (elevatorButtons.releasedButton(1)) { ev->elevatorGrab(!ev->getElevatorGrab()); } if (elevatorButtons.releasedButton(5)) { ev->intakeGrab(!ev->getIntakeGrab()); } if (elevatorButtons.releasedButton(6)) { ev->stowIntake(!ev->isIntakeStowed()); } if (shootStick->GetPOV() == 180) { ev->setIntakeDirection(Elevator::S_FORWARD); } else if (shootStick->GetPOV() == 0) { ev->setIntakeDirection(Elevator::S_REVERSED); } else { ev->setIntakeDirection(Elevator::S_STOPPED); } if (drive2Buttons.releasedButton(12)) { ev->resetEncoder(); } // Opens intake if the elevator is at the same level as it if (ev->getHeight() < 11 && !ev->isManualMode() && ev->getIntakeGrab()) { ev->intakeGrab(false); } drive1Buttons.updateButtons(); drive2Buttons.updateButtons(); elevatorButtons.updateButtons(); DS_PrintOut(); Wait(0.01); } } void Robot::Autonomous() { autonTimer->Reset(); autonTimer->Start(); dsDisplay.execAutonomous(); autonTimer->Stop(); } void Robot::Disabled() { while (IsDisabled()) { DS_PrintOut(); Wait(0.1); } } void Robot::DS_PrintOut() { if (pidGraph.hasIntervalPassed()) { pidGraph.graphData(ev->getHeight(), "Distance (EV)"); pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)"); pidGraph.resetInterval(); } if (displayTimer->HasPeriodPassed(0.5)) { dsDisplay.clear(); dsDisplay.addData("EV_LEVEL_INCHES", ev->getHeight()); dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->getIntakeGrab()); dsDisplay.addData("ARMS_CLOSED", ev->getElevatorGrab()); dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist()); dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist()); std::cout << std::setw(40) << "EV_LEVEL_INCHES=" << ev->getHeight() << "INTAKE_ARMS_CLOSED" << ev->getIntakeGrab() << "ARMS_CLOSED" << ev->getElevatorGrab() << std::endl; std::string name("EL_LEVEL_"); for (int i = 0; i < 6; i++) { std::string name("EL_LEVEL_"); if (ev->getHeight() == ev->getLevel(i) && ev->onTarget()) { dsDisplay.addData(name + std::to_string(i), DSDisplay::active); } else if (ev->getHeight() < ev->getLevel(i + 1)) { dsDisplay.addData(name + std::to_string(i), DSDisplay::standby); dsDisplay.addData(name + std::to_string( i + 1), DSDisplay::standby); } else { dsDisplay.addData(name + std::to_string(i), DSDisplay::inactive); } } dsDisplay.sendToDS(); } dsDisplay.receiveFromDS(); insight.receiveFromDS(); } START_ROBOT_CLASS(Robot); <|endoftext|>
<commit_before>#include <stddef.h> #include <list> #include "prelude.hpp" namespace rubinius { class ObjectHeader; class InflatedHeader; class VM; /** * Manages a list of InflatedHeader instances. * * Storage for InflatedHeader objects are allocated in chunks, and these are * in turn stored in a linked list. As ObjectHeader instances are inflated, * they are added to the next free spot, or if no slots exist, a new chunk * is allocated. * * As InflatedHeader instances are deflated, they are added to free_list_, * which re-uses the storage of the InflatedHeader to link to the next free * InflatedHeader slot. */ class InflatedHeaders { public: typedef std::list<InflatedHeader*> Chunks; /// Storage for InflatedHeader references is allocated in chunks. static const size_t cChunkSize = 1024; static const size_t cChunkLimit = 16; private: VM* state_; /// Linked list of InflatedHeader pointers. Chunks chunks_; /// Pointer to the first free InflatedHeader slot in the list. InflatedHeader* free_list_; /// Number of chunks allocated since last GC cycle size_t allocations_; /// Number of in-use slots int in_use_; public: InflatedHeaders(VM* state) : state_(state) , free_list_(0) , allocations_(0) , in_use_(0) {} ~InflatedHeaders(); InflatedHeader* allocate(ObjectHeader* obj); void deallocate_headers(int mark); void allocate_chunk(); }; } <commit_msg>Change how often a full GC is triggered to improve CAPI perf<commit_after>#include <stddef.h> #include <list> #include "prelude.hpp" namespace rubinius { class ObjectHeader; class InflatedHeader; class VM; /** * Manages a list of InflatedHeader instances. * * Storage for InflatedHeader objects are allocated in chunks, and these are * in turn stored in a linked list. As ObjectHeader instances are inflated, * they are added to the next free spot, or if no slots exist, a new chunk * is allocated. * * As InflatedHeader instances are deflated, they are added to free_list_, * which re-uses the storage of the InflatedHeader to link to the next free * InflatedHeader slot. */ class InflatedHeaders { public: typedef std::list<InflatedHeader*> Chunks; /// Storage for InflatedHeader references is allocated in chunks. static const size_t cChunkSize = 1024; static const size_t cChunkLimit = 32; private: VM* state_; /// Linked list of InflatedHeader pointers. Chunks chunks_; /// Pointer to the first free InflatedHeader slot in the list. InflatedHeader* free_list_; /// Number of chunks allocated since last GC cycle size_t allocations_; /// Number of in-use slots int in_use_; public: InflatedHeaders(VM* state) : state_(state) , free_list_(0) , allocations_(0) , in_use_(0) {} ~InflatedHeaders(); InflatedHeader* allocate(ObjectHeader* obj); void deallocate_headers(int mark); void allocate_chunk(); }; } <|endoftext|>
<commit_before>/***************************************************************************** * PokerTH - The open source texas holdem engine * * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * *****************************************************************************/ #include <net/netpacket.h> #include "session.h" #include "configfile.h" #include <qttoolsinterface.h> #include <gui/generic/serverguiwrapper.h> #include <net/socket_startup.h> #include <core/loghelper.h> #include <core/thread.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <csignal> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif using namespace std; namespace po = boost::program_options; using namespace boost::filesystem; volatile int g_pokerthTerminate = 0; void TerminateHandler(int /*signal*/) { g_pokerthTerminate = 1; } // TODO: Hack #ifdef _WIN32 #include <process.h> #else #include <unistd.h> #ifndef daemon int daemon(int, int); #endif #endif int main(int argc, char *argv[]) { ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(10260); bool readonlyConfig = false; string pidFile; int logLevel = 1; { // Check command line options. po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("version,v", "print version string") ("log-level,l", po::value<int>(), "set log level (0=minimal, 1=default, 2=verbose)") ("pid-file,p", po::value<string>(), "create pid-file in different location") ("readonly-config", "treat config file as read-only") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; return 1; } if (vm.count("version")) { cout << "PokerTH server version " << POKERTH_BETA_RELEASE_STRING << endl << "Network protocol version " << NET_VERSION_MAJOR << "." << NET_VERSION_MINOR << endl; return 1; } if (vm.count("log-level")) { logLevel = vm["log-level"].as<int>(); if (logLevel < 0 || logLevel > 2) { cout << "Invalid log-level: \"" << logLevel << "\", allowed range 0-2." << endl; return 1; } } if (vm.count("pid-file")) pidFile = vm["pid-file"].as<string>(); if (vm.count("readonly-config")) readonlyConfig = true; } boost::shared_ptr<QtToolsInterface> myQtToolsInterface(CreateQtToolsWrapper()); //create defaultconfig boost::shared_ptr<ConfigFile> myConfig(new ConfigFile(argv[0], readonlyConfig)); loghelper_init(myQtToolsInterface->stringFromUtf8(myConfig->readConfigString("LogDir")), logLevel); // TODO: Hack #ifndef _WIN32 if (daemon(0, 0) != 0) { cout << "Failed to start daemon." << endl; return 1; } #endif signal(SIGTERM, TerminateHandler); signal(SIGINT, TerminateHandler); socket_startup(); LOG_MSG("Starting PokerTH dedicated server. Availability: IPv6 " << socket_has_ipv6() << ", SCTP " << socket_has_sctp() << ", Dual Stack " << socket_has_dual_stack() << "."); // Store pid in file. if (pidFile.empty()) { path tmpPidPath(myConfig->readConfigString("LogDir")); tmpPidPath /= "pokerth.pid"; pidFile = tmpPidPath.directory_string(); } { ofstream pidStream(pidFile.c_str(), ios_base::out | ios_base::trunc); if (!pidStream.fail()) pidStream << getpid(); else LOG_ERROR("Could not create process id file \"" << pidFile << "\"!"); } // Create pseudo Gui Wrapper for the server. boost::shared_ptr<GuiInterface> myServerGuiInterface(new ServerGuiWrapper(myConfig.get(), NULL, NULL, NULL)); boost::shared_ptr<Session> session(new Session(myServerGuiInterface.get(), myConfig.get())); if (!session->init()) LOG_ERROR("Missing files - please check your directory settings!"); myServerGuiInterface->setSession(session); myServerGuiInterface->getSession()->startNetworkServer(true); while (!g_pokerthTerminate) { Thread::Msleep(100); if (myServerGuiInterface->getSession()->pollNetworkServerTerminated()) g_pokerthTerminate = true; } myServerGuiInterface->getSession()->terminateNetworkServer(); session.reset(); myServerGuiInterface.reset(); myConfig.reset(); LOG_MSG("Terminating PokerTH dedicated server." << endl); socket_cleanup(); return 0; } <commit_msg>Start daemon mode only in non-debug server.<commit_after>/***************************************************************************** * PokerTH - The open source texas holdem engine * * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * *****************************************************************************/ #include <net/netpacket.h> #include "session.h" #include "configfile.h" #include <qttoolsinterface.h> #include <gui/generic/serverguiwrapper.h> #include <net/socket_startup.h> #include <core/loghelper.h> #include <core/thread.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <csignal> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif using namespace std; namespace po = boost::program_options; using namespace boost::filesystem; volatile int g_pokerthTerminate = 0; void TerminateHandler(int /*signal*/) { g_pokerthTerminate = 1; } // TODO: Hack #ifdef _WIN32 #include <process.h> #else #include <unistd.h> #ifndef daemon int daemon(int, int); #endif #endif int main(int argc, char *argv[]) { ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(10260); bool readonlyConfig = false; string pidFile; int logLevel = 1; { // Check command line options. po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("version,v", "print version string") ("log-level,l", po::value<int>(), "set log level (0=minimal, 1=default, 2=verbose)") ("pid-file,p", po::value<string>(), "create pid-file in different location") ("readonly-config", "treat config file as read-only") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; return 1; } if (vm.count("version")) { cout << "PokerTH server version " << POKERTH_BETA_RELEASE_STRING << endl << "Network protocol version " << NET_VERSION_MAJOR << "." << NET_VERSION_MINOR << endl; return 1; } if (vm.count("log-level")) { logLevel = vm["log-level"].as<int>(); if (logLevel < 0 || logLevel > 2) { cout << "Invalid log-level: \"" << logLevel << "\", allowed range 0-2." << endl; return 1; } } if (vm.count("pid-file")) pidFile = vm["pid-file"].as<string>(); if (vm.count("readonly-config")) readonlyConfig = true; } boost::shared_ptr<QtToolsInterface> myQtToolsInterface(CreateQtToolsWrapper()); //create defaultconfig boost::shared_ptr<ConfigFile> myConfig(new ConfigFile(argv[0], readonlyConfig)); loghelper_init(myQtToolsInterface->stringFromUtf8(myConfig->readConfigString("LogDir")), logLevel); // TODO: Hack #ifndef _WIN32 #ifdef QT_NO_DEBUG if (daemon(0, 0) != 0) { cout << "Failed to start daemon." << endl; return 1; } #endif #endif signal(SIGTERM, TerminateHandler); signal(SIGINT, TerminateHandler); socket_startup(); LOG_MSG("Starting PokerTH dedicated server. Availability: IPv6 " << socket_has_ipv6() << ", SCTP " << socket_has_sctp() << ", Dual Stack " << socket_has_dual_stack() << "."); // Store pid in file. if (pidFile.empty()) { path tmpPidPath(myConfig->readConfigString("LogDir")); tmpPidPath /= "pokerth.pid"; pidFile = tmpPidPath.directory_string(); } { ofstream pidStream(pidFile.c_str(), ios_base::out | ios_base::trunc); if (!pidStream.fail()) pidStream << getpid(); else LOG_ERROR("Could not create process id file \"" << pidFile << "\"!"); } // Create pseudo Gui Wrapper for the server. boost::shared_ptr<GuiInterface> myServerGuiInterface(new ServerGuiWrapper(myConfig.get(), NULL, NULL, NULL)); boost::shared_ptr<Session> session(new Session(myServerGuiInterface.get(), myConfig.get())); if (!session->init()) LOG_ERROR("Missing files - please check your directory settings!"); myServerGuiInterface->setSession(session); myServerGuiInterface->getSession()->startNetworkServer(true); while (!g_pokerthTerminate) { Thread::Msleep(100); if (myServerGuiInterface->getSession()->pollNetworkServerTerminated()) g_pokerthTerminate = true; } myServerGuiInterface->getSession()->terminateNetworkServer(); session.reset(); myServerGuiInterface.reset(); myConfig.reset(); LOG_MSG("Terminating PokerTH dedicated server." << endl); socket_cleanup(); return 0; } <|endoftext|>
<commit_before>#include "FGame.hpp" //Images were downloaded from opengameart.org FGame::FGame(std::shared_ptr<FEngine> engine) { m_engine = engine; auto level = engine->getLevel(); m_width = level->getWidth(); m_height = level->getHeight(); m_tileSize = level->getTileSize(); sf::RenderWindow *window = new sf::RenderWindow( sf::VideoMode(m_width * m_tileSize, m_height * m_tileSize), "FightR 2.0" ); m_window = std::unique_ptr<sf::RenderWindow>(window); } std::shared_ptr<sf::Sprite> FGame::loadSprite(std::string fileName, int width, int height) { auto exists = m_sprites.find(fileName); if (exists == m_sprites.end()) { auto texture = std::make_shared<sf::Texture>(); if (!texture->loadFromFile(fileName, sf::IntRect(0, 0, width, height))) { std::cout << "ERROR trying to load " << fileName; } auto sprite = std::make_shared<sf::Sprite>(); sprite->setTexture(*texture); m_sprites[fileName] = sprite; m_textures[fileName] = texture; return sprite; } else { return exists->second; } } void FGame::run() { sf::Clock clock; sf::Time accumulator = sf::Time::Zero; sf::Time ups = sf::seconds(1.f / 60.f); while (m_window->isOpen() && m_engine->isRunning()) { processEvents(); while (accumulator > ups) { accumulator -= ups; m_engine->tick(ups.asSeconds()); m_engine->print(); } render(); accumulator += clock.restart(); } } void FGame::processEvents() { // Check events sf::Event event; while (m_window->pollEvent(event)) { if (event.type == sf::Event::Closed) m_window->close(); } // Check keyboard press auto &characters = m_engine->getCharacters(); auto it = std::find_if(characters.begin(), characters.end(), [] (FCharacter& character) { return character.isHuman(); } ); if (it != characters.end()) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) it->move(FDirection::left); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) it->move(FDirection::right); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) it->move(FDirection::up); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) it->move(FDirection::down); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) it->fire(); } } void FGame::render() { m_window->clear(); // Render all tiles for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { auto data = m_engine->getLevel()->get(x, y); auto sprite = loadSprite(m_tileMap[data], m_tileSize, m_tileSize); sprite->setPosition(sf::Vector2f(x * m_tileSize, y * m_tileSize)); m_window->draw(*sprite); } } // Render characters and their weapons for (auto &character : m_engine->getCharacters()) { if (character.getHealth() > 0) { auto sprite = loadSprite(m_characterTypeMap[character.getType()], character.getSize().x, character.getSize().y); sprite->setPosition(sf::Vector2f(character.getPosition().x, character.getPosition().y)); m_window->draw(*sprite); auto weapon = character.getWeapon(); auto weaponSprite = loadSprite(m_weaponTypeMap[weapon.getType()], weapon.getSize().x, weapon.getSize().y); weaponSprite->setPosition(sf::Vector2f(character.getPosition().x + character.getSize().x / 2.f, character.getPosition().y + character.getSize().y / 2.f)); m_window->draw(*weaponSprite); } } // Render projectiles for (auto &projectile : m_engine->getProjectiles()) { auto sprite = loadSprite(m_projectileTypeMap[projectile.getType()], projectile.getSize().x, projectile.getSize().y); sprite->setPosition(sf::Vector2f(projectile.getPosition().x, projectile.getPosition().y)); m_window->draw(*sprite); } // Render powerups for (auto &powerup : m_engine->getPowerups()) { auto sprite = loadSprite(m_powerupTypeMap[powerup.getType()], powerup.getSize().x, powerup.getSize().y); sprite->setPosition(sf::Vector2f(powerup.getPosition().x, powerup.getPosition().y)); m_window->draw(*sprite); } // Render effects //TODO m_window->display(); } void FGame::setTile(FTile typeName, std::string filename) { m_tileMap[typeName] = filename; } void FGame::setCharacterType(FCharacterType typeName, std::string filename) { m_characterTypeMap[typeName] = filename; } void FGame::setWeaponType(FWeaponType typeName, std::string filename) { m_weaponTypeMap[typeName] = filename; } void FGame::setProjectileType(FProjectileType typeName, std::string filename) { m_projectileTypeMap[typeName] = filename; } void FGame::setPowerupType(FPowerupType typeName, std::string filename) { m_powerupTypeMap[typeName] = filename; } <commit_msg>Added buttons for changing current weapon<commit_after>#include "FGame.hpp" FGame::FGame(std::shared_ptr<FEngine> engine) { m_engine = engine; auto level = engine->getLevel(); m_width = level->getWidth(); m_height = level->getHeight(); m_tileSize = level->getTileSize(); sf::RenderWindow *window = new sf::RenderWindow( sf::VideoMode(m_width * m_tileSize, m_height * m_tileSize), "FightR 2.0" ); m_window = std::unique_ptr<sf::RenderWindow>(window); } std::shared_ptr<sf::Sprite> FGame::loadSprite(std::string fileName, int width, int height) { auto exists = m_sprites.find(fileName); if (exists == m_sprites.end()) { auto texture = std::make_shared<sf::Texture>(); if (!texture->loadFromFile(fileName, sf::IntRect(0, 0, width, height))) { std::cout << "ERROR trying to load " << fileName; } auto sprite = std::make_shared<sf::Sprite>(); sprite->setTexture(*texture); m_sprites[fileName] = sprite; m_textures[fileName] = texture; return sprite; } else { return exists->second; } } void FGame::run() { sf::Clock clock; sf::Time accumulator = sf::Time::Zero; sf::Time ups = sf::seconds(1.f / 60.f); while (m_window->isOpen() && m_engine->isRunning()) { processEvents(); while (accumulator > ups) { accumulator -= ups; m_engine->tick(ups.asSeconds()); m_engine->print(); } render(); accumulator += clock.restart(); } } void FGame::processEvents() { // Check events sf::Event event; while (m_window->pollEvent(event)) { if (event.type == sf::Event::Closed) m_window->close(); } // Check keyboard press auto &characters = m_engine->getCharacters(); auto it = std::find_if(characters.begin(), characters.end(), [] (FCharacter& character) { return character.isHuman(); } ); if (it != characters.end()) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) it->move(FDirection::left); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) it->move(FDirection::right); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) it->move(FDirection::up); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) it->move(FDirection::down); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) it->setWeaponIndex(it->getWeaponIndex() - 1); else if (sf::Keyboard::isKeyPressed(sf::Keyboard::X)) it->setWeaponIndex(it->getWeaponIndex() + 1); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) it->fire(); } } void FGame::render() { m_window->clear(); // Render all tiles for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { auto data = m_engine->getLevel()->get(x, y); auto sprite = loadSprite(m_tileMap[data], m_tileSize, m_tileSize); sprite->setPosition(sf::Vector2f(x * m_tileSize, y * m_tileSize)); m_window->draw(*sprite); } } // Render characters and their weapons for (auto &character : m_engine->getCharacters()) { if (character.getHealth() > 0) { auto sprite = loadSprite(m_characterTypeMap[character.getType()], character.getSize().x, character.getSize().y); sprite->setPosition(sf::Vector2f(character.getPosition().x, character.getPosition().y)); m_window->draw(*sprite); auto weapon = character.getWeapon(); auto weaponSprite = loadSprite(m_weaponTypeMap[weapon.getType()], weapon.getSize().x, weapon.getSize().y); weaponSprite->setPosition(sf::Vector2f(character.getPosition().x + character.getSize().x / 2.f, character.getPosition().y + character.getSize().y / 2.f)); m_window->draw(*weaponSprite); } } // Render projectiles for (auto &projectile : m_engine->getProjectiles()) { auto sprite = loadSprite(m_projectileTypeMap[projectile.getType()], projectile.getSize().x, projectile.getSize().y); sprite->setPosition(sf::Vector2f(projectile.getPosition().x, projectile.getPosition().y)); m_window->draw(*sprite); } // Render powerups for (auto &powerup : m_engine->getPowerups()) { auto sprite = loadSprite(m_powerupTypeMap[powerup.getType()], powerup.getSize().x, powerup.getSize().y); sprite->setPosition(sf::Vector2f(powerup.getPosition().x, powerup.getPosition().y)); m_window->draw(*sprite); } // Render effects //TODO m_window->display(); } void FGame::setTile(FTile typeName, std::string filename) { m_tileMap[typeName] = filename; } void FGame::setCharacterType(FCharacterType typeName, std::string filename) { m_characterTypeMap[typeName] = filename; } void FGame::setWeaponType(FWeaponType typeName, std::string filename) { m_weaponTypeMap[typeName] = filename; } void FGame::setProjectileType(FProjectileType typeName, std::string filename) { m_projectileTypeMap[typeName] = filename; } void FGame::setPowerupType(FPowerupType typeName, std::string filename) { m_powerupTypeMap[typeName] = filename; } <|endoftext|>
<commit_before>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = NULL; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = NULL; line_len = NULL; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); if (start < 0 || length < 1) { cerr << "Error: cannot construct subsequence with negative offset or length < 1" << endl; exit(1); } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <commit_msg>clean up Fasta.cpp compile, NULL -> 0<commit_after>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = 0; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = 0; line_len = 0; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); if (start < 0 || length < 1) { cerr << "Error: cannot construct subsequence with negative offset or length < 1" << "(attempting start = " << start << " and length = " << length << ")" << endl; exit(1); } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <|endoftext|>
<commit_before><commit_msg>Don't check for pWin when drawing the Scrollbar<commit_after><|endoftext|>
<commit_before><commit_msg>tdf#91380 add WB_MOVEABLE bit to docking windows<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2008-2009 Josh A. Beam <josh@joshbeam.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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 <cstdio> #include <cstring> #include <DromeAudio/Exception.h> #include <DromeAudio/Sound.h> #ifdef WITH_VORBIS #include <DromeAudio/VorbisSound.h> #endif /* WITH_VORBIS */ #include <DromeAudio/WavSound.h> #include <DromeAudio/Util.h> #include "Wav.h" namespace DromeAudio { /* * Sound class */ Sound::Sound() { } Sample Sound::getSample(unsigned int index, unsigned int targetRate) const { unsigned int rate = getSampleRate(); // map index from target sample rate if necessary if(targetRate != rate) { float f = (float)rate / (float)targetRate; index = (unsigned int)((float)index * f); } return getSample(index); } void Sound::save(const char *filename, unsigned int numSamples) { const unsigned char bytesPerSample = 2; const unsigned char numChannels = 2; // make sure the number of samples to save is good if(numSamples == 0) { if(getNumSamples() == 0) throw Exception("Sound::Save(): Cannot save %s; sound has unlimited number of samples and the number of samples to save was not provided", filename); numSamples = getNumSamples(); } // open file for writing FILE *fp = fopen(filename, "wb"); if(!fp) throw Exception("Sound::Save(): Unable to open %s for writing", filename); // calculate length of sample data unsigned int dataLength = numSamples * (unsigned int)bytesPerSample * (unsigned int)numChannels; // create riff header WavChunkHeader hdr; hdr.chunk_id[0] = 'R'; hdr.chunk_id[1] = 'I'; hdr.chunk_id[2] = 'F'; hdr.chunk_id[3] = 'F'; hdr.chunk_size = nativeToLittleUInt32(4 + (sizeof(WavChunkHeader) * 2) + sizeof(WavFmtChunk)); fwrite(&hdr, sizeof(hdr), 1, fp); // write riff type char tmp[4]; tmp[0] = 'W'; tmp[1] = 'A'; tmp[2] = 'V'; tmp[3] = 'E'; fwrite(tmp, 4, 1, fp); // write fmt header hdr.chunk_id[0] = 'f'; hdr.chunk_id[1] = 'm'; hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = ' '; hdr.chunk_size = nativeToLittleUInt32(sizeof(WavFmtChunk)); fwrite(&hdr, sizeof(hdr), 1, fp); // write fmt chunk WavFmtChunk fmt; fmt.type = nativeToLittleUInt16(1); fmt.channels = nativeToLittleUInt16(numChannels); fmt.rate = nativeToLittleUInt32(getSampleRate()); fmt.bytes_per_second = nativeToLittleUInt32((unsigned int)bytesPerSample * (unsigned int)numChannels * getSampleRate()); fmt.block_align = nativeToLittleUInt16((uint16_t)bytesPerSample * (uint16_t)numChannels); fmt.bits_per_sample = nativeToLittleUInt16((uint16_t)bytesPerSample * 8); fwrite(&fmt, sizeof(fmt), 1, fp); // write data header hdr.chunk_id[0] = 'd'; hdr.chunk_id[1] = 'a'; hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = 'a'; hdr.chunk_size = nativeToLittleUInt32(dataLength); fwrite(&hdr, sizeof(hdr), 1, fp); // write data for(unsigned int i = 0; i < numSamples; i++) { uint16_t s[2]; Sample sample = getSample(i); s[0] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[0])); s[1] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[1])); fwrite(s, sizeof(s), 1, fp); } // done fclose(fp); } SoundPtr Sound::create(const char *filename) { // look for file extension const char *tmp = filename + strlen(filename); while(tmp != filename && *tmp != '.') --tmp; if(tmp == filename) throw Exception("Sound::New(): filename has no extension"); // create sound based on extension #ifdef WITH_VORBIS if(strCaseCmp(tmp, ".ogg") == 0) return VorbisSound::create(filename); #endif /* WITH_VORBIS */ if(strCaseCmp(tmp, ".wav") == 0) return WavSound::create(filename); throw Exception("Sound::New(): Unsupported file extension (%s)", tmp); return NULL; } } // namespace DromeAudio <commit_msg>Fixed outdated function names in Exception messages.<commit_after>/* * Copyright (C) 2008-2009 Josh A. Beam <josh@joshbeam.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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 <cstdio> #include <cstring> #include <DromeAudio/Exception.h> #include <DromeAudio/Sound.h> #ifdef WITH_VORBIS #include <DromeAudio/VorbisSound.h> #endif /* WITH_VORBIS */ #include <DromeAudio/WavSound.h> #include <DromeAudio/Util.h> #include "Wav.h" namespace DromeAudio { /* * Sound class */ Sound::Sound() { } Sample Sound::getSample(unsigned int index, unsigned int targetRate) const { unsigned int rate = getSampleRate(); // map index from target sample rate if necessary if(targetRate != rate) { float f = (float)rate / (float)targetRate; index = (unsigned int)((float)index * f); } return getSample(index); } void Sound::save(const char *filename, unsigned int numSamples) { const unsigned char bytesPerSample = 2; const unsigned char numChannels = 2; // make sure the number of samples to save is good if(numSamples == 0) { if(getNumSamples() == 0) throw Exception("Sound::Save(): Cannot save %s; sound has unlimited number of samples and the number of samples to save was not provided", filename); numSamples = getNumSamples(); } // open file for writing FILE *fp = fopen(filename, "wb"); if(!fp) throw Exception("Sound::Save(): Unable to open %s for writing", filename); // calculate length of sample data unsigned int dataLength = numSamples * (unsigned int)bytesPerSample * (unsigned int)numChannels; // create riff header WavChunkHeader hdr; hdr.chunk_id[0] = 'R'; hdr.chunk_id[1] = 'I'; hdr.chunk_id[2] = 'F'; hdr.chunk_id[3] = 'F'; hdr.chunk_size = nativeToLittleUInt32(4 + (sizeof(WavChunkHeader) * 2) + sizeof(WavFmtChunk)); fwrite(&hdr, sizeof(hdr), 1, fp); // write riff type char tmp[4]; tmp[0] = 'W'; tmp[1] = 'A'; tmp[2] = 'V'; tmp[3] = 'E'; fwrite(tmp, 4, 1, fp); // write fmt header hdr.chunk_id[0] = 'f'; hdr.chunk_id[1] = 'm'; hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = ' '; hdr.chunk_size = nativeToLittleUInt32(sizeof(WavFmtChunk)); fwrite(&hdr, sizeof(hdr), 1, fp); // write fmt chunk WavFmtChunk fmt; fmt.type = nativeToLittleUInt16(1); fmt.channels = nativeToLittleUInt16(numChannels); fmt.rate = nativeToLittleUInt32(getSampleRate()); fmt.bytes_per_second = nativeToLittleUInt32((unsigned int)bytesPerSample * (unsigned int)numChannels * getSampleRate()); fmt.block_align = nativeToLittleUInt16((uint16_t)bytesPerSample * (uint16_t)numChannels); fmt.bits_per_sample = nativeToLittleUInt16((uint16_t)bytesPerSample * 8); fwrite(&fmt, sizeof(fmt), 1, fp); // write data header hdr.chunk_id[0] = 'd'; hdr.chunk_id[1] = 'a'; hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = 'a'; hdr.chunk_size = nativeToLittleUInt32(dataLength); fwrite(&hdr, sizeof(hdr), 1, fp); // write data for(unsigned int i = 0; i < numSamples; i++) { uint16_t s[2]; Sample sample = getSample(i); s[0] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[0])); s[1] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[1])); fwrite(s, sizeof(s), 1, fp); } // done fclose(fp); } SoundPtr Sound::create(const char *filename) { // look for file extension const char *tmp = filename + strlen(filename); while(tmp != filename && *tmp != '.') --tmp; if(tmp == filename) throw Exception("Sound::create(): filename has no extension"); // create sound based on extension #ifdef WITH_VORBIS if(strCaseCmp(tmp, ".ogg") == 0) return VorbisSound::create(filename); #endif /* WITH_VORBIS */ if(strCaseCmp(tmp, ".wav") == 0) return WavSound::create(filename); throw Exception("Sound::create(): Unsupported file extension (%s)", tmp); return NULL; } } // namespace DromeAudio <|endoftext|>
<commit_before>#include "SqrtX.hpp" #include <climits> using namespace std; int SqrtX::mySqrt(int x) { if (x == 0) return 0; int left = 1, right = INT_MAX; while (true) { int mid = left + (right - left) / 2; if (mid > x / mid) right = mid - 1; else if (mid + 1 > x / (mid + 1)) return mid; else left = mid + 1; } }<commit_msg>Refine Problem 69. Sqrt(x)<commit_after>#include "SqrtX.hpp" #include <cstdint> using namespace std; int SqrtX::mySqrt(int x) { int64_t l = 1, r = x; while (l + 1 < r) { int64_t m = l + (r - l) / 2; if (m * m < x) l = m; else r = m; } return r * r <= x ? r : l; }<|endoftext|>
<commit_before>#ifndef VPP_OPENCV_BRIDGE_HH__ # define VPP_OPENCV_BRIDGE_HH__ # include <opencv2/opencv.hpp> # include <vpp/core/image2d.hh> namespace vpp { template <typename T> struct opencv_typeof; #define OPENCV_TYPEOF(T, V) \ template <> \ struct opencv_typeof<T> \ { \ enum { ret = V }; \ }; #define OPENCV_TYPEOF_(BT, T, CV) \ OPENCV_TYPEOF(BT, CV_##CV##C1); \ OPENCV_TYPEOF(v##T##1, CV_##CV##C1); \ OPENCV_TYPEOF(v##T##2, CV_##CV##C2); \ OPENCV_TYPEOF(v##T##3, CV_##CV##C3); \ OPENCV_TYPEOF(v##T##4, CV_##CV##C4); OPENCV_TYPEOF_(unsigned char, uchar, 8U); OPENCV_TYPEOF_(char, char, 8S); OPENCV_TYPEOF_(unsigned short, ushort, 16U); OPENCV_TYPEOF_(short, short, 16S); OPENCV_TYPEOF_(float, float, 32F); OPENCV_TYPEOF_(int, int, 32S); struct opencv_data_holder { int* refcount; void* data; }; static void opencv_data_deleter(void* data) { opencv_data_holder* d = (opencv_data_holder*) data; if (d->refcount and *(d->refcount) > 1) *(d->refcount) -= 1; else if (d->refcount and *(d->refcount) == 1) cv::fastFree(d->data); delete d; } template <typename V> image2d<V> from_opencv(cv::Mat m) { if (!m.data) return image2d<V>(); image2d<V> res(make_box2d(m.rows, m.cols), _data = m.data, _pitch = m.step); #if CV_VERSION_MAJOR == 2 res.set_external_data_holder(new opencv_data_holder{m.refcount, m.data}, opencv_data_deleter); #else res.set_external_data_holder(new opencv_data_holder{&m.u->refcount, m.data}, opencv_data_deleter); #endif m.addref(); return res; } template <typename V> cv::Mat to_opencv(image2d<V>& v) { if (!v.has_data()) return cv::Mat(); cv::Mat m(v.nrows(), v.ncols(), opencv_typeof<V>::ret, (void*) v.address_of(vint2(0,0)), v.pitch()); return m; } }; #endif <commit_msg>Fix compilation with opencv2.<commit_after>#ifndef VPP_OPENCV_BRIDGE_HH__ # define VPP_OPENCV_BRIDGE_HH__ # include <opencv2/opencv.hpp> # include <vpp/core/image2d.hh> namespace vpp { template <typename T> struct opencv_typeof; #define OPENCV_TYPEOF(T, V) \ template <> \ struct opencv_typeof<T> \ { \ enum { ret = V }; \ }; #define OPENCV_TYPEOF_(BT, T, CV) \ OPENCV_TYPEOF(BT, CV_##CV##C1); \ OPENCV_TYPEOF(v##T##1, CV_##CV##C1); \ OPENCV_TYPEOF(v##T##2, CV_##CV##C2); \ OPENCV_TYPEOF(v##T##3, CV_##CV##C3); \ OPENCV_TYPEOF(v##T##4, CV_##CV##C4); OPENCV_TYPEOF_(unsigned char, uchar, 8U); OPENCV_TYPEOF_(char, char, 8S); OPENCV_TYPEOF_(unsigned short, ushort, 16U); OPENCV_TYPEOF_(short, short, 16S); OPENCV_TYPEOF_(float, float, 32F); OPENCV_TYPEOF_(int, int, 32S); struct opencv_data_holder { int* refcount; void* data; }; static void opencv_data_deleter(void* data) { opencv_data_holder* d = (opencv_data_holder*) data; if (d->refcount and *(d->refcount) > 1) *(d->refcount) -= 1; else if (d->refcount and *(d->refcount) == 1) cv::fastFree(d->data); delete d; } template <typename V> image2d<V> from_opencv(cv::Mat m) { if (!m.data) return image2d<V>(); image2d<V> res(make_box2d(m.rows, m.cols), _data = m.data, _pitch = m.step); #if CV_VERSION_EPOCH == 2 res.set_external_data_holder(new opencv_data_holder{m.refcount, m.data}, opencv_data_deleter); #else res.set_external_data_holder(new opencv_data_holder{&m.u->refcount, m.data}, opencv_data_deleter); #endif m.addref(); return res; } template <typename V> cv::Mat to_opencv(image2d<V>& v) { if (!v.has_data()) return cv::Mat(); cv::Mat m(v.nrows(), v.ncols(), opencv_typeof<V>::ret, (void*) v.address_of(vint2(0,0)), v.pitch()); return m; } }; #endif <|endoftext|>
<commit_before>#include <muduo/base/Logging.h> #include <muduo/net/EventLoop.h> #include <muduo/net/InetAddress.h> #include <muduo/net/TcpClient.h> #include <muduo/net/TcpServer.h> #include <boost/bind.hpp> #include <queue> #include <utility> #include <mcheck.h> #include <stdio.h> #include <unistd.h> using namespace muduo; using namespace muduo::net; typedef boost::shared_ptr<TcpClient> TcpClientPtr; const int kMaxConns = 1; const size_t kMaxPacketLen = 255; const size_t kHeaderLen = 3; const uint16_t kListenPort = 9999; const char* socksIp = "127.0.0.1"; const uint16_t kSocksPort = 2007; struct Entry { int connId; TcpClientPtr client; TcpConnectionPtr connection; Buffer pending; }; class DemuxServer : boost::noncopyable { public: DemuxServer(EventLoop* loop, const InetAddress& listenAddr, const InetAddress& socksAddr) : loop_(loop), server_(loop, listenAddr, "DemuxServer"), socksAddr_(socksAddr) { server_.setConnectionCallback( boost::bind(&DemuxServer::onServerConnection, this, _1)); server_.setMessageCallback( boost::bind(&DemuxServer::onServerMessage, this, _1, _2, _3)); } void start() { server_.start(); } void onServerConnection(const TcpConnectionPtr& conn) { if (conn->connected()) { if (serverConn_) { conn->shutdown(); } else { serverConn_ = conn; LOG_INFO << "onServerConnection set serverConn_"; } } else { if (serverConn_ == conn) { serverConn_.reset(); LOG_INFO << "onServerConnection reset serverConn_"; } } } void onServerMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp) { while (buf->readableBytes() > kHeaderLen) { size_t len = static_cast<uint8_t>(*buf->peek()); if (buf->readableBytes() < len + kHeaderLen) { break; } else { int connId = static_cast<uint8_t>(buf->peek()[1]); connId |= (static_cast<uint8_t>(buf->peek()[2]) << 8); if (connId != 0) { assert(socksConns_.find(connId) != socksConns_.end()); TcpConnectionPtr& socksConn = socksConns_[connId].connection; if (socksConn) { assert(socksConns_[connId].pending.readableBytes() == 0); socksConn->send(buf->peek() + kHeaderLen, len); } else { socksConns_[connId].pending.append(buf->peek() + kHeaderLen, len); } } else { string cmd(buf->peek() + kHeaderLen, len); doCommand(cmd); } buf->retrieve(len + kHeaderLen); } } } void doCommand(const string& cmd) { static const string kConn = "CONN "; int connId = atoi(&cmd[kConn.size()]); bool isUp = cmd.find(" IS UP") != string::npos; LOG_INFO << "doCommand " << connId << " " << isUp; if (isUp) { assert(socksConns_.find(connId) == socksConns_.end()); char connName[256]; snprintf(connName, sizeof connName, "SocksClient %d", connId); Entry entry; entry.connId = connId; entry.client.reset(new TcpClient(loop_, socksAddr_, connName)); entry.client->setConnectionCallback( boost::bind(&DemuxServer::onSocksConnection, this, connId, _1)); entry.client->setMessageCallback( boost::bind(&DemuxServer::onSocksMessage, this, connId, _1, _2, _3)); // FIXME: setWriteCompleteCallback socksConns_[connId] = entry; entry.client->connect(); } else { assert(socksConns_.find(connId) != socksConns_.end()); TcpConnectionPtr& socksConn = socksConns_[connId].connection; if (socksConn) { socksConn->shutdown(); } else { socksConns_.erase(connId); } } } void onSocksConnection(int connId, const TcpConnectionPtr& conn) { assert(socksConns_.find(connId) != socksConns_.end()); if (conn->connected()) { socksConns_[connId].connection = conn; Buffer& pendingData = socksConns_[connId].pending; if (pendingData.readableBytes() > 0) { conn->send(&pendingData); } } else { if (serverConn_) { char buf[256]; int len = snprintf(buf, sizeof(buf), "DISCONNECT %d\r\n", connId); Buffer buffer; buffer.append(buf, len); sendServerPacket(0, &buffer); } else { socksConns_.erase(connId); } } } void onSocksMessage(int connId, const TcpConnectionPtr& conn, Buffer* buf, Timestamp) { assert(socksConns_.find(connId) != socksConns_.end()); while (buf->readableBytes() > kMaxPacketLen) { Buffer packet; packet.append(buf->peek(), kMaxPacketLen); buf->retrieve(kMaxPacketLen); sendServerPacket(connId, &packet); } if (buf->readableBytes() > 0) { sendServerPacket(connId, buf); } } void sendServerPacket(int connId, Buffer* buf) { size_t len = buf->readableBytes(); LOG_DEBUG << len; assert(len <= kMaxPacketLen); uint8_t header[kHeaderLen] = { static_cast<uint8_t>(len), static_cast<uint8_t>(connId & 0xFF), static_cast<uint8_t>((connId & 0xFF00) >> 8) }; buf->prepend(header, kHeaderLen); if (serverConn_) { serverConn_->send(buf); } } EventLoop* loop_; TcpServer server_; TcpConnectionPtr serverConn_; const InetAddress socksAddr_; std::map<int, Entry> socksConns_; }; int main(int argc, char* argv[]) { LOG_INFO << "pid = " << getpid(); EventLoop loop; InetAddress listenAddr(kListenPort); if (argc > 1) { socksIp = argv[1]; } InetAddress socksAddr(socksIp, kSocksPort); DemuxServer server(&loop, listenAddr, socksAddr); server.start(); loop.loop(); } <commit_msg>clear socksConn_ when server conn is down.<commit_after>#include <muduo/base/Logging.h> #include <muduo/net/EventLoop.h> #include <muduo/net/InetAddress.h> #include <muduo/net/TcpClient.h> #include <muduo/net/TcpServer.h> #include <boost/bind.hpp> #include <queue> #include <utility> #include <mcheck.h> #include <stdio.h> #include <unistd.h> using namespace muduo; using namespace muduo::net; typedef boost::shared_ptr<TcpClient> TcpClientPtr; const int kMaxConns = 1; const size_t kMaxPacketLen = 255; const size_t kHeaderLen = 3; const uint16_t kListenPort = 9999; const char* socksIp = "127.0.0.1"; const uint16_t kSocksPort = 7777; struct Entry { int connId; TcpClientPtr client; TcpConnectionPtr connection; Buffer pending; }; class DemuxServer : boost::noncopyable { public: DemuxServer(EventLoop* loop, const InetAddress& listenAddr, const InetAddress& socksAddr) : loop_(loop), server_(loop, listenAddr, "DemuxServer"), socksAddr_(socksAddr) { server_.setConnectionCallback( boost::bind(&DemuxServer::onServerConnection, this, _1)); server_.setMessageCallback( boost::bind(&DemuxServer::onServerMessage, this, _1, _2, _3)); } void start() { server_.start(); } void onServerConnection(const TcpConnectionPtr& conn) { if (conn->connected()) { if (serverConn_) { conn->shutdown(); } else { serverConn_ = conn; LOG_INFO << "onServerConnection set serverConn_"; } } else { if (serverConn_ == conn) { serverConn_.reset(); socksConns_.clear(); LOG_INFO << "onServerConnection reset serverConn_"; } } } void onServerMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp) { while (buf->readableBytes() > kHeaderLen) { size_t len = static_cast<uint8_t>(*buf->peek()); if (buf->readableBytes() < len + kHeaderLen) { break; } else { int connId = static_cast<uint8_t>(buf->peek()[1]); connId |= (static_cast<uint8_t>(buf->peek()[2]) << 8); if (connId != 0) { assert(socksConns_.find(connId) != socksConns_.end()); TcpConnectionPtr& socksConn = socksConns_[connId].connection; if (socksConn) { assert(socksConns_[connId].pending.readableBytes() == 0); socksConn->send(buf->peek() + kHeaderLen, len); } else { socksConns_[connId].pending.append(buf->peek() + kHeaderLen, len); } } else { string cmd(buf->peek() + kHeaderLen, len); doCommand(cmd); } buf->retrieve(len + kHeaderLen); } } } void doCommand(const string& cmd) { static const string kConn = "CONN "; int connId = atoi(&cmd[kConn.size()]); bool isUp = cmd.find(" IS UP") != string::npos; LOG_INFO << "doCommand " << connId << " " << isUp; if (isUp) { assert(socksConns_.find(connId) == socksConns_.end()); char connName[256]; snprintf(connName, sizeof connName, "SocksClient %d", connId); Entry entry; entry.connId = connId; entry.client.reset(new TcpClient(loop_, socksAddr_, connName)); entry.client->setConnectionCallback( boost::bind(&DemuxServer::onSocksConnection, this, connId, _1)); entry.client->setMessageCallback( boost::bind(&DemuxServer::onSocksMessage, this, connId, _1, _2, _3)); // FIXME: setWriteCompleteCallback socksConns_[connId] = entry; entry.client->connect(); } else { assert(socksConns_.find(connId) != socksConns_.end()); TcpConnectionPtr& socksConn = socksConns_[connId].connection; if (socksConn) { socksConn->shutdown(); } else { socksConns_.erase(connId); } } } void onSocksConnection(int connId, const TcpConnectionPtr& conn) { assert(socksConns_.find(connId) != socksConns_.end()); if (conn->connected()) { socksConns_[connId].connection = conn; Buffer& pendingData = socksConns_[connId].pending; if (pendingData.readableBytes() > 0) { conn->send(&pendingData); } } else { if (serverConn_) { char buf[256]; int len = snprintf(buf, sizeof(buf), "DISCONNECT %d\r\n", connId); Buffer buffer; buffer.append(buf, len); sendServerPacket(0, &buffer); } else { socksConns_.erase(connId); } } } void onSocksMessage(int connId, const TcpConnectionPtr& conn, Buffer* buf, Timestamp) { assert(socksConns_.find(connId) != socksConns_.end()); while (buf->readableBytes() > kMaxPacketLen) { Buffer packet; packet.append(buf->peek(), kMaxPacketLen); buf->retrieve(kMaxPacketLen); sendServerPacket(connId, &packet); } if (buf->readableBytes() > 0) { sendServerPacket(connId, buf); } } void sendServerPacket(int connId, Buffer* buf) { size_t len = buf->readableBytes(); LOG_DEBUG << len; assert(len <= kMaxPacketLen); uint8_t header[kHeaderLen] = { static_cast<uint8_t>(len), static_cast<uint8_t>(connId & 0xFF), static_cast<uint8_t>((connId & 0xFF00) >> 8) }; buf->prepend(header, kHeaderLen); if (serverConn_) { serverConn_->send(buf); } } EventLoop* loop_; TcpServer server_; TcpConnectionPtr serverConn_; const InetAddress socksAddr_; std::map<int, Entry> socksConns_; }; int main(int argc, char* argv[]) { LOG_INFO << "pid = " << getpid(); EventLoop loop; InetAddress listenAddr(kListenPort); if (argc > 1) { socksIp = argv[1]; } InetAddress socksAddr(socksIp, kSocksPort); DemuxServer server(&loop, listenAddr, socksAddr); server.start(); loop.loop(); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljscomponentfromobjectdef.h" #include "qmljscomponentnamedialog.h" #include <coreplugin/ifile.h> #include <qmljs/parser/qmljsast_p.h> #include <qmljs/qmljsdocument.h> #include <qmljstools/qmljsrefactoringchanges.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> using namespace QmlJS::AST; using namespace QmlJSEditor; using namespace QmlJSEditor::Internal; using namespace QmlJSTools; namespace { static QString toString(Statement *statement) { ExpressionStatement *expStmt = cast<ExpressionStatement *>(statement); if (!expStmt) return QString::null; if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) { return idExp->name->asString(); } else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) { return strExp->value->asString(); } return QString::null; } static QString getIdProperty(UiObjectDefinition *def) { QString objectName; if (def && def->initializer) { for (UiObjectMemberList *iter = def->initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name) { if (script->qualifiedId->name->asString() == QLatin1String("id")) return toString(script->statement); if (script->qualifiedId->name->asString() == QLatin1String("objectName")) objectName = toString(script->statement); } } } } return objectName; } class Operation: public QmlJSQuickFixOperation { UiObjectDefinition *m_objDef; QString m_componentName; public: Operation(const QmlJSQuickFixState &state, UiObjectDefinition *objDef) : QmlJSQuickFixOperation(state, 0) , m_objDef(objDef) { Q_ASSERT(m_objDef != 0); m_componentName = getIdProperty(m_objDef); if (m_componentName.isEmpty()) { setDescription(QCoreApplication::translate("QmlJSEditor::ComponentFromObjectDef", "Move Component into separate file")); } else { m_componentName[0] = m_componentName.at(0).toUpper(); setDescription(QCoreApplication::translate("QmlJSEditor::ComponentFromObjectDef", "Move Component into '%1.qml'").arg(m_componentName)); } } virtual void performChanges(QmlJSRefactoringFile *currentFile, QmlJSRefactoringChanges *refactoring) { QString componentName = m_componentName; QString path = QFileInfo(fileName()).path(); if (componentName.isEmpty()) { ComponentNameDialog::go(&componentName, &path, state().editor()); } if (componentName.isEmpty() || path.isEmpty()) return; const QString newFileName = path + QDir::separator() + componentName + QLatin1String(".qml"); QString imports; UiProgram *prog = currentFile->qmljsDocument()->qmlProgram(); if (prog && prog->imports) { const int start = currentFile->startOf(prog->imports->firstSourceLocation()); const int end = currentFile->startOf(prog->members->member->firstSourceLocation()); imports = currentFile->textOf(start, end); } const int start = currentFile->startOf(m_objDef->firstSourceLocation()); const int end = currentFile->startOf(m_objDef->lastSourceLocation()); const QString txt = imports + currentFile->textOf(start, end) + QLatin1String("}\n"); // stop if we can't create the new file if (!refactoring->createFile(newFileName, txt)) return; Utils::ChangeSet changes; changes.replace(start, end, componentName + QLatin1String(" {\n")); currentFile->change(changes); currentFile->indent(Range(start, end + 1)); } }; } // end of anonymous namespace QList<QmlJSQuickFixOperation::Ptr> ComponentFromObjectDef::match(const QmlJSQuickFixState &state) { const int pos = state.currentFile().cursor().position(); QList<Node *> path = state.semanticInfo().astPath(pos); for (int i = path.size() - 1; i >= 0; --i) { Node *node = path.at(i); if (UiObjectDefinition *objDef = cast<UiObjectDefinition *>(node)) { if (!state.currentFile().isCursorOn(objDef->qualifiedTypeNameId)) return noResult(); // check that the node is not the root node if (i > 0 && !cast<UiProgram*>(path.at(i - 1))) { return singleResult(new Operation(state, objDef)); } } } return noResult(); } <commit_msg>Retain id when creating a component from an object.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljscomponentfromobjectdef.h" #include "qmljscomponentnamedialog.h" #include <coreplugin/ifile.h> #include <qmljs/parser/qmljsast_p.h> #include <qmljs/qmljsdocument.h> #include <qmljstools/qmljsrefactoringchanges.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> using namespace QmlJS::AST; using namespace QmlJSEditor; using namespace QmlJSEditor::Internal; using namespace QmlJSTools; namespace { static QString toString(Statement *statement) { ExpressionStatement *expStmt = cast<ExpressionStatement *>(statement); if (!expStmt) return QString::null; if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) { return idExp->name->asString(); } else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) { return strExp->value->asString(); } return QString::null; } static QString getIdProperty(UiObjectDefinition *def) { QString objectName; if (def && def->initializer) { for (UiObjectMemberList *iter = def->initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name) { if (script->qualifiedId->name->asString() == QLatin1String("id")) return toString(script->statement); if (script->qualifiedId->name->asString() == QLatin1String("objectName")) objectName = toString(script->statement); } } } } return objectName; } class Operation: public QmlJSQuickFixOperation { UiObjectDefinition *m_objDef; QString m_idName, m_componentName; public: Operation(const QmlJSQuickFixState &state, UiObjectDefinition *objDef) : QmlJSQuickFixOperation(state, 0) , m_objDef(objDef) { Q_ASSERT(m_objDef != 0); m_idName = getIdProperty(m_objDef); if (m_idName.isEmpty()) { setDescription(QCoreApplication::translate("QmlJSEditor::ComponentFromObjectDef", "Move Component into separate file")); } else { m_componentName = m_idName; m_componentName[0] = m_componentName.at(0).toUpper(); setDescription(QCoreApplication::translate("QmlJSEditor::ComponentFromObjectDef", "Move Component into '%1.qml'").arg(m_componentName)); } } virtual void performChanges(QmlJSRefactoringFile *currentFile, QmlJSRefactoringChanges *refactoring) { QString componentName = m_componentName; QString path = QFileInfo(fileName()).path(); if (componentName.isEmpty()) { ComponentNameDialog::go(&componentName, &path, state().editor()); } if (componentName.isEmpty() || path.isEmpty()) return; const QString newFileName = path + QDir::separator() + componentName + QLatin1String(".qml"); QString imports; UiProgram *prog = currentFile->qmljsDocument()->qmlProgram(); if (prog && prog->imports) { const int start = currentFile->startOf(prog->imports->firstSourceLocation()); const int end = currentFile->startOf(prog->members->member->firstSourceLocation()); imports = currentFile->textOf(start, end); } const int start = currentFile->startOf(m_objDef->firstSourceLocation()); const int end = currentFile->startOf(m_objDef->lastSourceLocation()); const QString txt = imports + currentFile->textOf(start, end) + QLatin1String("}\n"); // stop if we can't create the new file if (!refactoring->createFile(newFileName, txt)) return; QString replacement = componentName + QLatin1String(" {\n"); if (!m_idName.isEmpty()) replacement += QLatin1String("id: ") + m_idName + QLatin1Char('\n'); Utils::ChangeSet changes; changes.replace(start, end, replacement); currentFile->change(changes); currentFile->indent(Range(start, end + 1)); } }; } // end of anonymous namespace QList<QmlJSQuickFixOperation::Ptr> ComponentFromObjectDef::match(const QmlJSQuickFixState &state) { const int pos = state.currentFile().cursor().position(); QList<Node *> path = state.semanticInfo().astPath(pos); for (int i = path.size() - 1; i >= 0; --i) { Node *node = path.at(i); if (UiObjectDefinition *objDef = cast<UiObjectDefinition *>(node)) { if (!state.currentFile().isCursorOn(objDef->qualifiedTypeNameId)) return noResult(); // check that the node is not the root node if (i > 0 && !cast<UiProgram*>(path.at(i - 1))) { return singleResult(new Operation(state, objDef)); } } } return noResult(); } <|endoftext|>
<commit_before>#include "VDLog.h" using namespace VideoDromm; VDLog::VDLog() { //fs::path path; //path = getAppPath() / "log"; //auto bLog = log::makeLogger<log::LoggerBreakpoint>(); //bLog->setTriggerLevel(log::LEVEL_ERROR); //log::makeLogger<log::LoggerFileRotating>(path.string(), "videodromm.%Y.%m.%d.txt", false); } <commit_msg>sysLogger<commit_after>#include "VDLog.h" using namespace VideoDromm; VDLog::VDLog() { auto sysLogger = log::makeLogger<log::LoggerSystem>(); sysLogger->setLoggingLevel(log::LEVEL_WARNING); #ifdef _DEBUG /* fs::path path; path = getAppPath() / "log"; auto bLog = log::makeLogger<log::LoggerBreakpoint>(); bLog->setTriggerLevel(log::LEVEL_ERROR); log::makeLogger<log::LoggerFileRotating>(path.string(), "videodromm.%Y.%m.%d.txt", false);*/ log::makeLogger<log::LoggerFileRotating>("/tmp/videodromm", "videodromm.%Y.%m.%d.txt", false); #else #endif // _DEBUG } <|endoftext|>
<commit_before>#ifndef STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP #define STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/analyze/mcmc/autocovariance.hpp> #include <stan/analyze/mcmc/split_chains.hpp> #include <algorithm> #include <cmath> #include <vector> namespace stan { namespace analyze { /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param std::vector stores pointers to arrays of chains * @param std::vector stores sizes of chains * @return effective sample size for the specified parameter */ template <typename DerivedA, typename DerivedB> inline double effective_sample_size_impl(const Eigen::MatrixBase<DerivedA>& acov, const Eigen::MatrixBase<DerivedB>& chain_mean) { int num_chains = chain_mean.size(); Eigen::VectorXd chain_var(num_chains); for (int chain = 0; chain < num_chains; ++chain) { chain_var(chain) = acov(chain)(0); } // need to generalize to each jagged draws per chain int num_draws = acov(0).size(); double mean_var = chain_var.mean() * num_draws / (num_draws - 1); double var_plus = mean_var * (num_draws - 1) / num_draws; if (num_chains > 1) var_plus += (chain_mean.array() - chain_mean.mean()).square().sum() / (num_chains - 1); Eigen::VectorXd rho_hat_s(num_draws); rho_hat_s.setZero(); Eigen::VectorXd acov_s(num_chains); for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(1); double rho_hat_even = 1.0; rho_hat_s(0) = rho_hat_even; double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; rho_hat_s(1) = rho_hat_odd; // Geyer's initial positive sequence size_t s = 1; for (; s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0; s += 2) { for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 1); rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus; for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 2); rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; if ((rho_hat_even + rho_hat_odd) >= 0) { rho_hat_s(s + 1) = rho_hat_even; rho_hat_s(s + 2) = rho_hat_odd; } } int max_s = s; // this is used in the improved estimate if (rho_hat_even > 0) rho_hat_s(max_s + 1) = rho_hat_even; // Geyer's initial monotone sequence for (int s = 1; s <= max_s - 3; s += 2) { if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) { rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2; rho_hat_s(s + 2) = rho_hat_s(s + 1); } } double ess = num_chains * num_draws; // Geyer's truncated estimate // Improved estimate reduces variance in antithetic case double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1); // Safety check for negative values and with max ess equal to ess*log10(ess) return ess / std::max(tau_hat, 1 / std::log10(ess)); } /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param Eigen::MatrixBase stores arrays of chains * @return effective sample size for the specified parameter */ template <typename Derived> inline double compute_effective_sample_size(const Eigen::MatrixBase<Derived>& draws) { int num_chains = draws.cols(); Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains); Eigen::VectorXd chain_mean(num_chains); for (int chain = 0; chain < num_chains; ++chain) { autocovariance<double>(draws.col(chain), acov(chain)); chain_mean(chain) = draws.col(chain).mean(); } return effective_sample_size_impl(acov, chain_mean); } /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param std::vector stores pointers to arrays of chains * @param std::vector stores sizes of chains * @return effective sample size for the specified parameter */ inline double compute_effective_sample_size(std::vector<const double*> draws, std::vector<size_t> sizes) { // std::cout << compute_effective_sample_size(split_chains(draws, sizes)) // << std::endl; int num_chains = sizes.size(); Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains); Eigen::VectorXd chain_mean(num_chains); for (int chain = 0; chain < num_chains; ++chain) { Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(draws[chain], sizes[chain]); autocovariance<double>(draw, acov(chain)); chain_mean(chain) = draw.mean(); } return effective_sample_size_impl(acov, chain_mean); } inline double compute_effective_sample_size(std::vector<const double*> draws, size_t size) { int num_chains = draws.size(); std::vector<size_t> sizes(num_chains, size); return compute_effective_sample_size(draws, sizes); } } // namespace analyze } // namespace stan #endif <commit_msg>slight doc changes<commit_after>#ifndef STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP #define STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/analyze/mcmc/autocovariance.hpp> #include <stan/analyze/mcmc/split_chains.hpp> #include <algorithm> #include <cmath> #include <vector> namespace stan { namespace analyze { /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param Eigen::VectorXd stores autocovariance of each chain * @param Eigen::VectorXd stores means of each chain * @return effective sample size for the specified parameter */ template <typename DerivedA, typename DerivedB> inline double effective_sample_size_impl(const Eigen::MatrixBase<DerivedA>& acov, const Eigen::MatrixBase<DerivedB>& chain_mean) { int num_chains = chain_mean.size(); Eigen::VectorXd chain_var(num_chains); for (int chain = 0; chain < num_chains; ++chain) { chain_var(chain) = acov(chain)(0); } // need to generalize to each jagged draws per chain int num_draws = acov(0).size(); double mean_var = chain_var.mean() * num_draws / (num_draws - 1); double var_plus = mean_var * (num_draws - 1) / num_draws; if (num_chains > 1) var_plus += (chain_mean.array() - chain_mean.mean()).square().sum() / (num_chains - 1); Eigen::VectorXd rho_hat_s(num_draws); rho_hat_s.setZero(); Eigen::VectorXd acov_s(num_chains); for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(1); double rho_hat_even = 1.0; rho_hat_s(0) = rho_hat_even; double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; rho_hat_s(1) = rho_hat_odd; // Geyer's initial positive sequence size_t s = 1; for (; s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0; s += 2) { for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 1); rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus; for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 2); rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; if ((rho_hat_even + rho_hat_odd) >= 0) { rho_hat_s(s + 1) = rho_hat_even; rho_hat_s(s + 2) = rho_hat_odd; } } int max_s = s; // this is used in the improved estimate if (rho_hat_even > 0) rho_hat_s(max_s + 1) = rho_hat_even; // Geyer's initial monotone sequence for (int s = 1; s <= max_s - 3; s += 2) { if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) { rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2; rho_hat_s(s + 2) = rho_hat_s(s + 1); } } double ess = num_chains * num_draws; // Geyer's truncated estimate // Improved estimate reduces variance in antithetic case double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1); // Safety check for negative values and with max ess equal to ess*log10(ess) return ess / std::max(tau_hat, 1 / std::log10(ess)); } /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param Eigen::MatrixBase stores arrays of chains * @return effective sample size for the specified parameter */ template <typename Derived> inline double compute_effective_sample_size(const Eigen::MatrixBase<Derived>& draws) { int num_chains = draws.cols(); Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains); Eigen::VectorXd chain_mean(num_chains); for (int chain = 0; chain < num_chains; ++chain) { autocovariance<double>(draws.col(chain), acov(chain)); chain_mean(chain) = draws.col(chain).mean(); } return effective_sample_size_impl(acov, chain_mean); } /** * Returns the effective sample size for the specified parameter * across all kept samples. * * See more details in Stan reference manual section "Effective * Sample Size". http://mc-stan.org/users/documentation * * Current implementation assumes chains are all of equal size and * draws are stored in contiguous blocks of memory. * * @param std::vector stores pointers to arrays of chains * @param std::vector stores sizes of chains * @return effective sample size for the specified parameter */ inline double compute_effective_sample_size(std::vector<const double*> draws, std::vector<size_t> sizes) { // std::cout << compute_effective_sample_size(split_chains(draws, sizes)) // << std::endl; int num_chains = sizes.size(); Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains); Eigen::VectorXd chain_mean(num_chains); for (int chain = 0; chain < num_chains; ++chain) { Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(draws[chain], sizes[chain]); autocovariance<double>(draw, acov(chain)); chain_mean(chain) = draw.mean(); } return effective_sample_size_impl(acov, chain_mean); } inline double compute_effective_sample_size(std::vector<const double*> draws, size_t size) { int num_chains = draws.size(); std::vector<size_t> sizes(num_chains, size); return compute_effective_sample_size(draws, sizes); } } // namespace analyze } // namespace stan #endif <|endoftext|>
<commit_before>/* * Glib::Dispatcher example -- cross thread signalling * by Daniel Elstner <daniel.elstner@gmx.net> * * modified to only use glibmm * by J. Abelardo Gutierrez <jabelardo@cantv.net> * * Copyright (c) 2002-2003 Free Software Foundation */ #include <sigc++/class_slot.h> #include <glibmm.h> #include <iostream> #include <algorithm> #include <functional> #include <list> namespace { Glib::RefPtr<Glib::MainLoop> main_loop; class ThreadProgress : public sigc::trackable { public: ThreadProgress(int id, Glib::Mutex& mtx); virtual ~ThreadProgress(); void launch(); typedef sigc::signal<void, ThreadProgress*> type_signal_finished; type_signal_finished& signal_finished(); int id() const; private: unsigned int progress_; Glib::Dispatcher signal_increment_; type_signal_finished signal_finished_; int id_; Glib::Mutex& cout_mutex_; void progress_increment(); void thread_function(); }; //TODO: Rename to avoid confusion with Glib::Dispatcher. class Dispatcher : public sigc::trackable { public: Dispatcher(); virtual ~Dispatcher(); void launch_threads(); private: std::list<ThreadProgress*> progress_list_; Glib::Mutex cout_mutex_; void on_progress_finished(ThreadProgress* progress); }; ThreadProgress::ThreadProgress(int id, Glib::Mutex& mtx) : progress_ (0), id_ (id), cout_mutex_ (mtx) { // Connect to the cross-thread signal. signal_increment_.connect(sigc::mem_fun(*this, &ThreadProgress::progress_increment)); } ThreadProgress::~ThreadProgress() {} void ThreadProgress::launch() { // Create a non-joinable thread -- it's deleted automatically on thread exit. Glib::Thread::create(sigc::mem_fun(*this, &ThreadProgress::thread_function), false); } ThreadProgress::type_signal_finished& ThreadProgress::signal_finished() { return signal_finished_; } int ThreadProgress::id() const { return id_; } void ThreadProgress::progress_increment() { // Use an integer because floating point arithmetic is inaccurate -- // we want to finish *exactly* after the 100th increment. ++progress_; cout_mutex_.lock(); std::cout << "Thread " << id_ << ": " << progress_ << " %" << std::endl; cout_mutex_.unlock(); if(progress_ >= 100) signal_finished().emit(this); } void ThreadProgress::thread_function() { Glib::Rand rand; int usecs = 5000; for(int i = 0; i < 100; ++i) { usecs = rand.get_int_range(std::max(0, usecs - 1000 - i), std::min(20000, usecs + 1000 + i)); Glib::usleep(usecs); // Tell the thread to increment the progress value. signal_increment_.emit(); } } Dispatcher::Dispatcher() : cout_mutex_ () { std::cout << "Thread Dispatcher Example." << std::endl; for(int i = 0; i < 5; ++i) { ThreadProgress *const progress = new ThreadProgress(i, cout_mutex_); progress_list_.push_back(progress); progress->signal_finished().connect( sigc::mem_fun(*this, &Dispatcher::on_progress_finished)); } } Dispatcher::~Dispatcher() {} void Dispatcher::launch_threads() { std::for_each( progress_list_.begin(), progress_list_.end(), std::mem_fun(&ThreadProgress::launch)); } void Dispatcher::on_progress_finished(ThreadProgress* progress) { cout_mutex_.lock(); std::cout << "Thread " << progress->id() << ": finished." << std::endl; cout_mutex_.unlock(); progress_list_.remove(progress); if(progress_list_.empty()) main_loop->quit(); } } // anonymous namespace int main(int argc, char** argv) { Glib::thread_init(); main_loop = Glib::MainLoop::create(); Dispatcher dispatcher; // Install a one-shot idle handler to launch the threads Glib::signal_idle().connect( sigc::bind_return(sigc::mem_fun(dispatcher, &Dispatcher::launch_threads), false)); main_loop->run(); return 0; } <commit_msg>Code cleanup. Most importantly, get rid of the locking around std::cout<commit_after>/* * Glib::Dispatcher example -- cross thread signalling * by Daniel Elstner <daniel.elstner@gmx.net> * * modified to only use glibmm * by J. Abelardo Gutierrez <jabelardo@cantv.net> * * Copyright (c) 2002-2003 Free Software Foundation */ #include <glibmm.h> #include <algorithm> #include <functional> #include <iostream> #include <list> #include <memory> namespace { class ThreadProgress { public: explicit ThreadProgress(int id); ~ThreadProgress(); void launch(); sigc::signal<void>& signal_finished(); int id() const; private: int id_; unsigned int progress_; Glib::Dispatcher signal_increment_; sigc::signal<void> signal_finished_; void progress_increment(); void thread_function(); }; class Application : public sigc::trackable { public: Application(); virtual ~Application(); void launch_threads(); void run(); private: Glib::RefPtr<Glib::MainLoop> main_loop_; std::list<ThreadProgress*> progress_list_; void on_progress_finished(ThreadProgress* thread_progress); }; ThreadProgress::ThreadProgress(int id) : id_ (id), progress_ (0) { // Connect to the cross-thread signal. signal_increment_.connect(sigc::mem_fun(*this, &ThreadProgress::progress_increment)); } ThreadProgress::~ThreadProgress() {} void ThreadProgress::launch() { // Create a non-joinable thread -- it's deleted automatically on thread exit. Glib::Thread::create(sigc::mem_fun(*this, &ThreadProgress::thread_function), false); } sigc::signal<void>& ThreadProgress::signal_finished() { return signal_finished_; } int ThreadProgress::id() const { return id_; } void ThreadProgress::progress_increment() { // Use an integer because floating point arithmetic is inaccurate -- // we want to finish *exactly* after the 100th increment. ++progress_; std::cout << "Thread " << id_ << ": " << progress_ << '%' << std::endl; if(progress_ >= 100) signal_finished_(); } void ThreadProgress::thread_function() { Glib::Rand rand; int usecs = 5000; for(int i = 0; i < 100; ++i) { usecs = rand.get_int_range(std::max(0, usecs - 1000 - i), std::min(20000, usecs + 1000 + i)); Glib::usleep(usecs); // Tell the main thread to increment the progress value. signal_increment_(); } } Application::Application() : main_loop_ (Glib::MainLoop::create()) { std::cout << "Thread Dispatcher Example." << std::endl; for(int i = 1; i <= 5; ++i) { std::auto_ptr<ThreadProgress> progress (new ThreadProgress(i)); progress_list_.push_back(progress.get()); progress->signal_finished().connect( sigc::bind(sigc::mem_fun(*this, &Application::on_progress_finished), progress.release())); } } Application::~Application() {} void Application::launch_threads() { std::for_each(progress_list_.begin(), progress_list_.end(), std::mem_fun(&ThreadProgress::launch)); } void Application::run() { main_loop_->run(); } void Application::on_progress_finished(ThreadProgress* thread_progress) { { const std::auto_ptr<ThreadProgress> progress (thread_progress); progress_list_.remove(progress.get()); std::cout << "Thread " << progress->id() << ": finished." << std::endl; } if(progress_list_.empty()) main_loop_->quit(); } } // anonymous namespace int main(int argc, char** argv) { Glib::thread_init(); Application application; // Install a one-shot idle handler to launch the threads Glib::signal_idle().connect( sigc::bind_return(sigc::mem_fun(application, &Application::launch_threads), false)); application.run(); return 0; } <|endoftext|>
<commit_before>#include <string.h> #include "base/logging.h" #include "gfx/gl_common.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) && !defined(BLACKBERRY) #ifndef GL_READ_FRAMEBUFFER #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #endif #ifndef GL_RGBA8 #define GL_RGBA8 GL_RGBA #endif #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif #ifdef IOS extern void bindDefaultFBO(); #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. #ifndef USING_GLES2 FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffersEXT(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height); //glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } #endif FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); #ifndef USING_GLES2 if(!gl_extensions.FBO_ARB) return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth); #endif FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { CheckGLExtensions(); if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); #endif } #ifdef IOS bindDefaultFBO(); #endif } void fbo_bind_as_render_target(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_for_read(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_color_as_texture(FBO *fbo, int color) { if (fbo) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } } void fbo_destroy(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &fbo->handle); glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer); #endif } glDeleteTextures(1, &fbo->color_texture); delete fbo; } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; } int fbo_get_color_texture(FBO *fbo) { return fbo->color_texture; } <commit_msg>Revert "Fix a redeclaration warning."<commit_after>#include <string.h> #include "base/logging.h" #include "gfx/gl_common.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) && !defined(BLACKBERRY) #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #define GL_RGBA8 GL_RGBA #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif #ifdef IOS extern void bindDefaultFBO(); #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. #ifndef USING_GLES2 FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffersEXT(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height); //glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } #endif FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); #ifndef USING_GLES2 if(!gl_extensions.FBO_ARB) return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth); #endif FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { CheckGLExtensions(); if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); #endif } #ifdef IOS bindDefaultFBO(); #endif } void fbo_bind_as_render_target(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_for_read(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_color_as_texture(FBO *fbo, int color) { if (fbo) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } } void fbo_destroy(FBO *fbo) { if(gl_extensions.FBO_ARB){ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &fbo->handle); glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer); #endif } glDeleteTextures(1, &fbo->color_texture); delete fbo; } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; } int fbo_get_color_texture(FBO *fbo) { return fbo->color_texture; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <fstream> #include <vector> #include <memory> #include <algorithm> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CDoorway.h" #include "CMap.h" #include "CDoorway.h" #include "CBaphomet.h" #include "CCuco.h" #include "CDemon.h" #include "CMoura.h" #include "CWizard.h" #include "IRenderer.h" #include "CConsoleRenderer.h" #include "CGame.h" #include "CFireball.h" namespace WizardOfGalicia { std::string CGame::readMap( std::string mapName ) { std::string entry; std::ifstream mapFile( "res/map1.txt" ); char line[ 80 ]; while ( !mapFile.eof() ) { mapFile >> line; entry += line; } auto position = entry.find('\n' ); while ( position != std::string::npos ) { entry.replace( position, 1, "" ); position = entry.find( '\n', position + 1); } return entry; } void CGame::endOfTurn() { map->endOfTurn(); ++turn; } void CGame::update() { for ( auto actor : map->actors ) { if ( actor->hp > 0 ) { actor->update(map); } else { map->map[ actor->position.y][actor->position.x] = nullptr; } } map->actors.erase( std::remove_if( map->actors.begin(), map->actors.end(), [](std::shared_ptr<CActor> actor){ return actor->hp <= 0;} ), map->actors.end() ); } void CGame::runGame( IRenderer *renderer ) { turn = 1; std::string entry; std::string mapData = readMap( "res/map1.txt" ); map = std::make_shared<CMap>( mapData ); std::shared_ptr<CActor> avatar = map->mWizard; while ( true ) { renderer->drawMap( *map, avatar ); if ( avatar != nullptr && avatar->hp <= 0 ) { std::cout << "DEAD" << std::endl; avatar = nullptr; } std::cin >> entry; if ( avatar != nullptr ) { if ( entry == "s" ) { map->move( Direction::E, avatar ); } if ( entry == "w" ) { map->move( Direction::N, avatar ); } if ( entry == "a" ) { map->move( Direction::W, avatar ); } if ( entry == "i" ) { avatar->turnLeft(); } if ( entry == "o" ) { map->move( avatar->direction, avatar ); } if ( entry == "p" ) { avatar->turnRight(); } if ( entry == "k" ) { } if ( entry == "l" ) { } if ( entry == "f" ) { map->cast( avatar ); } if ( entry == "z" ) { map->move( Direction::S, avatar ); } if ( entry == "c" ) { int x; int y; std::cout << "target x?" << std::endl; std::cin >> x; std::cout << "target y?" << std::endl; std::cin >> y; map->attack( avatar, x, y, false ); } update(); endOfTurn(); } } } } <commit_msg>Only end a turn and update game stats for players moving and firing<commit_after>#include <string> #include <iostream> #include <fstream> #include <vector> #include <memory> #include <algorithm> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CDoorway.h" #include "CMap.h" #include "CDoorway.h" #include "CBaphomet.h" #include "CCuco.h" #include "CDemon.h" #include "CMoura.h" #include "CWizard.h" #include "IRenderer.h" #include "CConsoleRenderer.h" #include "CGame.h" #include "CFireball.h" namespace WizardOfGalicia { std::string CGame::readMap( std::string mapName ) { std::string entry; std::ifstream mapFile( "res/map1.txt" ); char line[ 80 ]; while ( !mapFile.eof() ) { mapFile >> line; entry += line; } auto position = entry.find('\n' ); while ( position != std::string::npos ) { entry.replace( position, 1, "" ); position = entry.find( '\n', position + 1); } return entry; } void CGame::endOfTurn() { map->endOfTurn(); ++turn; } void CGame::update() { for ( auto actor : map->actors ) { if ( actor->hp > 0 ) { actor->update(map); } else { map->map[ actor->position.y][actor->position.x] = nullptr; } } map->actors.erase( std::remove_if( map->actors.begin(), map->actors.end(), [](std::shared_ptr<CActor> actor){ return actor->hp <= 0;} ), map->actors.end() ); } void CGame::runGame( IRenderer *renderer ) { turn = 1; bool shouldEndTurn = false; std::string entry; std::string mapData = readMap( "res/map1.txt" ); map = std::make_shared<CMap>( mapData ); std::shared_ptr<CActor> avatar = map->mWizard; while ( true ) { renderer->drawMap( *map, avatar ); if ( avatar != nullptr && avatar->hp <= 0 ) { std::cout << "DEAD" << std::endl; avatar = nullptr; } std::cin >> entry; if ( avatar != nullptr ) { if ( entry == "s" ) { map->move( Direction::E, avatar ); shouldEndTurn = true; } if ( entry == "w" ) { map->move( Direction::N, avatar ); shouldEndTurn = true; } if ( entry == "a" ) { map->move( Direction::W, avatar ); shouldEndTurn = true; } if ( entry == "i" ) { avatar->turnLeft(); } if ( entry == "o" ) { shouldEndTurn = true; map->move( avatar->direction, avatar ); } if ( entry == "p" ) { avatar->turnRight(); } if ( entry == "k" ) { } if ( entry == "l" ) { } if ( entry == "f" ) { map->cast( avatar ); shouldEndTurn = true; } if ( entry == "z" ) { map->move( Direction::S, avatar ); } if ( shouldEndTurn ) { update(); endOfTurn(); shouldEndTurn = false; } } } } } <|endoftext|>
<commit_before>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = 0; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = 0; line_len = 0; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string removeIupac(string& str) { for (int i=0; i<str.length(); ++i) { char c = str[i]; if (c != 'A' && c != 'T' && c != 'G' && c != 'C' && c != 'N' && c != 'a' && c != 't' && c != 'g' && c != 'c' && c != 'n') { str[i] = 'N'; } } return str; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupac(s); } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); length = min(length, entry.length - start); if (start < 0 || length < 1) { return ""; } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupac(s); } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <commit_msg>Clean up whitespace and shorten code<commit_after>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = 0; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = 0; line_len = 0; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string removeIupacBases(string& str) { const string bases = "ATGCNatgcn"; size_t found = str.find_first_not_of(bases); while (found != string::npos) { str[found] = 'N'; found = str.find_first_not_of(bases, found + 1); } return str; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupacBases(s); } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); length = min(length, entry.length - start); if (start < 0 || length < 1) { return ""; } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupacBases(s); } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <|endoftext|>
<commit_before>#include "Graph.h" #include <algorithm> #include <queue> #include <stack> #include <set> vertex* Graph::at(const std::string& name)const { auto it = m_V.find(name); if(it != m_V.end()) { return it->second; } else throw; } std::vector<std::string> Graph::getkeys()const { std::vector<std::string> ret; ret.resize(size()); int ind = 0; for(auto& i : m_V) { ret[ind++] = i.first; } return ret; } void Graph::filladj(const std::vector<std::string>& names, const Graph& g) { for(size_t i = 0; i < m_V.size(); i++) { auto it = m_V.find(names[i]); vertex* tmp = g.at(names[i]); vertex* pIt = it->second; for(auto& j : tmp->adj) { //1.cost //2.vertex* in this graph pIt->adj.push_back(std::make_pair(j.first, m_V.find(j.second->name)->second)); } } } Graph::Graph(const Graph& g) { std::vector<std::string> names = g.getkeys(); for(size_t i = 0; i < g.size(); i++) addvertex(names[i]); filladj(names,g); } /* As long as there are vertexes change name,clean adjacency list. x After that create new vertexes. x Then fill adjacency lists. Clean remaining not needed vertexes x */ Graph& Graph::operator=(const Graph& g) { int n = m_V.size() - g.size(); ///if there are more vertexes than needed: n > 0 ///if it is just the right size: n = 0 ///if there are not enough vertexes: n < 0 std::vector<std::string> names = getkeys(); std::vector<std::string> namesTO = g.getkeys(); if(!(n<0)) { for(size_t i = 0; i < g.size(); i++) { auto it = m_V.find(names[i]); it->second->name = namesTO[i]; it->second->adj.clear(); } //Clean remaining not needed vertexes for(int i = g.size(); i < n; i++) removevertex(names[i]); } else { for(size_t i = 0; i < g.size(); i++) addvertex(namesTO[i]); } //Filling adjacency list filladj(namesTO,g); return *this; } Graph::~Graph() { if(!m_V.empty()) { for(auto& i : m_V) delete i.second; } } Graph::vmap::iterator Graph::addvertex(const std::string& name) { auto it=m_V.find(name); if(it==m_V.end()) { vertex *v; v = new vertex(name); m_V[name]=v; return it; } return m_V.end(); } void Graph::addedge(const std::string& from, const std::string& to, int cost) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { vertex *f = (fromIt->second); vertex *t = (toIt->second); std::pair<int,vertex*> edge = std::make_pair(cost,t); f->adj.push_back(edge); } } //Currently fixed(Use removeedge in later versions?) void Graph::removevertex(const std::string& name) { auto it = m_V.find(name); if(it != m_V.end()) { for(auto& i : m_V) { if(i.second != it->second) { vertex* v = i.second; for(auto& j : v->adj) { if(j.second->name == name) { v->adj.erase(std::find(v->adj.begin(),v->adj.end(), j)); } } } } delete it->second; m_V.erase(it); } } //works correctly void Graph::removeedge(const std::string& from, const std::string& to) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { vertex* v = fromIt->second; size_t i = 0; while(i < v->adj.size() && !(v->adj[i].second->name == to)) i++; if(i < v->adj.size()) { v->adj.erase(v->adj.begin()+i); } } } bool Graph::adjacent(const std::string& from, const std::string& to) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { for(auto& i : fromIt->second->adj) { if(i.second->name == to) { return true; } } } return false; } std::vector<std::string> Graph::neighbours(const std::string& name) { auto it = m_V.find(name); std::vector<std::string> ret; if(it != m_V.end()) { for(auto& i : it->second->adj) ret.push_back(i.second->name); } return ret; } std::string Graph::bfs(const std::string& name) { std::string ret = ""; auto it = m_V.find(name); if(it != m_V.end()) { std::queue<vertex*> Queue; vertex* curr = it->second; Queue.push(curr); curr->visited = true; ret += curr->name + " "; while(!Queue.empty()) { for(auto& i : curr->adj) { if(i.second->visited == false) { Queue.push(i.second); i.second->visited = true; ret+= i.second->name + " "; } } Queue.pop(); if(!Queue.empty()) { curr = Queue.front(); } } //reset the visited var for(auto& i : m_V) i.second->visited = false; } return ret; } std::string Graph::dfs(const std::string& name, bool topo) { std::string ret = ""; auto it = m_V.find(name); if(it != m_V.end()) { std::stack<vertex*> Stack; vertex* curr = it->second; Stack.push(curr); curr->visited = true; if(!topo) ret += curr->name + " "; while(!Stack.empty()) { bool found = false; size_t i = 0; while(i < curr->adj.size() && !found) { if(curr->adj[i].second->visited == false) { found = true; curr = curr->adj[i].second; curr->visited = true; if(!topo) ret += curr->name + " "; Stack.push(curr); } i++; } if(!found) { Stack.pop(); if(topo) { ret += curr->name + " "; } if(!Stack.empty()) { curr = Stack.top(); } } } if(topo) { std::reverse(ret.begin(),ret.end()); ret.erase(ret.begin());//remove space at the beginning } else ret.erase(ret.end()-1);//remove space at the end for(auto& i : m_V) i.second->visited = false; } return ret; } /* There are 3 sets. White set is used for those vertexes that haven't been visited yet, grey is for those which we are currently visiting, and Black is used for those that we already visited. Using depth first search we go through one of the starting vertexes child, and move it to the grey set. If on this way we find a vertex that has a child in the grey set we found a cycle. If a vertex has no more children that haven't been visited yet, it is moved into the black set and if possible we go back to the parent. If no parent can be found(nullptr) we pick the first element in the white set.(if it has any.) If there is no cycle every vertex will be moved to the black set. */ std::string Graph::cycle(bool& found) { std::string ret = ""; std::set<vertex*> white; std::set<vertex*> grey; std::set<vertex*> black; std::map<vertex*,vertex*> parentMap; ///Init all vertexes into white for(auto& i : m_V) white.insert(i.second); vertex* curr = *white.begin(); vertex* prev = nullptr; grey.insert(curr); white.erase(curr); parentMap[curr] = prev; while(black.size() != m_V.size()) { found = false; size_t i = 0; while(i < curr->adj.size() && !found) { vertex* v = curr->adj[i].second; if(white.find(v) != white.end()) { prev = curr; curr = v; grey.insert(curr); white.erase(curr); parentMap[curr] = prev; found = true; i = 0; } else if(grey.find(v) != grey.end()) { found = true; ret += v->name + " " + curr->name + " "; while(curr != nullptr) { curr = parentMap.find(curr)->second; if(curr != nullptr) ret += curr->name + " "; } std::reverse(ret.begin(),ret.end()); ret.erase(ret.begin()); return ret; } else i++; } if(!found) { black.insert(curr); grey.erase(curr); prev = nullptr; curr = parentMap.find(curr)->second; if(curr == nullptr && !white.empty()) { curr = *white.begin(); grey.insert(curr); white.erase(curr); parentMap[curr] = prev; } } } return ret; } <commit_msg>Minor changes.<commit_after>#include "Graph.h" #include <algorithm> #include <queue> #include <stack> #include <set> vertex* Graph::at(const std::string& name)const { auto it = m_V.find(name); if(it != m_V.end()) { return it->second; } else throw; } std::vector<std::string> Graph::getkeys()const { std::vector<std::string> ret; ret.resize(size()); int ind = 0; for(auto& i : m_V) { ret[ind++] = i.first; } return ret; } void Graph::filladj(const std::vector<std::string>& names, const Graph& g) { for(size_t i = 0; i < m_V.size(); i++) { auto it = m_V.find(names[i]); vertex* tmp = g.at(names[i]); vertex* pIt = it->second; for(auto& j : tmp->adj) { //1.cost //2.vertex* in this graph pIt->adj.push_back(std::make_pair(j.first, m_V.find(j.second->name)->second)); } } } Graph::Graph(const Graph& g) { std::vector<std::string> names = g.getkeys(); for(size_t i = 0; i < g.size(); i++) addvertex(names[i]); filladj(names,g); } /* As long as there are vertexes change name,clean adjacency list. x After that create new vertexes. x Then fill adjacency lists. Clean remaining not needed vertexes x */ Graph& Graph::operator=(const Graph& g) { int n = m_V.size() - g.size(); ///if there are more vertexes than needed: n > 0 ///if it is just the right size: n = 0 ///if there are not enough vertexes: n < 0 std::vector<std::string> names = getkeys(); std::vector<std::string> namesTO = g.getkeys(); if(!(n<0)) { for(size_t i = 0; i < g.size(); i++) { auto it = m_V.find(names[i]); it->second->name = namesTO[i]; it->second->adj.clear(); } //Clean remaining not needed vertexes for(int i = g.size(); i < n; i++) removevertex(names[i]); } else { for(size_t i = 0; i < g.size(); i++) addvertex(namesTO[i]); } //Filling adjacency list filladj(namesTO,g); return *this; } Graph::~Graph() { if(!m_V.empty()) { for(auto& i : m_V) delete i.second; } } Graph::vmap::iterator Graph::addvertex(const std::string& name) { auto it=m_V.find(name); if(it==m_V.end()) { vertex *v; v = new vertex(name); m_V[name]=v; return it; } return m_V.end(); } void Graph::addedge(const std::string& from, const std::string& to, int cost) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { vertex *f = (fromIt->second); vertex *t = (toIt->second); std::pair<int,vertex*> edge = std::make_pair(cost,t); f->adj.push_back(edge); } } void Graph::removevertex(const std::string& name) { auto it = m_V.find(name); if(it != m_V.end()) { for(auto& i : m_V) { if(i.second != it->second) { vertex* v = i.second; for(auto& j : v->adj) { if(j.second->name == name) { v->adj.erase(std::find(v->adj.begin(),v->adj.end(), j)); } } } } delete it->second; m_V.erase(it); } } void Graph::removeedge(const std::string& from, const std::string& to) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { vertex* v = fromIt->second; size_t i = 0; while(i < v->adj.size() && !(v->adj[i].second->name == to)) i++; if(i < v->adj.size()) { v->adj.erase(v->adj.begin()+i); } } } bool Graph::adjacent(const std::string& from, const std::string& to) { auto fromIt = m_V.find(from); auto toIt = m_V.find(to); if(fromIt != m_V.end() && toIt != m_V.end()) { for(auto& i : fromIt->second->adj) { if(i.second->name == to) { return true; } } } return false; } std::vector<std::string> Graph::neighbours(const std::string& name) { auto it = m_V.find(name); std::vector<std::string> ret; if(it != m_V.end()) { for(auto& i : it->second->adj) ret.push_back(i.second->name); } return ret; } std::string Graph::bfs(const std::string& name) { std::string ret = ""; auto it = m_V.find(name); if(it != m_V.end()) { std::queue<vertex*> Queue; vertex* curr = it->second; Queue.push(curr); curr->visited = true; ret += curr->name + " "; while(!Queue.empty()) { for(auto& i : curr->adj) { if(i.second->visited == false) { Queue.push(i.second); i.second->visited = true; ret+= i.second->name + " "; } } Queue.pop(); if(!Queue.empty()) curr = Queue.front(); } //reset the visited var for(auto& i : m_V) i.second->visited = false; } return ret; } std::string Graph::dfs(const std::string& name, bool topo) { std::string ret = ""; auto it = m_V.find(name); if(it != m_V.end()) { std::stack<vertex*> Stack; vertex* curr = it->second; Stack.push(curr); curr->visited = true; if(!topo) ret += curr->name + " "; while(!Stack.empty()) { bool found = false; size_t i = 0; while(i < curr->adj.size() && !found) { if(curr->adj[i].second->visited == false) { found = true; curr = curr->adj[i].second; curr->visited = true; if(!topo) ret += curr->name + " "; Stack.push(curr); } i++; } if(!found) { Stack.pop(); if(topo) ret += curr->name + " "; if(!Stack.empty()) curr = Stack.top(); } } if(topo) { std::reverse(ret.begin(),ret.end()); ret.erase(ret.begin());//remove space at the beginning } else ret.erase(ret.end()-1);//remove space at the end for(auto& i : m_V) i.second->visited = false; } return ret; } /* There are 3 sets. White set is used for those vertexes that haven't been visited yet, grey is for those which we are currently visiting, and Black is used for those that we already visited. Using depth first search we go through one of the starting vertexes child, and move it to the grey set. If on this way we find a vertex that has a child in the grey set we found a cycle. If a vertex has no more children that haven't been visited yet, it is moved into the black set and if possible we go back to the parent. If no parent can be found(nullptr) we pick the first element in the white set.(if it has any.) If there is no cycle every vertex will be moved to the black set. */ std::string Graph::cycle(bool& found) { std::string ret = ""; std::set<vertex*> white; std::set<vertex*> grey; std::set<vertex*> black; std::map<vertex*,vertex*> parentMap; ///Init all vertexes into white for(auto& i : m_V) white.insert(i.second); vertex* curr = *white.begin(); vertex* prev = nullptr; grey.insert(curr); white.erase(curr); parentMap[curr] = prev; while(black.size() != m_V.size()) { found = false; size_t i = 0; while(i < curr->adj.size() && !found) { vertex* v = curr->adj[i].second; if(white.find(v) != white.end()) { prev = curr; curr = v; grey.insert(curr); white.erase(curr); parentMap[curr] = prev; found = true; i = 0; } else if(grey.find(v) != grey.end()) { found = true; ret += v->name + " " + curr->name + " "; while(curr != nullptr) { curr = parentMap.find(curr)->second; if(curr != nullptr) ret += curr->name + " "; } std::reverse(ret.begin(),ret.end()); ret.erase(ret.begin()); return ret; } else i++; } if(!found) { black.insert(curr); grey.erase(curr); prev = nullptr; curr = parentMap.find(curr)->second; if(curr == nullptr && !white.empty()) { curr = *white.begin(); grey.insert(curr); white.erase(curr); parentMap[curr] = prev; } } } return ret; } <|endoftext|>
<commit_before>/* * Graph.hpp * * Created on: Nov 4, 2014 * Author: Pimenta */ #ifndef GRAPH_HPP_ #define GRAPH_HPP_ #include <memory> #include <map> #include <functional> #include <cstdio> typedef int Size; typedef int Vertex; typedef int Weight; enum { INFINITE = 0x7fffffff }; class Edge { public: Vertex vertex; Weight weight; Edge(Vertex vertex = 0, Weight weight = INFINITE); bool operator<(const Edge& other) const; }; class Neighbourhood { public: class Iterator : public std::iterator<std::forward_iterator_tag, Edge> { private: std::shared_ptr<Iterator> it, itend; public: Iterator(Iterator* it, Iterator* itend); virtual ~Iterator(); virtual bool operator!=(const Iterator& other) const; virtual Edge operator*(); virtual Iterator& operator++(); }; Vertex vertex; Neighbourhood(Vertex vertex = 0); virtual ~Neighbourhood(); virtual Iterator begin() const = 0; virtual Iterator end() const = 0; virtual Edge operator[](Vertex v) const = 0; virtual Size degree() const = 0; virtual void edge(Vertex v, Weight w) = 0; }; class Graph { public: class Iterator : public std::iterator<std::forward_iterator_tag, Neighbourhood> { private: std::shared_ptr<Iterator> it; public: Iterator(Iterator* it); virtual ~Iterator(); virtual bool operator!=(const Iterator& other) const; virtual Neighbourhood& operator*(); virtual Iterator& operator++(); }; virtual ~Graph(); virtual Iterator begin() const = 0; virtual Iterator end() const = 0; virtual Neighbourhood& operator[](Vertex v) const = 0; virtual Size order() const = 0; virtual void order(Size new_order) = 0; }; class ArrayNeighbourhood : public Neighbourhood { public: class Iterator : public Neighbourhood::Iterator { private: Edge* ptr; public: Iterator(Edge* ptr); bool operator!=(const Neighbourhood::Iterator& other) const; Edge operator*(); Neighbourhood::Iterator& operator++(); }; private: Size size_; Edge* data; Size degree_; public: ArrayNeighbourhood(); ~ArrayNeighbourhood(); Neighbourhood::Iterator begin() const; Neighbourhood::Iterator end() const; Edge operator[](Vertex v) const; Size degree() const; void resize(Size new_size); void edge(Vertex v, Weight w); }; class MapNeighbourhood : public Neighbourhood { public: class Iterator : public Neighbourhood::Iterator { private: std::map<Vertex, Edge>::const_iterator mapit; public: Iterator(std::map<Vertex, Edge>::const_iterator mapit); bool operator!=(const Neighbourhood::Iterator& other) const; Edge operator*(); Neighbourhood::Iterator& operator++(); }; private: std::map<Vertex, Edge> data; public: Neighbourhood::Iterator begin() const; Neighbourhood::Iterator end() const; Edge operator[](Vertex v) const; Size degree() const; void edge(Vertex v, Weight w); }; template <class NeighbourhoodType> class ArrayGraph : public Graph { public: class Iterator : public Graph::Iterator { private: NeighbourhoodType* ptr; public: Iterator(NeighbourhoodType* ptr) : Graph::Iterator(nullptr), ptr(ptr) { } bool operator!=(const Graph::Iterator& other) const { return ptr != ((Iterator&)other).ptr; } Neighbourhood& operator*() { return *ptr; } Graph::Iterator& operator++() { ptr++; return *this; } }; private: Size order_; NeighbourhoodType* data; public: ArrayGraph() : order_(0), data(new NeighbourhoodType[0]) { } ~ArrayGraph() { delete[] data; } Graph::Iterator begin() const { return Graph::Iterator(new Iterator(data)); } Graph::Iterator end() const { return Graph::Iterator(new Iterator(data + order_)); } Neighbourhood& operator[](Vertex v) const { return data[v - 1]; } Size order() const { return order_; } void order(Size new_order) { order_ = new_order; delete[] data; data = new NeighbourhoodType[order_]; for (Size i = 0; i < order_; i++) { data[i].vertex = i + 1; } } }; template <> inline void ArrayGraph<ArrayNeighbourhood>::order(Size new_order) { order_ = new_order; delete[] data; data = new ArrayNeighbourhood[order_]; for (Size i = 0; i < order_; i++) { data[i].vertex = i + 1; data[i].resize(order_); } } template <class NeighbourhoodType> class MapGraph : public Graph { public: class Iterator : public Graph::Iterator { private: typename std::map<Vertex, NeighbourhoodType>::const_iterator mapit; public: Iterator(typename std::map<Vertex, NeighbourhoodType>::const_iterator mapit) : Graph::Iterator(nullptr), mapit(mapit) { } bool operator!=(const Graph::Iterator& other) const { return mapit != ((Iterator&)other).mapit; } Neighbourhood& operator*() { return (Neighbourhood&)mapit->second; } Graph::Iterator& operator++() { mapit++; return *this; } }; private: std::map<Vertex, NeighbourhoodType> data; public: Graph::Iterator begin() const { return Graph::Iterator(new Iterator(data.begin())); } Graph::Iterator end() const { return Graph::Iterator(new Iterator(data.end())); } Neighbourhood& operator[](Vertex v) const { return (Neighbourhood&)data.at(v); } Size order() const { return data.size(); } void order(Size new_order) { data.clear(); for (Vertex u = 1; u <= new_order; u++) { data[u].vertex = u; } } }; template <> inline void MapGraph<ArrayNeighbourhood>::order(Size new_order) { data.clear(); for (Vertex u = 1; u <= new_order; u++) { data[u].vertex = u; data[u].resize(new_order); } } template <int maxN> class AllPairsShortestPaths { private: struct Data { Weight data[maxN][maxN]; }; int N; Data* res; public: AllPairsShortestPaths( const Graph& G, std::function<void(const Graph&, Vertex, Weight*)> spfunc ) : N(G.order()), res(new Data) { Weight* shortest_path_tree = new Weight[G.order() + 1]; for (auto& u : G) { spfunc(G, u.vertex, shortest_path_tree); for (auto& v : G) { res->data[u.vertex][v.vertex] = shortest_path_tree[v.vertex]; } } delete[] shortest_path_tree; } ~AllPairsShortestPaths() { delete res; } bool operator==(const AllPairsShortestPaths& other) { if (N != other.N) { return false; } for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { if (res->data[source][target] != other.res->data[source][target]) { return false; } } } return true; } bool operator!=(const AllPairsShortestPaths& other) { if (N != other.N) { return true; } for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { if (res->data[source][target] != other.res->data[source][target]) { return true; } } } return false; } void print(FILE* fp, const char* funcname) { fprintf(fp, "%s:\n", funcname); for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { Weight w = res->data[source][target]; if (w == INFINITE) { fprintf(fp, " inf "); } else { fprintf(fp, "%5d ", w); } } fprintf(fp, "\n"); } } }; void scanUndirectedGraph(Graph& G, FILE* fp); void scanDirectedGraph(Graph& G, FILE* fp); void printDirectedGraph(const Graph& G, FILE* fp); /** * Generates loop-free weighted undirected graphs without multiple edges, using * a uniform distribution. * G: container * N: number of vertices * maxWeight: will generate weights in [1, maxWeight] */ void generateGraph(Graph& G, int N, Weight maxWeight); #endif /* GRAPH_HPP_ */ <commit_msg>Breaking line<commit_after>/* * Graph.hpp * * Created on: Nov 4, 2014 * Author: Pimenta */ #ifndef GRAPH_HPP_ #define GRAPH_HPP_ #include <memory> #include <map> #include <functional> #include <cstdio> typedef int Size; typedef int Vertex; typedef int Weight; enum { INFINITE = 0x7fffffff }; class Edge { public: Vertex vertex; Weight weight; Edge(Vertex vertex = 0, Weight weight = INFINITE); bool operator<(const Edge& other) const; }; class Neighbourhood { public: class Iterator : public std::iterator<std::forward_iterator_tag, Edge> { private: std::shared_ptr<Iterator> it, itend; public: Iterator(Iterator* it, Iterator* itend); virtual ~Iterator(); virtual bool operator!=(const Iterator& other) const; virtual Edge operator*(); virtual Iterator& operator++(); }; Vertex vertex; Neighbourhood(Vertex vertex = 0); virtual ~Neighbourhood(); virtual Iterator begin() const = 0; virtual Iterator end() const = 0; virtual Edge operator[](Vertex v) const = 0; virtual Size degree() const = 0; virtual void edge(Vertex v, Weight w) = 0; }; class Graph { public: class Iterator : public std::iterator<std::forward_iterator_tag, Neighbourhood> { private: std::shared_ptr<Iterator> it; public: Iterator(Iterator* it); virtual ~Iterator(); virtual bool operator!=(const Iterator& other) const; virtual Neighbourhood& operator*(); virtual Iterator& operator++(); }; virtual ~Graph(); virtual Iterator begin() const = 0; virtual Iterator end() const = 0; virtual Neighbourhood& operator[](Vertex v) const = 0; virtual Size order() const = 0; virtual void order(Size new_order) = 0; }; class ArrayNeighbourhood : public Neighbourhood { public: class Iterator : public Neighbourhood::Iterator { private: Edge* ptr; public: Iterator(Edge* ptr); bool operator!=(const Neighbourhood::Iterator& other) const; Edge operator*(); Neighbourhood::Iterator& operator++(); }; private: Size size_; Edge* data; Size degree_; public: ArrayNeighbourhood(); ~ArrayNeighbourhood(); Neighbourhood::Iterator begin() const; Neighbourhood::Iterator end() const; Edge operator[](Vertex v) const; Size degree() const; void resize(Size new_size); void edge(Vertex v, Weight w); }; class MapNeighbourhood : public Neighbourhood { public: class Iterator : public Neighbourhood::Iterator { private: std::map<Vertex, Edge>::const_iterator mapit; public: Iterator(std::map<Vertex, Edge>::const_iterator mapit); bool operator!=(const Neighbourhood::Iterator& other) const; Edge operator*(); Neighbourhood::Iterator& operator++(); }; private: std::map<Vertex, Edge> data; public: Neighbourhood::Iterator begin() const; Neighbourhood::Iterator end() const; Edge operator[](Vertex v) const; Size degree() const; void edge(Vertex v, Weight w); }; template <class NeighbourhoodType> class ArrayGraph : public Graph { public: class Iterator : public Graph::Iterator { private: NeighbourhoodType* ptr; public: Iterator(NeighbourhoodType* ptr) : Graph::Iterator(nullptr), ptr(ptr) { } bool operator!=(const Graph::Iterator& other) const { return ptr != ((Iterator&)other).ptr; } Neighbourhood& operator*() { return *ptr; } Graph::Iterator& operator++() { ptr++; return *this; } }; private: Size order_; NeighbourhoodType* data; public: ArrayGraph() : order_(0), data(new NeighbourhoodType[0]) { } ~ArrayGraph() { delete[] data; } Graph::Iterator begin() const { return Graph::Iterator(new Iterator(data)); } Graph::Iterator end() const { return Graph::Iterator(new Iterator(data + order_)); } Neighbourhood& operator[](Vertex v) const { return data[v - 1]; } Size order() const { return order_; } void order(Size new_order) { order_ = new_order; delete[] data; data = new NeighbourhoodType[order_]; for (Size i = 0; i < order_; i++) { data[i].vertex = i + 1; } } }; template <> inline void ArrayGraph<ArrayNeighbourhood>::order(Size new_order) { order_ = new_order; delete[] data; data = new ArrayNeighbourhood[order_]; for (Size i = 0; i < order_; i++) { data[i].vertex = i + 1; data[i].resize(order_); } } template <class NeighbourhoodType> class MapGraph : public Graph { public: class Iterator : public Graph::Iterator { private: typename std::map<Vertex, NeighbourhoodType>::const_iterator mapit; public: Iterator( typename std::map<Vertex, NeighbourhoodType>::const_iterator mapit ) : Graph::Iterator(nullptr), mapit(mapit) { } bool operator!=(const Graph::Iterator& other) const { return mapit != ((Iterator&)other).mapit; } Neighbourhood& operator*() { return (Neighbourhood&)mapit->second; } Graph::Iterator& operator++() { mapit++; return *this; } }; private: std::map<Vertex, NeighbourhoodType> data; public: Graph::Iterator begin() const { return Graph::Iterator(new Iterator(data.begin())); } Graph::Iterator end() const { return Graph::Iterator(new Iterator(data.end())); } Neighbourhood& operator[](Vertex v) const { return (Neighbourhood&)data.at(v); } Size order() const { return data.size(); } void order(Size new_order) { data.clear(); for (Vertex u = 1; u <= new_order; u++) { data[u].vertex = u; } } }; template <> inline void MapGraph<ArrayNeighbourhood>::order(Size new_order) { data.clear(); for (Vertex u = 1; u <= new_order; u++) { data[u].vertex = u; data[u].resize(new_order); } } template <int maxN> class AllPairsShortestPaths { private: struct Data { Weight data[maxN][maxN]; }; int N; Data* res; public: AllPairsShortestPaths( const Graph& G, std::function<void(const Graph&, Vertex, Weight*)> spfunc ) : N(G.order()), res(new Data) { Weight* shortest_path_tree = new Weight[G.order() + 1]; for (auto& u : G) { spfunc(G, u.vertex, shortest_path_tree); for (auto& v : G) { res->data[u.vertex][v.vertex] = shortest_path_tree[v.vertex]; } } delete[] shortest_path_tree; } ~AllPairsShortestPaths() { delete res; } bool operator==(const AllPairsShortestPaths& other) { if (N != other.N) { return false; } for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { if (res->data[source][target] != other.res->data[source][target]) { return false; } } } return true; } bool operator!=(const AllPairsShortestPaths& other) { if (N != other.N) { return true; } for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { if (res->data[source][target] != other.res->data[source][target]) { return true; } } } return false; } void print(FILE* fp, const char* funcname) { fprintf(fp, "%s:\n", funcname); for (Vertex source = 1; source <= N; source++) { for (Vertex target = 1; target <= N; target++) { Weight w = res->data[source][target]; if (w == INFINITE) { fprintf(fp, " inf "); } else { fprintf(fp, "%5d ", w); } } fprintf(fp, "\n"); } } }; void scanUndirectedGraph(Graph& G, FILE* fp); void scanDirectedGraph(Graph& G, FILE* fp); void printDirectedGraph(const Graph& G, FILE* fp); /** * Generates loop-free weighted undirected graphs without multiple edges, using * a uniform distribution. * G: container * N: number of vertices * maxWeight: will generate weights in [1, maxWeight] */ void generateGraph(Graph& G, int N, Weight maxWeight); #endif /* GRAPH_HPP_ */ <|endoftext|>
<commit_before>#include "Layer.h" // Generate random float for initial weight float Layer::randomFloat() { int randInt = rand() % (INITIALWEIGHTRANGE * 1000) - (INITIALWEIGHTRANGE * 500); float randFl = (float) randInt / 1000; return randFl; } // Public constructor Layer::Layer(int numNodes, int numPrevNodes, std::vector<float> weights) { setNumNodes(numNodes); setNumPrevNodes(numPrevNodes); // Initialize nodes for (int n = 0; n < numNodes; n++) { Node newNode = Node(0); nodes.push_back(newNode); } // Skip adding links to input layer if (numPrevNodes > 0) { int w = 0; // Initialize links for (int n = 0; n < numNodes; n++) { std::vector<Link> newVector; links.push_back(newVector); // Push back numPrevNodes + 1 to incorperate bias node for (int pn = 0; pn < numPrevNodes + 1; pn++) { if (weights.empty() == true) { Link newLink = Link(randomFloat()); links[n].push_back(newLink); } else { Link newLink = Link(weights[w]); links[n].push_back(newLink); w++; } } } } } // Calculate the weighted input for node in layer float Layer::calculateWeightedInput(std::vector<Link> inputLinks) { float sum = 0.0; for (int pn = 0; pn < getNumPrevNodes(); pn++) { sum = sum + getInputs()[pn] * inputLinks[pn].getWeight(); } sum = sum + BIASINPUT * inputLinks[getNumPrevNodes()].getWeight(); return sum; } // Feed inputs through Network std::vector<float> Layer::feedForward(std::vector<float> in) { // Update inputs vector instance variable setInputs(in); std::vector<float> outputs; // Outputs are equivilent to inputs in the first layer if (getNumPrevNodes() == 0) { outputs = getInputs(); } else { // Set new values and obtain output for the input to the next layer for (int n = 0; n < getNumNodes(); n++) { nodes[n].setValue(calculateWeightedInput(links[n])); outputs.push_back(nodes[n].getOutput()); } } return outputs; } // Calculate and update delta values for each node from next layer deltinis void Layer::updateDeltas(std::vector<float> deltinis) { for (int n = 0; n < getNumNodes(); n++) { nodes[n].setDelta(deltinis[n] * nodes[n].getOutput() * (1 - nodes[n].getOutput())); } } // Calculate and update weight values for each link void Layer::updateWeights() { for (int n = 0; n < getNumNodes(); n++) { for (int pn = 0; pn < getNumPrevNodes(); pn++) { links[n][pn].updateWeight(nodes[n].getDelta(), getInputs()[pn]); } links[n][getNumPrevNodes()].updateWeight(nodes[n].getDelta(), BIASINPUT); } } // Calculate the deltini for each node in the previous layer std::vector<float> Layer::calculateDeltinis() { std::vector<float> deltinis; for (int pn = 0; pn < getNumPrevNodes() + 1; pn++) { float deltini = 0.0; for (int n = 0; n < getNumNodes(); n++) { deltini = deltini + links[n][pn].getWeight() * nodes[n].getDelta(); } deltinis.push_back(deltini); } return deltinis; } // Back propegation algorithm to update weights std::vector<float> Layer::backPropegation(std::vector<float> deltinis) { // Calculate and update delta values for each node from next layer deltinis updateDeltas(deltinis); // Calculate deltinis for use in previous layer's delta calculations deltinis = calculateDeltinis(); // Update weights after calculating deltinis to preserve original weights // in deltini calculation updateWeights(); return deltinis; } // Print node values in the layer void Layer::printNodes() { std::cout << "===========================\n"; for (std::vector<Node>::iterator it = nodes.begin() ; it != nodes.end(); ++it) { std::cout << " Node: " << it - nodes.begin() << " = " << it->getValue() << std::endl; } } // Print link weights in the layer void Layer::printLinks() { std::cout << "===========================\n"; for (int n = 0; n < getNumNodes(); n++) { for (int pn = 0; pn < getNumPrevNodes() + 1; pn++) { std::cout << " Link: " << pn << "->" << n << " = " << links[n][pn].getWeight() << std::endl; } } } <commit_msg>fixing spacing<commit_after>#include "Layer.h" // Generate random float for initial weight float Layer::randomFloat() { int randInt = rand() % (INITIALWEIGHTRANGE * 1000) - (INITIALWEIGHTRANGE * 500); float randFl = (float) randInt / 1000; return randFl; } // Public constructor Layer::Layer(int numNodes, int numPrevNodes, std::vector<float> weights) { setNumNodes(numNodes); setNumPrevNodes(numPrevNodes); // Initialize nodes for (int n = 0; n < numNodes; n++) { Node newNode = Node(0); nodes.push_back(newNode); } // Skip adding links to input layer if (numPrevNodes > 0) { int w = 0; // Initialize links for (int n = 0; n < numNodes; n++) { std::vector<Link> newVector; links.push_back(newVector); // Push back numPrevNodes + 1 to incorperate bias node for (int pn = 0; pn < numPrevNodes + 1; pn++) { if (weights.empty() == true) { Link newLink = Link(randomFloat()); links[n].push_back(newLink); } else { Link newLink = Link(weights[w]); links[n].push_back(newLink); w++; } } } } } // Calculate the weighted input for node in layer float Layer::calculateWeightedInput(std::vector<Link> inputLinks) { float sum = 0.0; for (int pn = 0; pn < getNumPrevNodes(); pn++) { sum = sum + getInputs()[pn] * inputLinks[pn].getWeight(); } sum = sum + BIASINPUT * inputLinks[getNumPrevNodes()].getWeight(); return sum; } // Feed inputs through Network std::vector<float> Layer::feedForward(std::vector<float> in) { // Update inputs vector instance variable setInputs(in); std::vector<float> outputs; // Outputs are equivilent to inputs in the first layer if (getNumPrevNodes() == 0) { outputs = getInputs(); } else { // Set new values and obtain output for the input to the next layer for (int n = 0; n < getNumNodes(); n++) { nodes[n].setValue(calculateWeightedInput(links[n])); outputs.push_back(nodes[n].getOutput()); } } return outputs; } // Calculate and update delta values for each node from next layer deltinis void Layer::updateDeltas(std::vector<float> deltinis) { for (int n = 0; n < getNumNodes(); n++) { nodes[n].setDelta(deltinis[n] * nodes[n].getOutput() * (1 - nodes[n].getOutput())); } } // Calculate and update weight values for each link void Layer::updateWeights() { for (int n = 0; n < getNumNodes(); n++) { for (int pn = 0; pn < getNumPrevNodes(); pn++) { links[n][pn].updateWeight(nodes[n].getDelta(), getInputs()[pn]); } links[n][getNumPrevNodes()].updateWeight(nodes[n].getDelta(), BIASINPUT); } } // Calculate the deltini for each node in the previous layer std::vector<float> Layer::calculateDeltinis() { std::vector<float> deltinis; for (int pn = 0; pn < getNumPrevNodes() + 1; pn++) { float deltini = 0.0; for (int n = 0; n < getNumNodes(); n++) { deltini = deltini + links[n][pn].getWeight() * nodes[n].getDelta(); } deltinis.push_back(deltini); } return deltinis; } // Back propegation algorithm to update weights std::vector<float> Layer::backPropegation(std::vector<float> deltinis) { // Calculate and update delta values for each node from next layer deltinis updateDeltas(deltinis); // Calculate deltinis for use in previous layer's delta calculations deltinis = calculateDeltinis(); // Update weights after calculating deltinis to preserve original weights // in deltini calculation updateWeights(); return deltinis; } // Print node values in the layer void Layer::printNodes() { std::cout << "===========================\n"; for (std::vector<Node>::iterator it = nodes.begin() ; it != nodes.end(); ++it) { std::cout << " Node: " << it - nodes.begin() << " = " << it->getValue() << std::endl; } } // Print link weights in the layer void Layer::printLinks() { std::cout << "===========================\n"; for (int n = 0; n < getNumNodes(); n++) { for (int pn = 0; pn < getNumPrevNodes() + 1; pn++) { std::cout << " Link: " << pn << "->" << n << " = " << links[n][pn].getWeight() << std::endl; } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "Lexer.hpp" using std::pair; using std::string; using std::ios_base; using namespace eddic; void Lexer::lex(string file) { scanner.scan(file); currentType = NOTHING; } void Lexer::close() { scanner.close(); } bool Lexer::next() { if(!buffer.empty()) { pair<string, TokenType> old = buffer.top(); currentToken = old.first; currentType = old.second; buffer.pop(); return true; } else if(readNext()) { read.push(make_pair(currentToken, currentType)); return true; } return false; } void Lexer::pushBack() { pair<string, TokenType> old = read.top(); buffer.push(old); read.pop(); } bool Lexer::readNext() { if(!scanner.next()) { return false; } while(scanner.isSpace()) { if(!scanner.next()){ return false; } } if(scanner.current() == '"') { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.current() != '"') { currentToken += scanner.current(); } currentToken += scanner.current(); currentType = LITTERAL; return true; } else if(scanner.isAlpha()) { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.isAlpha()) { currentToken += scanner.current(); } scanner.pushBack(); if(currentToken == "true") { currentType = TRUE; } else if(currentToken == "false") { currentType = FALSE; } else if(currentToken == "if") { currentType = IF; } else if(currentToken == "else") { currentType = ELSE; } else { currentType = WORD; } return true; } else if(scanner.isDigit()) { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.isDigit()) { currentToken += scanner.current(); } scanner.pushBack(); currentType = INTEGER; return true; } switch (scanner.current()) { case ';': currentType = STOP; currentToken = ";"; return true; case '=': scanner.next(); if(scanner.current() == '=') { currentType = EQUALS_TOKEN; } else { scanner.pushBack(); currentType = ASSIGN; } return true; case '(': currentType = LEFT_PARENTH; return true; case ')': currentType = RIGHT_PARENTH; return true; case '{': currentType = LEFT_BRACE; return true; case '}': currentType = RIGHT_BRACE; return true; case '+': currentType = ADDITION; return true; case '-': currentType = SUBTRACTION; return true; case '*': currentType = MULTIPLICATION; return true; case '/': currentType = DIVISION; return true; case '%': currentType = MODULO; return true; case '!': scanner.next(); if(scanner.current() == '=') { currentType = NOT_EQUALS_TOKEN; } return false; case '<': scanner.next(); if(scanner.current() == '=') { scanner.next(); if(scanner.current() == '>'){ currentType = SWAP; } else { scanner.pushBack(); currentType = LESS_EQUALS_TOKEN; } } else { scanner.pushBack(); currentType = LESS_TOKEN; } return true; case '>': scanner.next(); if(scanner.current() == '=') { currentType = GREATER_EQUALS_TOKEN; } else { scanner.pushBack(); currentType = GREATER_TOKEN; } return true; } return false; } string Lexer::getCurrentToken() const { return currentToken; } bool Lexer::isWord() const { return currentType == WORD; } bool Lexer::isLitteral() const { return currentType == LITTERAL; } bool Lexer::isAssign() const { return currentType == ASSIGN; } bool Lexer::isSwap() const { return currentType == SWAP; } bool Lexer::isLeftParenth() const { return currentType == LEFT_PARENTH; } bool Lexer::isRightParenth() const { return currentType == RIGHT_PARENTH; } bool Lexer::isLeftBrace() const { return currentType == LEFT_BRACE; } bool Lexer::isRightBrace() const { return currentType == RIGHT_BRACE; } bool Lexer::isStop() const { return currentType == STOP; } bool Lexer::isInteger() const { return currentType == INTEGER; } bool Lexer::isAddition() const { return currentType == ADDITION; } bool Lexer::isSubtraction() const { return currentType == SUBTRACTION; } bool Lexer::isMultiplication() const { return currentType == MULTIPLICATION; } bool Lexer::isModulo() const { return currentType == MODULO; } bool Lexer::isDivision() const { return currentType == DIVISION; } bool Lexer::isEquals() const { return currentType == EQUALS_TOKEN; } bool Lexer::isNotEquals() const { return currentType == NOT_EQUALS_TOKEN; } bool Lexer::isGreater() const { return currentType == GREATER_TOKEN; } bool Lexer::isLess() const { return currentType == LESS_TOKEN; } bool Lexer::isGreaterOrEquals() const { return currentType == GREATER_EQUALS_TOKEN; } bool Lexer::isLessOrEquals() const { return currentType == LESS_EQUALS_TOKEN; } bool Lexer::isIf() const { return currentType == IF; } bool Lexer::isElse() const { return currentType == ELSE; } bool Lexer::isBooleanOperator() const { return currentType >= EQUALS_TOKEN && currentType <= LESS_EQUALS_TOKEN; } bool Lexer::isBoolean() const { return currentType == TRUE || currentType == FALSE; } bool Lexer::isTrue() const { return currentType == TRUE; } bool Lexer::isFalse() const { return currentType == FALSE; } <commit_msg>Remove a useless assignement<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "Lexer.hpp" using std::pair; using std::string; using std::ios_base; using namespace eddic; void Lexer::lex(string file) { scanner.scan(file); currentType = NOTHING; } void Lexer::close() { scanner.close(); } bool Lexer::next() { if(!buffer.empty()) { pair<string, TokenType> old = buffer.top(); currentToken = old.first; currentType = old.second; buffer.pop(); return true; } else if(readNext()) { read.push(make_pair(currentToken, currentType)); return true; } return false; } void Lexer::pushBack() { pair<string, TokenType> old = read.top(); buffer.push(old); read.pop(); } bool Lexer::readNext() { if(!scanner.next()) { return false; } while(scanner.isSpace()) { if(!scanner.next()){ return false; } } if(scanner.current() == '"') { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.current() != '"') { currentToken += scanner.current(); } currentToken += scanner.current(); currentType = LITTERAL; return true; } else if(scanner.isAlpha()) { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.isAlpha()) { currentToken += scanner.current(); } scanner.pushBack(); if(currentToken == "true") { currentType = TRUE; } else if(currentToken == "false") { currentType = FALSE; } else if(currentToken == "if") { currentType = IF; } else if(currentToken == "else") { currentType = ELSE; } else { currentType = WORD; } return true; } else if(scanner.isDigit()) { currentToken = string(1, scanner.current()); while(scanner.next() && scanner.isDigit()) { currentToken += scanner.current(); } scanner.pushBack(); currentType = INTEGER; return true; } switch (scanner.current()) { case ';': currentType = STOP; return true; case '=': scanner.next(); if(scanner.current() == '=') { currentType = EQUALS_TOKEN; } else { scanner.pushBack(); currentType = ASSIGN; } return true; case '(': currentType = LEFT_PARENTH; return true; case ')': currentType = RIGHT_PARENTH; return true; case '{': currentType = LEFT_BRACE; return true; case '}': currentType = RIGHT_BRACE; return true; case '+': currentType = ADDITION; return true; case '-': currentType = SUBTRACTION; return true; case '*': currentType = MULTIPLICATION; return true; case '/': currentType = DIVISION; return true; case '%': currentType = MODULO; return true; case '!': scanner.next(); if(scanner.current() == '=') { currentType = NOT_EQUALS_TOKEN; } return false; case '<': scanner.next(); if(scanner.current() == '=') { scanner.next(); if(scanner.current() == '>'){ currentType = SWAP; } else { scanner.pushBack(); currentType = LESS_EQUALS_TOKEN; } } else { scanner.pushBack(); currentType = LESS_TOKEN; } return true; case '>': scanner.next(); if(scanner.current() == '=') { currentType = GREATER_EQUALS_TOKEN; } else { scanner.pushBack(); currentType = GREATER_TOKEN; } return true; } return false; } string Lexer::getCurrentToken() const { return currentToken; } bool Lexer::isWord() const { return currentType == WORD; } bool Lexer::isLitteral() const { return currentType == LITTERAL; } bool Lexer::isAssign() const { return currentType == ASSIGN; } bool Lexer::isSwap() const { return currentType == SWAP; } bool Lexer::isLeftParenth() const { return currentType == LEFT_PARENTH; } bool Lexer::isRightParenth() const { return currentType == RIGHT_PARENTH; } bool Lexer::isLeftBrace() const { return currentType == LEFT_BRACE; } bool Lexer::isRightBrace() const { return currentType == RIGHT_BRACE; } bool Lexer::isStop() const { return currentType == STOP; } bool Lexer::isInteger() const { return currentType == INTEGER; } bool Lexer::isAddition() const { return currentType == ADDITION; } bool Lexer::isSubtraction() const { return currentType == SUBTRACTION; } bool Lexer::isMultiplication() const { return currentType == MULTIPLICATION; } bool Lexer::isModulo() const { return currentType == MODULO; } bool Lexer::isDivision() const { return currentType == DIVISION; } bool Lexer::isEquals() const { return currentType == EQUALS_TOKEN; } bool Lexer::isNotEquals() const { return currentType == NOT_EQUALS_TOKEN; } bool Lexer::isGreater() const { return currentType == GREATER_TOKEN; } bool Lexer::isLess() const { return currentType == LESS_TOKEN; } bool Lexer::isGreaterOrEquals() const { return currentType == GREATER_EQUALS_TOKEN; } bool Lexer::isLessOrEquals() const { return currentType == LESS_EQUALS_TOKEN; } bool Lexer::isIf() const { return currentType == IF; } bool Lexer::isElse() const { return currentType == ELSE; } bool Lexer::isBooleanOperator() const { return currentType >= EQUALS_TOKEN && currentType <= LESS_EQUALS_TOKEN; } bool Lexer::isBoolean() const { return currentType == TRUE || currentType == FALSE; } bool Lexer::isTrue() const { return currentType == TRUE; } bool Lexer::isFalse() const { return currentType == FALSE; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MSRIOImp.hpp" #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sstream> #include <map> #include "geopm_sched.h" #include "Exception.hpp" #include "Helper.hpp" #include "config.h" #define GEOPM_IOC_MSR_BATCH _IOWR('c', 0xA2, struct geopm::MSRIOImp::m_msr_batch_array_s) namespace geopm { std::unique_ptr<MSRIO> MSRIO::make_unique(void) { return geopm::make_unique<MSRIOImp>(); } std::shared_ptr<MSRIO> MSRIO::make_shared(void) { return std::make_shared<MSRIOImp>(); } MSRIOImp::MSRIOImp() : MSRIOImp(geopm_sched_num_cpu()) { } MSRIOImp::MSRIOImp(int num_cpu) : m_num_cpu(num_cpu) , m_file_desc(m_num_cpu + 1, -1) // Last file descriptor is for the batch file , m_is_batch_enabled(true) , m_read_batch({0, NULL}) , m_write_batch({0, NULL}) , m_read_batch_op(0) , m_write_batch_op(0) { } MSRIOImp::~MSRIOImp() { for (int cpu_idx = 0; cpu_idx < m_num_cpu; ++cpu_idx) { close_msr(cpu_idx); } close_msr_batch(); } uint64_t MSRIOImp::read_msr(int cpu_idx, uint64_t offset) { uint64_t result = 0; size_t num_read = pread(msr_desc(cpu_idx), &result, sizeof(result), offset); if (num_read != sizeof(result)) { std::ostringstream err_str; err_str << "MSRIOImp::read_msr(): pread() failed at offset 0x" << std::hex << offset << " system error: " << strerror(errno); throw Exception(err_str.str(), GEOPM_ERROR_MSR_WRITE, __FILE__, __LINE__); } return result; } void MSRIOImp::write_msr(int cpu_idx, uint64_t offset, uint64_t raw_value, uint64_t write_mask) { if ((raw_value & write_mask) != raw_value) { std::ostringstream err_str; err_str << "MSRIOImp::write_msr(): raw_value does not obey write_mask, " << "raw_value=0x" << std::hex << raw_value << " write_mask=0x" << write_mask; throw Exception(err_str.str(), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } uint64_t write_value = read_msr(cpu_idx, offset); write_value &= ~write_mask; write_value |= raw_value; size_t num_write = pwrite(msr_desc(cpu_idx), &write_value, sizeof(write_value), offset); if (num_write != sizeof(write_value)) { std::ostringstream err_str; err_str << "MSRIOImp::write_msr(): pwrite() failed at offset 0x" << std::hex << offset << " system error: " << strerror(errno); throw Exception(err_str.str(), GEOPM_ERROR_MSR_WRITE, __FILE__, __LINE__); } } void MSRIOImp::config_batch(const std::vector<int> &read_cpu_idx, const std::vector<uint64_t> &read_offset, const std::vector<int> &write_cpu_idx, const std::vector<uint64_t> &write_offset, const std::vector<uint64_t> &write_mask) { if (read_cpu_idx.size() != read_offset.size() || write_cpu_idx.size() != write_offset.size() || write_offset.size() != write_mask.size()) { throw Exception("MSRIOImp::config_batch(): Input vector length mismatch", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } m_read_batch_op.resize(read_cpu_idx.size()); { auto cpu_it = read_cpu_idx.begin(); auto offset_it = read_offset.begin(); for (auto batch_it = m_read_batch_op.begin(); batch_it != m_read_batch_op.end(); ++batch_it, ++cpu_it, ++offset_it) { batch_it->cpu = *cpu_it; batch_it->isrdmsr = 1; batch_it->err = 0; batch_it->msr = *offset_it; batch_it->msrdata = 0; batch_it->wmask = 0; } } m_read_batch.numops = m_read_batch_op.size(); m_read_batch.ops = m_read_batch_op.data(); m_write_batch_op.resize(write_cpu_idx.size()); { auto cpu_it = write_cpu_idx.begin(); auto offset_it = write_offset.begin(); auto mask_it = write_mask.begin(); for (auto batch_it = m_write_batch_op.begin(); batch_it != m_write_batch_op.end(); ++batch_it, ++cpu_it, ++offset_it, ++mask_it) { batch_it->cpu = *cpu_it; batch_it->isrdmsr = 0; batch_it->err = 0; batch_it->msr = *offset_it; batch_it->msrdata = 0; batch_it->wmask = *mask_it; } } m_write_batch.numops = m_write_batch_op.size(); m_write_batch.ops = m_write_batch_op.data(); } void MSRIOImp::msr_ioctl(bool is_read) { struct m_msr_batch_array_s *batch_ptr = is_read ? &m_read_batch : &m_write_batch; int err = ioctl(msr_batch_desc(), GEOPM_IOC_MSR_BATCH, batch_ptr); if (err) { throw Exception("MSRIOImp::msr_ioctl(): call to ioctl() for /dev/cpu/msr_batch failed: " + std::string(" system error: ") + strerror(errno), GEOPM_ERROR_MSR_READ, __FILE__, __LINE__); } for (uint32_t batch_idx = 0; batch_idx != m_write_batch.numops; ++batch_idx) { if (m_write_batch.ops[batch_idx].err) { std::ostringstream err_str; err_str << "MSRIOImp::msr_ioctl(): operation failed at offset 0x" << std::hex << m_write_batch.ops[batch_idx].msr << " system error: " << strerror(m_write_batch.ops[batch_idx].err); throw Exception(err_str.str(), GEOPM_ERROR_MSR_WRITE, __FILE__, __LINE__); } } } void MSRIOImp::read_batch(std::vector<uint64_t> &raw_value) { if (raw_value.size() < m_read_batch.numops) { raw_value.resize(m_read_batch.numops); } open_msr_batch(); if (m_is_batch_enabled) { msr_ioctl(true); uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_read_batch.numops; ++raw_it, ++batch_idx) { *raw_it = m_read_batch.ops[batch_idx].msrdata; } } else { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_read_batch.numops; ++raw_it, ++batch_idx) { *raw_it = read_msr(m_read_batch_op[batch_idx].cpu, m_read_batch_op[batch_idx].msr); } } } void MSRIOImp::write_batch(const std::vector<uint64_t> &raw_value) { if (raw_value.size() < m_write_batch.numops) { throw Exception("MSRIOImp::write_batch(): input vector smaller than configured number of operations", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } open_msr_batch(); #ifdef GEOPM_ENABLE_MSRSAFE_IOCTL_WRITE if (m_is_batch_enabled) { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_write_batch.numops; ++raw_it, ++batch_idx) { m_write_batch.ops[batch_idx].msrdata = *raw_it; } msr_ioctl(false); } else #endif { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_write_batch.numops; ++raw_it, ++batch_idx) { write_msr(m_write_batch_op[batch_idx].cpu, m_write_batch_op[batch_idx].msr, *raw_it, m_write_batch_op[batch_idx].wmask); } } } int MSRIOImp::msr_desc(int cpu_idx) { if (cpu_idx < 0 || cpu_idx > m_num_cpu) { throw Exception("MSRIOImp::msr_desc(): cpu_idx=" + std::to_string(cpu_idx) + " out of range, num_cpu=" + std::to_string(m_num_cpu), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } open_msr(cpu_idx); return m_file_desc[cpu_idx]; } int MSRIOImp::msr_batch_desc() { return m_file_desc[m_num_cpu]; } void MSRIOImp::msr_path(int cpu_idx, bool is_fallback, std::string &path) { std::ostringstream msr_path; msr_path << "/dev/cpu/" << cpu_idx; if (!is_fallback) { msr_path << "/msr_safe"; } else { msr_path << "/msr"; } path = msr_path.str(); } void MSRIOImp::msr_batch_path(std::string &path) { path = "/dev/cpu/msr_batch"; } void MSRIOImp::open_msr(int cpu_idx) { if (m_file_desc[cpu_idx] == -1) { std::string path; msr_path(cpu_idx, false, path); m_file_desc[cpu_idx] = open(path.c_str(), O_RDWR); if (m_file_desc[cpu_idx] == -1) { errno = 0; msr_path(cpu_idx, true, path); m_file_desc[cpu_idx] = open(path.c_str(), O_RDWR); if (m_file_desc[cpu_idx] == -1) { throw Exception("MSRIOImp::open_msr(): Failed to open \"" + path + "\": " + "system error: " + strerror(errno), GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } } struct stat stat_buffer; int err = fstat(m_file_desc[cpu_idx], &stat_buffer); if (err) { throw Exception("MSRIOImp::open_msr(): file descriptor invalid", GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } void MSRIOImp::open_msr_batch(void) { if (m_is_batch_enabled && m_file_desc[m_num_cpu] == -1) { std::string path; msr_batch_path(path); m_file_desc[m_num_cpu] = open(path.c_str(), O_RDWR); if (m_file_desc[m_num_cpu] == -1) { m_is_batch_enabled = false; } } if (m_is_batch_enabled) { struct stat stat_buffer; int err = fstat(m_file_desc[m_num_cpu], &stat_buffer); if (err) { throw Exception("MSRIOImp::open_msr_batch(): file descriptor invalid", GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } } void MSRIOImp::close_msr(int cpu_idx) { if (m_file_desc[cpu_idx] != -1) { (void)close(m_file_desc[cpu_idx]); m_file_desc[cpu_idx] = -1; } } void MSRIOImp::close_msr_batch(void) { if (m_file_desc[m_num_cpu] != -1) { (void)close(m_file_desc[m_num_cpu]); m_file_desc[m_num_cpu] = -1; } } } <commit_msg>Fix error message when MSR read fails<commit_after>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MSRIOImp.hpp" #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sstream> #include <map> #include "geopm_sched.h" #include "Exception.hpp" #include "Helper.hpp" #include "config.h" #define GEOPM_IOC_MSR_BATCH _IOWR('c', 0xA2, struct geopm::MSRIOImp::m_msr_batch_array_s) namespace geopm { std::unique_ptr<MSRIO> MSRIO::make_unique(void) { return geopm::make_unique<MSRIOImp>(); } std::shared_ptr<MSRIO> MSRIO::make_shared(void) { return std::make_shared<MSRIOImp>(); } MSRIOImp::MSRIOImp() : MSRIOImp(geopm_sched_num_cpu()) { } MSRIOImp::MSRIOImp(int num_cpu) : m_num_cpu(num_cpu) , m_file_desc(m_num_cpu + 1, -1) // Last file descriptor is for the batch file , m_is_batch_enabled(true) , m_read_batch({0, NULL}) , m_write_batch({0, NULL}) , m_read_batch_op(0) , m_write_batch_op(0) { } MSRIOImp::~MSRIOImp() { for (int cpu_idx = 0; cpu_idx < m_num_cpu; ++cpu_idx) { close_msr(cpu_idx); } close_msr_batch(); } uint64_t MSRIOImp::read_msr(int cpu_idx, uint64_t offset) { uint64_t result = 0; size_t num_read = pread(msr_desc(cpu_idx), &result, sizeof(result), offset); if (num_read != sizeof(result)) { std::ostringstream err_str; err_str << "MSRIOImp::read_msr(): pread() failed at offset 0x" << std::hex << offset << " system error: " << strerror(errno); throw Exception(err_str.str(), GEOPM_ERROR_MSR_READ, __FILE__, __LINE__); } return result; } void MSRIOImp::write_msr(int cpu_idx, uint64_t offset, uint64_t raw_value, uint64_t write_mask) { if ((raw_value & write_mask) != raw_value) { std::ostringstream err_str; err_str << "MSRIOImp::write_msr(): raw_value does not obey write_mask, " << "raw_value=0x" << std::hex << raw_value << " write_mask=0x" << write_mask; throw Exception(err_str.str(), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } uint64_t write_value = read_msr(cpu_idx, offset); write_value &= ~write_mask; write_value |= raw_value; size_t num_write = pwrite(msr_desc(cpu_idx), &write_value, sizeof(write_value), offset); if (num_write != sizeof(write_value)) { std::ostringstream err_str; err_str << "MSRIOImp::write_msr(): pwrite() failed at offset 0x" << std::hex << offset << " system error: " << strerror(errno); throw Exception(err_str.str(), GEOPM_ERROR_MSR_WRITE, __FILE__, __LINE__); } } void MSRIOImp::config_batch(const std::vector<int> &read_cpu_idx, const std::vector<uint64_t> &read_offset, const std::vector<int> &write_cpu_idx, const std::vector<uint64_t> &write_offset, const std::vector<uint64_t> &write_mask) { if (read_cpu_idx.size() != read_offset.size() || write_cpu_idx.size() != write_offset.size() || write_offset.size() != write_mask.size()) { throw Exception("MSRIOImp::config_batch(): Input vector length mismatch", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } m_read_batch_op.resize(read_cpu_idx.size()); { auto cpu_it = read_cpu_idx.begin(); auto offset_it = read_offset.begin(); for (auto batch_it = m_read_batch_op.begin(); batch_it != m_read_batch_op.end(); ++batch_it, ++cpu_it, ++offset_it) { batch_it->cpu = *cpu_it; batch_it->isrdmsr = 1; batch_it->err = 0; batch_it->msr = *offset_it; batch_it->msrdata = 0; batch_it->wmask = 0; } } m_read_batch.numops = m_read_batch_op.size(); m_read_batch.ops = m_read_batch_op.data(); m_write_batch_op.resize(write_cpu_idx.size()); { auto cpu_it = write_cpu_idx.begin(); auto offset_it = write_offset.begin(); auto mask_it = write_mask.begin(); for (auto batch_it = m_write_batch_op.begin(); batch_it != m_write_batch_op.end(); ++batch_it, ++cpu_it, ++offset_it, ++mask_it) { batch_it->cpu = *cpu_it; batch_it->isrdmsr = 0; batch_it->err = 0; batch_it->msr = *offset_it; batch_it->msrdata = 0; batch_it->wmask = *mask_it; } } m_write_batch.numops = m_write_batch_op.size(); m_write_batch.ops = m_write_batch_op.data(); } void MSRIOImp::msr_ioctl(bool is_read) { struct m_msr_batch_array_s *batch_ptr = is_read ? &m_read_batch : &m_write_batch; int err = ioctl(msr_batch_desc(), GEOPM_IOC_MSR_BATCH, batch_ptr); if (err) { throw Exception("MSRIOImp::msr_ioctl(): call to ioctl() for /dev/cpu/msr_batch failed: " + std::string(" system error: ") + strerror(errno), GEOPM_ERROR_MSR_READ, __FILE__, __LINE__); } for (uint32_t batch_idx = 0; batch_idx != m_write_batch.numops; ++batch_idx) { if (m_write_batch.ops[batch_idx].err) { std::ostringstream err_str; err_str << "MSRIOImp::msr_ioctl(): operation failed at offset 0x" << std::hex << m_write_batch.ops[batch_idx].msr << " system error: " << strerror(m_write_batch.ops[batch_idx].err); throw Exception(err_str.str(), GEOPM_ERROR_MSR_WRITE, __FILE__, __LINE__); } } } void MSRIOImp::read_batch(std::vector<uint64_t> &raw_value) { if (raw_value.size() < m_read_batch.numops) { raw_value.resize(m_read_batch.numops); } open_msr_batch(); if (m_is_batch_enabled) { msr_ioctl(true); uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_read_batch.numops; ++raw_it, ++batch_idx) { *raw_it = m_read_batch.ops[batch_idx].msrdata; } } else { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_read_batch.numops; ++raw_it, ++batch_idx) { *raw_it = read_msr(m_read_batch_op[batch_idx].cpu, m_read_batch_op[batch_idx].msr); } } } void MSRIOImp::write_batch(const std::vector<uint64_t> &raw_value) { if (raw_value.size() < m_write_batch.numops) { throw Exception("MSRIOImp::write_batch(): input vector smaller than configured number of operations", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } open_msr_batch(); #ifdef GEOPM_ENABLE_MSRSAFE_IOCTL_WRITE if (m_is_batch_enabled) { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_write_batch.numops; ++raw_it, ++batch_idx) { m_write_batch.ops[batch_idx].msrdata = *raw_it; } msr_ioctl(false); } else #endif { uint32_t batch_idx = 0; for (auto raw_it = raw_value.begin(); batch_idx != m_write_batch.numops; ++raw_it, ++batch_idx) { write_msr(m_write_batch_op[batch_idx].cpu, m_write_batch_op[batch_idx].msr, *raw_it, m_write_batch_op[batch_idx].wmask); } } } int MSRIOImp::msr_desc(int cpu_idx) { if (cpu_idx < 0 || cpu_idx > m_num_cpu) { throw Exception("MSRIOImp::msr_desc(): cpu_idx=" + std::to_string(cpu_idx) + " out of range, num_cpu=" + std::to_string(m_num_cpu), GEOPM_ERROR_INVALID, __FILE__, __LINE__); } open_msr(cpu_idx); return m_file_desc[cpu_idx]; } int MSRIOImp::msr_batch_desc() { return m_file_desc[m_num_cpu]; } void MSRIOImp::msr_path(int cpu_idx, bool is_fallback, std::string &path) { std::ostringstream msr_path; msr_path << "/dev/cpu/" << cpu_idx; if (!is_fallback) { msr_path << "/msr_safe"; } else { msr_path << "/msr"; } path = msr_path.str(); } void MSRIOImp::msr_batch_path(std::string &path) { path = "/dev/cpu/msr_batch"; } void MSRIOImp::open_msr(int cpu_idx) { if (m_file_desc[cpu_idx] == -1) { std::string path; msr_path(cpu_idx, false, path); m_file_desc[cpu_idx] = open(path.c_str(), O_RDWR); if (m_file_desc[cpu_idx] == -1) { errno = 0; msr_path(cpu_idx, true, path); m_file_desc[cpu_idx] = open(path.c_str(), O_RDWR); if (m_file_desc[cpu_idx] == -1) { throw Exception("MSRIOImp::open_msr(): Failed to open \"" + path + "\": " + "system error: " + strerror(errno), GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } } struct stat stat_buffer; int err = fstat(m_file_desc[cpu_idx], &stat_buffer); if (err) { throw Exception("MSRIOImp::open_msr(): file descriptor invalid", GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } void MSRIOImp::open_msr_batch(void) { if (m_is_batch_enabled && m_file_desc[m_num_cpu] == -1) { std::string path; msr_batch_path(path); m_file_desc[m_num_cpu] = open(path.c_str(), O_RDWR); if (m_file_desc[m_num_cpu] == -1) { m_is_batch_enabled = false; } } if (m_is_batch_enabled) { struct stat stat_buffer; int err = fstat(m_file_desc[m_num_cpu], &stat_buffer); if (err) { throw Exception("MSRIOImp::open_msr_batch(): file descriptor invalid", GEOPM_ERROR_MSR_OPEN, __FILE__, __LINE__); } } } void MSRIOImp::close_msr(int cpu_idx) { if (m_file_desc[cpu_idx] != -1) { (void)close(m_file_desc[cpu_idx]); m_file_desc[cpu_idx] = -1; } } void MSRIOImp::close_msr_batch(void) { if (m_file_desc[m_num_cpu] != -1) { (void)close(m_file_desc[m_num_cpu]); m_file_desc[m_num_cpu] = -1; } } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/clientmodel.h> #include <qt/bantablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/peertablemodel.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> #include <validation.h> #include <net.h> #include <txmempool.h> #include <ui_interface.h> #include <util.h> #include <warnings.h> #include <stdint.h> #include <QDebug> #include <QTimer> class CBlockIndex; static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); versionOutDated = false; subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } void ClientModel::updateBlockchainStatus(int status) { Q_EMIT BlockchainStatusChanged(status); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(GetStartupTime()).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void NotifyBlockchainStatusChanged(ClientModel *clientmodel, int newStatus) { qDebug() << "NotifyBlockchainStatusChanged: " + QString::number(newStatus); QMetaObject::invokeMethod(clientmodel, "updateBlockchainStatus", Qt::QueuedConnection, Q_ARG(int, newStatus)); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass an async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } bool ClientModel::isNewVersionAvailable() { //Connect to default tor node QNetworkProxy proxy; proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName("127.0.0.1"); proxy.setPort(9081); QUrl url("https://deeponion.org/latestversion.txt"); qInfo() << url.toString(); QNetworkRequest request(url); QNetworkAccessManager nam; nam.setProxy(proxy); QNetworkReply * reply = nam.get(request); QTimer timer; timer.setSingleShot(true); timer.start(5000); while(timer.isActive()){ qApp->processEvents(); if(reply->isFinished()){ timer.stop(); // QMessageBox Msgbox; // Msgbox.setText(reply->readAll()); // Msgbox.exec(); QByteArray response_data = reply->readAll(); int ver = QString(response_data).toInt(); if(ver == 0) { versionStatus = "<i> - not available - </i>"; reply->close(); return false; //Empty response } if(isNewVersion(ver)) { versionStatus = "<font color=red>outdated</>"; versionOutDated = true; } else { versionStatus = "<font color=green>up to date</>"; versionOutDated = false; } reply->close(); return true; } } //Timeout versionStatus = "<i> - not available - </i>"; reply->close(); return false; } bool ClientModel::isNewVersion(int ver) { if(ver > CLIENT_VERSION) return true; else return true;// return false; } QString ClientModel::VersionStatus() { return versionStatus; } bool ClientModel::VersionOutDated() { return versionOutDated; } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyBlockchainStatusChanged.connect(boost::bind(NotifyBlockchainStatusChanged, this, _1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyBlockchainStatusChanged.disconnect(boost::bind(NotifyBlockchainStatusChanged, this, _1)); } <commit_msg>remove debugging config<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/clientmodel.h> #include <qt/bantablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/peertablemodel.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> #include <validation.h> #include <net.h> #include <txmempool.h> #include <ui_interface.h> #include <util.h> #include <warnings.h> #include <stdint.h> #include <QDebug> #include <QTimer> class CBlockIndex; static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); versionOutDated = false; subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } void ClientModel::updateBlockchainStatus(int status) { Q_EMIT BlockchainStatusChanged(status); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(GetStartupTime()).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void NotifyBlockchainStatusChanged(ClientModel *clientmodel, int newStatus) { qDebug() << "NotifyBlockchainStatusChanged: " + QString::number(newStatus); QMetaObject::invokeMethod(clientmodel, "updateBlockchainStatus", Qt::QueuedConnection, Q_ARG(int, newStatus)); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass an async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } bool ClientModel::isNewVersionAvailable() { //Connect to default tor node QNetworkProxy proxy; proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName("127.0.0.1"); proxy.setPort(9081); QUrl url("https://deeponion.org/latestversion.txt"); qInfo() << url.toString(); QNetworkRequest request(url); QNetworkAccessManager nam; nam.setProxy(proxy); QNetworkReply * reply = nam.get(request); QTimer timer; timer.setSingleShot(true); timer.start(5000); while(timer.isActive()){ qApp->processEvents(); if(reply->isFinished()){ timer.stop(); // QMessageBox Msgbox; // Msgbox.setText(reply->readAll()); // Msgbox.exec(); QByteArray response_data = reply->readAll(); int ver = QString(response_data).toInt(); if(ver == 0) { versionStatus = "<i> - not available - </i>"; reply->close(); return false; //Empty response } if(isNewVersion(ver)) { versionStatus = "<font color=red>outdated</>"; versionOutDated = true; } else { versionStatus = "<font color=green>up to date</>"; versionOutDated = false; } reply->close(); return true; } } //Timeout versionStatus = "<i> - not available - </i>"; reply->close(); return false; } bool ClientModel::isNewVersion(int ver) { if(ver > CLIENT_VERSION) return true; else return false; } QString ClientModel::VersionStatus() { return versionStatus; } bool ClientModel::VersionOutDated() { return versionOutDated; } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyBlockchainStatusChanged.connect(boost::bind(NotifyBlockchainStatusChanged, this, _1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyBlockchainStatusChanged.disconnect(boost::bind(NotifyBlockchainStatusChanged, this, _1)); } <|endoftext|>
<commit_before>/* db2.cc DB2 OCI Interface to Qore DBI layer Qore Programming Language Copyright 2009 Qore Technologies, sro This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../config.h" #include <qore/Qore.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <strings.h> #include <assert.h> #include <unistd.h> #include <sqlcli1.h> #include <sqlutil.h> #include <sqlenv.h> #include <memory> #include <string> static QoreStringNode *db2_module_init(); static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns); static void db2_module_delete(); DLLEXPORT char qore_module_name[] = "db2"; DLLEXPORT char qore_module_version[] = PACKAGE_VERSION; DLLEXPORT char qore_module_description[] = "DB2 database driver"; DLLEXPORT char qore_module_author[] = "Qore Technologies, sro"; DLLEXPORT char qore_module_url[] = "http://www.qoretechnologies.com"; DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR; DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR; DLLEXPORT qore_module_init_t qore_module_init = db2_module_init; DLLEXPORT qore_module_ns_init_t qore_module_ns_init = db2_module_ns_init; DLLEXPORT qore_module_delete_t qore_module_delete = db2_module_delete; DLLEXPORT qore_license_t qore_module_license = QL_LGPL; // capabilities of this driver #define DBI_DB2_CAPS (DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER) DBIDriver *DBID_DB2 = 0; static QoreString QoreDB2ClientName; static QoreString this_hostname; static const char *this_user = 0; class QoreDB2Handle { }; class QoreDB2 { private: SQLHANDLE henv, hdbc; // add diagnostic info to exception description string DLLLOCAL static void addDiagnostics(SQLSMALLINT htype, SQLHANDLE hndl, QoreStringNode *desc) { SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1]; SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length, i = 1; // get multiple field settings of diagnostic record while (SQLGetDiagRec(htype, hndl, i, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length) == SQL_SUCCESS) { if (i > 1) desc->concat("; "); desc->sprintf("SQLSTATE: %s, native error code: %d: %s", sqlstate, sqlcode, message); i++; } if (i == 1) desc->concat("no diagnostic information available"); } public: DLLLOCAL QoreDB2(const std::string &dbname, const std::string &user, const std::string &pass, ExceptionSink *xsink) : henv(0), hdbc(0) { SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); if (rc != SQL_SUCCESS) { xsink->raiseException("DBI:DB2:OPEN-ERROR", "error allocating environment handle: SQLAllocHandle() returned %d", rc); return; } //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)\n"); // set environment attributes rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_APPLNAME, (void *)QoreDB2ClientName.getBuffer(), 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_WRKSTNNAME, (void *)this_hostname.getBuffer(), 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_USERID)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_USERID, (void *)this_user, 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_USERID)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLAllocHandle(SQL_HANDLE_DBC)\n"); rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLAllocHandle(SQL_HANDLE_DBC)", xsink)) return; // set connection attributes //printd(5, "QoreDB2::QoreDB2() calling SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)\n"); rc = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLConnect()\n"); rc = SQLConnect(hdbc, (SQLCHAR *)dbname.c_str(), dbname.size(), (SQLCHAR *)user.c_str(), user.size(), (SQLCHAR *)pass.c_str(), pass.size()); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLConnect()", xsink)) return; } DLLLOCAL ~QoreDB2() { if (hdbc) { // TODO: check return value? SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); } if (henv) { SQLFreeHandle(SQL_HANDLE_ENV, henv); } } DLLLOCAL int commit(ExceptionSink *xsink) { SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "SQLEndTran(SQL_COMMIT)", xsink)) return -1; return 0; } DLLLOCAL int rollback(ExceptionSink *xsink) { SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_ROLLBACK); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "SQLEndTran(SQL_ROLLBACK)", xsink)) return -1; return 0; } DLLLOCAL static int checkError(SQLSMALLINT htype, SQLHANDLE hndl, SQLRETURN rc, const char *info, ExceptionSink *xsink) { switch (rc) { case SQL_SUCCESS: return 0; case SQL_INVALID_HANDLE: assert(false); return -1; case SQL_ERROR: { QoreStringNode *desc = new QoreStringNode(); desc->sprintf("error %d in %s: ", rc, info); addDiagnostics(htype, hndl, desc); xsink->raiseException("DBI:DB2:ERROR", desc); return -1; } case SQL_SUCCESS_WITH_INFO: case SQL_STILL_EXECUTING: case SQL_NEED_DATA: case SQL_NO_DATA_FOUND: return 0; } QoreStringNode *desc = new QoreStringNode(); desc->sprintf("unknown error %d returned in %s: ", rc, info); addDiagnostics(htype, hndl, desc); xsink->raiseException("DBI:DB2:ERROR", desc); return -1; } }; static AbstractQoreNode *db2_exec(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return 0; } static AbstractQoreNode *db2_select(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return 0; } static AbstractQoreNode *db2_select_rows(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return 0; } static int db2_commit(Datasource *ds, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->commit(xsink); } static int db2_rollback(Datasource *ds, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->rollback(xsink); } static int db2_open(Datasource *ds, ExceptionSink *xsink) { if (!ds->getDBName()) { xsink->raiseException("DATASOURCE-MISSING-DBNAME", "missing dbname in datasource connection"); return -1; } std::auto_ptr<QoreDB2> db2(new QoreDB2(ds->getDBNameStr(), ds->getUsernameStr(), ds->getPasswordStr(), xsink)); if (*xsink) return -1; ds->setPrivateData((void *)db2.release()); return 0; } static int db2_close(Datasource *ds) { QORE_TRACE("db2_close()"); QoreDB2 *d_db2 = (QoreDB2 *)ds->getPrivateData(); delete d_db2; ds->setPrivateData(0); return 0; } static AbstractQoreNode *db2_get_server_version(Datasource *ds, ExceptionSink *xsink) { // get private data structure for connection //QoreDB2 *db2 = (QoreDB2 *)ds->getPrivateData(); return 0; } static AbstractQoreNode *db2_get_client_version(const Datasource *ds, ExceptionSink *xsink) { return 0; } #ifndef HOSTNAMEBUFSIZE #define HOSTNAMEBUFSIZE 512 #endif static QoreStringNode *db2_module_init() { QORE_TRACE("db2_module_init()"); QoreDB2ClientName.sprintf("Qore DB2 driver v%s on Qore v%s %s %s", PACKAGE_VERSION, qore_version_string, qore_target_arch, qore_target_os); // DB2 API global initialization // turn off thread locking in the DB2 API - all locking will be provided by qore SQLRETURN rc = SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0); if (rc != SQL_SUCCESS) { QoreStringNode *err = new QoreStringNode("error initializing DB2 API: SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0) returned %d", rc); return err; } // get username this_user = getlogin(); if (!this_user) this_user = "<unknown user>"; // get hostname char buf[HOSTNAMEBUFSIZE + 1]; this_hostname.set(!gethostname(buf, HOSTNAMEBUFSIZE) ? buf : "<unknown>"); // register driver with DBI subsystem qore_dbi_method_list methods; methods.add(QDBI_METHOD_OPEN, db2_open); methods.add(QDBI_METHOD_CLOSE, db2_close); methods.add(QDBI_METHOD_SELECT, db2_select); methods.add(QDBI_METHOD_SELECT_ROWS, db2_select_rows); methods.add(QDBI_METHOD_EXEC, db2_exec); methods.add(QDBI_METHOD_COMMIT, db2_commit); methods.add(QDBI_METHOD_ROLLBACK, db2_rollback); methods.add(QDBI_METHOD_GET_SERVER_VERSION, db2_get_server_version); methods.add(QDBI_METHOD_GET_CLIENT_VERSION, db2_get_client_version); DBID_DB2 = DBI.registerDriver("db2", methods, DBI_DB2_CAPS); return 0; } static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) { QORE_TRACE("db2_module_ns_init()"); // nothing to do at the moment } static void db2_module_delete() { QORE_TRACE("db2_module_delete()"); } <commit_msg>initial support for executing queries<commit_after>/* db2.cc DB2 OCI Interface to Qore DBI layer Qore Programming Language Copyright 2009 Qore Technologies, sro This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../config.h" #include <qore/Qore.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <strings.h> #include <assert.h> #include <unistd.h> #include <sqlcli1.h> #include <sqlutil.h> #include <sqlenv.h> #include <memory> #include <string> static QoreStringNode *db2_module_init(); static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns); static void db2_module_delete(); DLLEXPORT char qore_module_name[] = "db2"; DLLEXPORT char qore_module_version[] = PACKAGE_VERSION; DLLEXPORT char qore_module_description[] = "DB2 database driver"; DLLEXPORT char qore_module_author[] = "Qore Technologies, sro"; DLLEXPORT char qore_module_url[] = "http://www.qoretechnologies.com"; DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR; DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR; DLLEXPORT qore_module_init_t qore_module_init = db2_module_init; DLLEXPORT qore_module_ns_init_t qore_module_ns_init = db2_module_ns_init; DLLEXPORT qore_module_delete_t qore_module_delete = db2_module_delete; DLLEXPORT qore_license_t qore_module_license = QL_LGPL; // capabilities of this driver #define DBI_DB2_CAPS (DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER) DBIDriver *DBID_DB2 = 0; static QoreString QoreDB2ClientName; static QoreString this_hostname; static const char *this_user = 0; #define QORE_DB2_MAX_COL_NAME_LEN 128 //class QoreDB2Handle {}; class QoreDB2 { private: SQLHANDLE henv, hdbc; // add diagnostic info to exception description string DLLLOCAL static void addDiagnostics(SQLSMALLINT htype, SQLHANDLE hndl, QoreStringNode *desc) { SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1]; SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length, i = 1; // get multiple field settings of diagnostic record while (SQLGetDiagRec(htype, hndl, i, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length) == SQL_SUCCESS) { if (i > 1) desc->concat("; "); desc->sprintf("SQLSTATE: %s, native error code: %d: %s", sqlstate, sqlcode, message); i++; } if (i == 1) desc->concat("no diagnostic information available"); } public: DLLLOCAL QoreDB2(const std::string &dbname, const std::string &user, const std::string &pass, ExceptionSink *xsink) : henv(0), hdbc(0) { SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); if (rc != SQL_SUCCESS) { xsink->raiseException("DBI:DB2:OPEN-ERROR", "error allocating environment handle: SQLAllocHandle() returned %d", rc); return; } //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)\n"); // set environment attributes rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_APPLNAME, (void *)QoreDB2ClientName.getBuffer(), 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_WRKSTNNAME, (void *)this_hostname.getBuffer(), 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_USERID)\n"); rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_USERID, (void *)this_user, 0); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_USERID)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLAllocHandle(SQL_HANDLE_DBC)\n"); rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLAllocHandle(SQL_HANDLE_DBC)", xsink)) return; // set connection attributes //printd(5, "QoreDB2::QoreDB2() calling SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)\n"); rc = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)", xsink)) return; //printd(5, "QoreDB2::QoreDB2() calling SQLConnect()\n"); rc = SQLConnect(hdbc, (SQLCHAR *)dbname.c_str(), dbname.size(), (SQLCHAR *)user.c_str(), user.size(), (SQLCHAR *)pass.c_str(), pass.size()); if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLConnect()", xsink)) return; } DLLLOCAL ~QoreDB2() { if (hdbc) { // TODO: check return value? SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); } if (henv) { SQLFreeHandle(SQL_HANDLE_ENV, henv); } } DLLLOCAL int commit(ExceptionSink *xsink) { SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT); if (QoreDB2::checkError(SQL_HANDLE_DBC, hdbc, rc, "SQLEndTran(SQL_COMMIT)", xsink)) return -1; return 0; } DLLLOCAL int rollback(ExceptionSink *xsink) { SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_ROLLBACK); if (QoreDB2::checkError(SQL_HANDLE_DBC, hdbc, rc, "SQLEndTran(SQL_ROLLBACK)", xsink)) return -1; return 0; } DLLLOCAL AbstractQoreNode *select(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) { SQLHANDLE hstmt; SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); if (QoreDB2::checkError(SQL_HANDLE_DBC, henv, rc, "select: SQLAllocHandle(SQL_HANDLE_STMT)", xsink)) return 0; // free handle on block exit ON_BLOCK_EXIT(SQLFreeHandle, SQL_HANDLE_STMT, hstmt); // prepare the statement rc = SQLPrepare(hstmt, (SQLCHAR*)sql.getBuffer(), SQL_NTS); if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLPrepare()", xsink)) return 0; rc = SQLExecute(hstmt); if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLExecute()", xsink)) return 0; SQLSMALLINT cols; rc = SQLNumResultCols(hstmt, &cols); if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLNumResultCols()", xsink)) return 0; printd(0, "QoreDB2::select() query returned %d columns\n", (int)cols); for (int i = 0; i < cols; ++i) { SQLSMALLINT colNameLen; SQLSMALLINT colType; SQLUINTEGER colSize; SQLSMALLINT colScale; char cname[QORE_DB2_MAX_COL_NAME_LEN + 1]; rc = SQLDescribeCol(hstmt, (SQLSMALLINT)(i + 1), (SQLCHAR*)cname, sizeof(cname), &colNameLen, &colType, &colSize, &colScale, 0); if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLDescribeCol()", xsink)) return 0; printd(0, "column %d/%d: %s: type=%d size=%d scale=%d\n", i, cols, cname, colType, colSize, colScale); } return 0; } DLLLOCAL AbstractQoreNode *exec(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) { return 0; } DLLLOCAL AbstractQoreNode *select_rows(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) { return 0; } DLLLOCAL static int checkError(SQLSMALLINT htype, SQLHANDLE hndl, SQLRETURN rc, const char *info, ExceptionSink *xsink) { switch (rc) { case SQL_SUCCESS: return 0; case SQL_INVALID_HANDLE: assert(false); return -1; case SQL_ERROR: { QoreStringNode *desc = new QoreStringNode(); desc->sprintf("error %d in %s: ", rc, info); addDiagnostics(htype, hndl, desc); xsink->raiseException("DBI:DB2:ERROR", desc); return -1; } case SQL_SUCCESS_WITH_INFO: case SQL_STILL_EXECUTING: case SQL_NEED_DATA: case SQL_NO_DATA_FOUND: return 0; } QoreStringNode *desc = new QoreStringNode(); desc->sprintf("unknown error %d returned in %s: ", rc, info); addDiagnostics(htype, hndl, desc); xsink->raiseException("DBI:DB2:ERROR", desc); return -1; } }; static AbstractQoreNode *db2_exec(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->exec(*qstr, args, xsink); } static AbstractQoreNode *db2_select(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->select(*qstr, args, xsink); } static AbstractQoreNode *db2_select_rows(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->select_rows(*qstr, args, xsink); } static int db2_commit(Datasource *ds, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->commit(xsink); } static int db2_rollback(Datasource *ds, ExceptionSink *xsink) { return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->rollback(xsink); } static int db2_open(Datasource *ds, ExceptionSink *xsink) { if (!ds->getDBName()) { xsink->raiseException("DATASOURCE-MISSING-DBNAME", "missing dbname in datasource connection"); return -1; } std::auto_ptr<QoreDB2> db2(new QoreDB2(ds->getDBNameStr(), ds->getUsernameStr(), ds->getPasswordStr(), xsink)); if (*xsink) return -1; ds->setPrivateData((void *)db2.release()); return 0; } static int db2_close(Datasource *ds) { QORE_TRACE("db2_close()"); QoreDB2 *d_db2 = (QoreDB2 *)ds->getPrivateData(); delete d_db2; ds->setPrivateData(0); return 0; } static AbstractQoreNode *db2_get_server_version(Datasource *ds, ExceptionSink *xsink) { // get private data structure for connection //QoreDB2 *db2 = (QoreDB2 *)ds->getPrivateData(); return 0; } static AbstractQoreNode *db2_get_client_version(const Datasource *ds, ExceptionSink *xsink) { return 0; } #ifndef HOSTNAMEBUFSIZE #define HOSTNAMEBUFSIZE 512 #endif static QoreStringNode *db2_module_init() { QORE_TRACE("db2_module_init()"); QoreDB2ClientName.sprintf("Qore DB2 driver v%s on Qore v%s %s %s", PACKAGE_VERSION, qore_version_string, qore_target_arch, qore_target_os); // DB2 API global initialization // turn off thread locking in the DB2 API - all locking will be provided by qore SQLRETURN rc = SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0); if (rc != SQL_SUCCESS) { QoreStringNode *err = new QoreStringNode("error initializing DB2 API: SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0) returned %d", rc); return err; } // get username this_user = getlogin(); if (!this_user) this_user = "<unknown user>"; // get hostname char buf[HOSTNAMEBUFSIZE + 1]; this_hostname.set(!gethostname(buf, HOSTNAMEBUFSIZE) ? buf : "<unknown>"); // register driver with DBI subsystem qore_dbi_method_list methods; methods.add(QDBI_METHOD_OPEN, db2_open); methods.add(QDBI_METHOD_CLOSE, db2_close); methods.add(QDBI_METHOD_SELECT, db2_select); methods.add(QDBI_METHOD_SELECT_ROWS, db2_select_rows); methods.add(QDBI_METHOD_EXEC, db2_exec); methods.add(QDBI_METHOD_COMMIT, db2_commit); methods.add(QDBI_METHOD_ROLLBACK, db2_rollback); methods.add(QDBI_METHOD_GET_SERVER_VERSION, db2_get_server_version); methods.add(QDBI_METHOD_GET_CLIENT_VERSION, db2_get_client_version); DBID_DB2 = DBI.registerDriver("db2", methods, DBI_DB2_CAPS); return 0; } static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) { QORE_TRACE("db2_module_ns_init()"); // nothing to do at the moment } static void db2_module_delete() { QORE_TRACE("db2_module_delete()"); } <|endoftext|>
<commit_before>#include <iostream> #include "common/state/ray_config.h" #include "ray/raylet/raylet.h" #include "ray/status.h" #ifndef RAYLET_TEST int main(int argc, char *argv[]) { RAY_CHECK(argc == 9); const std::string raylet_socket_name = std::string(argv[1]); const std::string store_socket_name = std::string(argv[2]); const std::string node_ip_address = std::string(argv[3]); const std::string redis_address = std::string(argv[4]); int redis_port = std::stoi(argv[5]); int num_initial_workers = std::stoi(argv[6]); const std::string worker_command = std::string(argv[7]); const std::string static_resource_list = std::string(argv[8]); // Configuration for the node manager. ray::raylet::NodeManagerConfig node_manager_config; std::unordered_map<std::string, double> static_resource_conf; // Parse the resource list. std::istringstream resource_string(static_resource_list); std::string resource_name; std::string resource_quantity; while (std::getline(resource_string, resource_name, ',')) { RAY_CHECK(std::getline(resource_string, resource_quantity, ',')); // TODO(rkn): The line below could throw an exception. What should we do about this? static_resource_conf[resource_name] = std::stod(resource_quantity); } node_manager_config.resource_config = ray::raylet::ResourceSet(std::move(static_resource_conf)); RAY_LOG(INFO) << "Starting raylet with static resource configuration: " << node_manager_config.resource_config.ToString(); node_manager_config.num_initial_workers = num_initial_workers; node_manager_config.num_workers_per_process = RayConfig::instance().num_workers_per_process(); // Use a default worker that can execute empty tasks with dependencies. std::stringstream worker_command_stream(worker_command); std::string token; while (getline(worker_command_stream, token, ' ')) { node_manager_config.worker_command.push_back(token); } node_manager_config.heartbeat_period_ms = RayConfig::instance().heartbeat_timeout_milliseconds(); node_manager_config.max_lineage_size = RayConfig::instance().max_lineage_size(); // Configuration for the object manager. ray::ObjectManagerConfig object_manager_config; object_manager_config.store_socket_name = store_socket_name; object_manager_config.pull_timeout_ms = RayConfig::instance().object_manager_pull_timeout_ms(); object_manager_config.push_timeout_ms = RayConfig::instance().object_manager_push_timeout_ms(); int num_cpus = static_cast<int>(static_resource_conf["CPU"]); object_manager_config.max_sends = std::max(1, num_cpus / 4); object_manager_config.max_receives = std::max(1, num_cpus / 4); object_manager_config.object_chunk_size = RayConfig::instance().object_manager_default_chunk_size(); RAY_LOG(INFO) << "Starting object manager with configuration: \n" "max_sends = " << object_manager_config.max_sends << "\n" "max_receives = " << object_manager_config.max_receives << "\n" "object_chunk_size = " << object_manager_config.object_chunk_size; // initialize mock gcs & object directory auto gcs_client = std::make_shared<ray::gcs::AsyncGcsClient>(); RAY_LOG(INFO) << "Initializing GCS client " << gcs_client->client_table().GetLocalClientId(); // Initialize the node manager. boost::asio::io_service main_service; ray::raylet::Raylet server(main_service, raylet_socket_name, node_ip_address, redis_address, redis_port, node_manager_config, object_manager_config, gcs_client); // Destroy the Raylet on a SIGTERM. The pointer to main_service is // guaranteed to be valid since this function will run the event loop // instead of returning immediately. auto handler = [&main_service](const boost::system::error_code &error, int signal_number) { main_service.stop(); }; boost::asio::signal_set signals(main_service, SIGTERM); signals.async_wait(handler); main_service.run(); } #endif <commit_msg>[xray] Silence some object manager logging (#2437)<commit_after>#include <iostream> #include "common/state/ray_config.h" #include "ray/raylet/raylet.h" #include "ray/status.h" #ifndef RAYLET_TEST int main(int argc, char *argv[]) { RAY_CHECK(argc == 9); const std::string raylet_socket_name = std::string(argv[1]); const std::string store_socket_name = std::string(argv[2]); const std::string node_ip_address = std::string(argv[3]); const std::string redis_address = std::string(argv[4]); int redis_port = std::stoi(argv[5]); int num_initial_workers = std::stoi(argv[6]); const std::string worker_command = std::string(argv[7]); const std::string static_resource_list = std::string(argv[8]); // Configuration for the node manager. ray::raylet::NodeManagerConfig node_manager_config; std::unordered_map<std::string, double> static_resource_conf; // Parse the resource list. std::istringstream resource_string(static_resource_list); std::string resource_name; std::string resource_quantity; while (std::getline(resource_string, resource_name, ',')) { RAY_CHECK(std::getline(resource_string, resource_quantity, ',')); // TODO(rkn): The line below could throw an exception. What should we do about this? static_resource_conf[resource_name] = std::stod(resource_quantity); } node_manager_config.resource_config = ray::raylet::ResourceSet(std::move(static_resource_conf)); RAY_LOG(DEBUG) << "Starting raylet with static resource configuration: " << node_manager_config.resource_config.ToString(); node_manager_config.num_initial_workers = num_initial_workers; node_manager_config.num_workers_per_process = RayConfig::instance().num_workers_per_process(); // Use a default worker that can execute empty tasks with dependencies. std::stringstream worker_command_stream(worker_command); std::string token; while (getline(worker_command_stream, token, ' ')) { node_manager_config.worker_command.push_back(token); } node_manager_config.heartbeat_period_ms = RayConfig::instance().heartbeat_timeout_milliseconds(); node_manager_config.max_lineage_size = RayConfig::instance().max_lineage_size(); // Configuration for the object manager. ray::ObjectManagerConfig object_manager_config; object_manager_config.store_socket_name = store_socket_name; object_manager_config.pull_timeout_ms = RayConfig::instance().object_manager_pull_timeout_ms(); object_manager_config.push_timeout_ms = RayConfig::instance().object_manager_push_timeout_ms(); int num_cpus = static_cast<int>(static_resource_conf["CPU"]); object_manager_config.max_sends = std::max(1, num_cpus / 4); object_manager_config.max_receives = std::max(1, num_cpus / 4); object_manager_config.object_chunk_size = RayConfig::instance().object_manager_default_chunk_size(); RAY_LOG(DEBUG) << "Starting object manager with configuration: \n" << "max_sends = " << object_manager_config.max_sends << "\n" << "max_receives = " << object_manager_config.max_receives << "\n" << "object_chunk_size = " << object_manager_config.object_chunk_size; // initialize mock gcs & object directory auto gcs_client = std::make_shared<ray::gcs::AsyncGcsClient>(); RAY_LOG(DEBUG) << "Initializing GCS client " << gcs_client->client_table().GetLocalClientId(); // Initialize the node manager. boost::asio::io_service main_service; ray::raylet::Raylet server(main_service, raylet_socket_name, node_ip_address, redis_address, redis_port, node_manager_config, object_manager_config, gcs_client); // Destroy the Raylet on a SIGTERM. The pointer to main_service is // guaranteed to be valid since this function will run the event loop // instead of returning immediately. auto handler = [&main_service](const boost::system::error_code &error, int signal_number) { main_service.stop(); }; boost::asio::signal_set signals(main_service, SIGTERM); signals.async_wait(handler); main_service.run(); } #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 "Paths.h" namespace madai { #ifdef WIN32 const char Paths::SEPARATOR = '\\'; #else const char Paths::SEPARATOR = '/'; #endif const std::string Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY( "model_output" ); const std::string Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY( "experimental_results" ); const std::string Paths::TRACE_DIRECTORY( "trace" ); const std::string Paths::OBSERVABLE_NAMES_FILE( "observable_names.dat" ); const std::string Paths::PARAMETERS_FILE( "parameters.dat" ); const std::string Paths::RESULTS_FILE( "results.dat" ); const std::string Paths::RUNTIME_PARAMETER_FILE( "stat_params.dat" ); const std::string Paths::EMULATOR_STATE_FILE( "emulator_state.dat" ); const std::string Paths::PCA_DECOMPOSITION_FILE( "pca_decomposition.dat" ); const std::string Paths::PARAMETER_PRIORS_FILE( "parameter_priors.dat" ); } // end namespace madai <commit_msg>Renamed stat_params.dat => settings.dat<commit_after>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 "Paths.h" namespace madai { #ifdef WIN32 const char Paths::SEPARATOR = '\\'; #else const char Paths::SEPARATOR = '/'; #endif const std::string Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY( "model_output" ); const std::string Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY( "experimental_results" ); const std::string Paths::TRACE_DIRECTORY( "trace" ); const std::string Paths::OBSERVABLE_NAMES_FILE( "observable_names.dat" ); const std::string Paths::PARAMETERS_FILE( "parameters.dat" ); const std::string Paths::RESULTS_FILE( "results.dat" ); const std::string Paths::RUNTIME_PARAMETER_FILE( "settings.dat" ); const std::string Paths::EMULATOR_STATE_FILE( "emulator_state.dat" ); const std::string Paths::PCA_DECOMPOSITION_FILE( "pca_decomposition.dat" ); const std::string Paths::PARAMETER_PRIORS_FILE( "parameter_priors.dat" ); } // end namespace madai <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: PtLoad.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "PtLoad.hh" #include "vtkMath.hh" #include "FTensors.hh" // Description: // Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50), // and LoadValue = 1. vtkPointLoad::vtkPointLoad() { this->LoadValue = 1.0; this->ModelBounds[0] = -1.0; this->ModelBounds[1] = 1.0; this->ModelBounds[2] = -1.0; this->ModelBounds[3] = 1.0; this->ModelBounds[4] = -1.0; this->ModelBounds[5] = 1.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; } // Description: // Specify the dimensions of the volume. A stress tensor will be computed for // each point in the volume. void vtkPointLoad::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Description: // Specify the dimensions of the volume. A stress tensor will be computed for // each point in the volume. void vtkPointLoad::SetSampleDimensions(int dim[3]) { vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] || dim[2] != SampleDimensions[2] ) { for ( int i=0; i<3; i++) this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1); this->Modified(); } } // Description: // Specify the region in space over which the tensors are computed. The point // load is assumed to be applied at top center of the volume. void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax) { if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax || this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax || this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax ) { this->Modified(); this->ModelBounds[0] = xmin; this->ModelBounds[1] = xmax; this->ModelBounds[2] = ymin; this->ModelBounds[3] = ymax; this->ModelBounds[4] = zmin; this->ModelBounds[5] = zmax; } } // Description: // Specify the region in space over which the tensors are computed. The point // load is assumed to be applied at top center of the volume. void vtkPointLoad::SetModelBounds(float *bounds) { vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); } void vtkPointLoad::Execute() { int ptId, i; vtkFloatTensors *newTensors; vtkTensor tensor; int numPts; vtkMath math; vtkDebugMacro(<< "Computing point load stress tensors"); // // Initialize self; create output objects // this->Initialize(); numPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newTensors = new vtkFloatTensors(numPts); // Compute origin and aspect ratio this->SetDimensions(this->GetSampleDimensions()); for (i=0; i < 3; i++) { this->Origin[i] = this->ModelBounds[2*i]; this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } // // Traverse all points evaluating implicit function at each point // for (ptId=0; ptId < numPts; ptId++ ) { } // // Update self // this->PointData.SetTensors(newTensors); } void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredPointsSource::PrintSelf(os,indent); os << indent << "Load Value: " << this->LoadValue << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; } <commit_msg>ENH: IMplementation.<commit_after>/*========================================================================= Program: Visualization Library Module: PtLoad.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "PtLoad.hh" #include "vtkMath.hh" #include "FTensors.hh" // Description: // Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50), // and LoadValue = 1. vtkPointLoad::vtkPointLoad() { this->LoadValue = 1.0; this->ModelBounds[0] = -1.0; this->ModelBounds[1] = 1.0; this->ModelBounds[2] = -1.0; this->ModelBounds[3] = 1.0; this->ModelBounds[4] = -1.0; this->ModelBounds[5] = 1.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; } // Description: // Specify the dimensions of the volume. A stress tensor will be computed for // each point in the volume. void vtkPointLoad::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Description: // Specify the dimensions of the volume. A stress tensor will be computed for // each point in the volume. void vtkPointLoad::SetSampleDimensions(int dim[3]) { vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] || dim[2] != SampleDimensions[2] ) { for ( int i=0; i<3; i++) this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1); this->Modified(); } } // Description: // Specify the region in space over which the tensors are computed. The point // load is assumed to be applied at top center of the volume. void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax) { if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax || this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax || this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax ) { this->Modified(); this->ModelBounds[0] = xmin; this->ModelBounds[1] = xmax; this->ModelBounds[2] = ymin; this->ModelBounds[3] = ymax; this->ModelBounds[4] = zmin; this->ModelBounds[5] = zmax; } } // Description: // Specify the region in space over which the tensors are computed. The point // load is assumed to be applied at top center of the volume. void vtkPointLoad::SetModelBounds(float *bounds) { vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); } void vtkPointLoad::Execute() { int ptId, i, j, k; vtkFloatTensors *newTensors; vtkTensor tensor; int numPts; vtkMath math; float P, pi, twoPi, xP[3], rho, rho2, rho3, rho5, nu; float x, x2, y, y2, z, z2, z3, rhoPlusz2, zPlus2rho, txy, txz, tyz; vtkDebugMacro(<< "Computing point load stress tensors"); // // Initialize self; create output objects // this->Initialize(); numPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newTensors = new vtkFloatTensors(numPts); // Compute origin and aspect ratio this->SetDimensions(this->GetSampleDimensions()); for (i=0; i < 3; i++) { this->Origin[i] = this->ModelBounds[2*i]; this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } // // Compute the location of the load // xP[0] = (this->ModelBounds[0] + this->ModelBounds[1]) / 2.0; //in center xP[1] = (this->ModelBounds[2] + this->ModelBounds[3]) / 2.0; xP[2] = this->ModelBounds[5]; // at top of box // // Traverse all points evaluating implicit function at each point // twoPi = 2.0*math.Pi(); P = -this->LoadValue; for (k=0; k<this->Dimensions[2]; k++) { z = this->Origin[2] + k*this->AspectRatio[2]; for (j=0; j<this->Dimensions[1]; j++) { y = this->Origin[1] + k*this->AspectRatio[1]; for (i=0; i<this->Dimensions[0]; i++) { x = this->Origin[0] + k*this->AspectRatio[0]; rho = sqrt((x-xP[0])*(x-xP[0]) + (y-xP[1])*(y-xP[1]) + (z-xP[2])*(z-xP[2])); rho2 = rho*rho; rho3 = rho2*rho; rho5 = rho2*rho3; nu = (1.0 - 2.0*this->PoissonsRatio); x2 = x*x; y2 = y*y; rhoPlusz2 = (rho + z) * (rho + z); zPlus2rho = (2.0*rho + z); // normal stresses tensor.SetComponent(0,0, P/(twoPi*rho2) * (3.0*z*x2/rho3 - nu*(z/rho - rho/(rho+z) + x2*(zPlus2rho)/(rho*rhoPlusz2)))); tensor.SetComponent(1,1, P/(twoPi*rho2) * (3.0*z*y2/rho3 - nu*(z/rho - rho/(rho+z) + y2*(zPlus2rho)/(rho*rhoPlusz2)))); tensor.SetComponent(2,2, 3.0*P*z3/(twoPi*rho5)); //shear stresses txy = P/(twoPi*rho2) * (3.0*x*y*z/rho3 - nu*x*y*(zPlus2rho)/(rho*rhoPlusz2)); tensor.SetComponent(0,1,txy); tensor.SetComponent(1,0,txy); txz = 3.0*P*x*z2/(twoPi*rho5); tensor.SetComponent(0,2,txz); tensor.SetComponent(2,0,txz); tyz = 3.0*P*y*z2/(twoPi*rho5); tensor.SetComponent(1,2,tyz); tensor.SetComponent(2,1,tyz); newTensors->InsertNextTensor(tensor); } } } // // Update self // this->PointData.SetTensors(newTensors); } void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent) { vtkStructuredPointsSource::PrintSelf(os,indent); os << indent << "Load Value: " << this->LoadValue << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Poisson's Ratio: " << this->PoissonsRatio << "\n"; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optpath.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:48:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_OPTPATH_HXX #define _SVX_OPTPATH_HXX // include --------------------------------------------------------------- #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifdef _SVX_OPTPATH_CXX #ifndef _HEADBAR_HXX //autogen #include <svtools/headbar.hxx> #endif #else class HeaderBar; #endif #ifndef SVX_CONTROLL_FUCUS_HELPER_HXX #include "ControlFocusHelper.hxx" #endif // forward --------------------------------------------------------------- class SvTabListBox; namespace svx { class OptHeaderTabListBox; } struct OptPath_Impl; // define ---------------------------------------------------------------- #define SfxPathTabPage SvxPathTabPage // class SvxPathTabPage -------------------------------------------------- class SvxPathTabPage : public SfxTabPage { private: FixedText aTypeText; FixedText aPathText; SvxControlFocusHelper aPathCtrl; PushButton aStandardBtn; PushButton aPathBtn; FixedLine aStdBox; HeaderBar* pHeaderBar; ::svx::OptHeaderTabListBox* pPathBox; OptPath_Impl* pImpl; #ifdef _SVX_OPTPATH_CXX DECL_LINK( PathHdl_Impl, PushButton * ); DECL_LINK( StandardHdl_Impl, PushButton * ); DECL_LINK( PathSelect_Impl, OptHeaderTabListBox * ); DECL_LINK( HeaderSelect_Impl, HeaderBar * ); DECL_LINK( HeaderEndDrag_Impl, HeaderBar * ); #endif public: SvxPathTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxPathTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void FillUserData(); }; #endif <commit_msg>INTEGRATION: CWS pathoptions01 (1.5.444); FILE MERGED 2006/07/07 04:51:00 pb 1.5.444.1: fix: #i67100# add Get/SetPathList()<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optpath.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-07-13 12:01:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_OPTPATH_HXX #define _SVX_OPTPATH_HXX // include --------------------------------------------------------------- #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifdef _SVX_OPTPATH_CXX #ifndef _HEADBAR_HXX //autogen #include <svtools/headbar.hxx> #endif #else class HeaderBar; #endif #ifndef SVX_CONTROLL_FUCUS_HELPER_HXX #include "ControlFocusHelper.hxx" #endif // forward --------------------------------------------------------------- class SvTabListBox; namespace svx { class OptHeaderTabListBox; } struct OptPath_Impl; // define ---------------------------------------------------------------- #define SfxPathTabPage SvxPathTabPage // class SvxPathTabPage -------------------------------------------------- class SvxPathTabPage : public SfxTabPage { private: FixedText aTypeText; FixedText aPathText; SvxControlFocusHelper aPathCtrl; PushButton aStandardBtn; PushButton aPathBtn; FixedLine aStdBox; HeaderBar* pHeaderBar; ::svx::OptHeaderTabListBox* pPathBox; OptPath_Impl* pImpl; #ifdef _SVX_OPTPATH_CXX DECL_LINK( PathHdl_Impl, PushButton * ); DECL_LINK( StandardHdl_Impl, PushButton * ); DECL_LINK( PathSelect_Impl, OptHeaderTabListBox * ); DECL_LINK( HeaderSelect_Impl, HeaderBar * ); DECL_LINK( HeaderEndDrag_Impl, HeaderBar * ); void GetPathList( USHORT _nPathHandle, String& _rInternalPath, String& _rUserPath, String& _rWritablePath ); void SetPathList( USHORT _nPathHandle, const String& _rUserPath, const String& _rWritablePath ); #endif public: SvxPathTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxPathTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void FillUserData(); }; #endif <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str()); Secret=read_Secretfile(F.Secretfile,F); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } //diagnostic int count_ss=0; int count_sf=0; for(int g=0;g<M.size();++g){ if(M[g].SS) count_ss++; if(M[g].SF) count_sf++; } printf(" number SS = %d number SF = %d\n",count_ss,count_sf); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if any SS or SF are assigned int SS_count=0; int SF_count=0; std::vector <int> class_count(3,0); for( int j=0;j<F.Nplate;++j){ for (int k=0;k<F.Nfiber;++k){ if(A.TF[j][k]!=-1){ if(M[A.TF[j][k]].SS)SS_count++; if(M[A.TF[j][k]].SF)SF_count++; class_count[M[A.TF[j][k]].priority_class]++; } } } printf("after simple assign, SS assigned %d SF assigned %d\n",SS_count,SF_count); printf(" class 0 %d class 1 %d class 2 %d\n", class_count[0],class_count[1],class_count[2]); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //diagnostic /* for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf(" js = %d available SF for fibers\n",js); for (int k=0;k<10;++k){ printf(" %d ",P[js].SF_av_gal_fiber[k*500].size()); } printf("\n petals"); for (int q=0;q<F.Npetal;++q){ printf(" %d",P[js].SF_av_gal[q].size()); } printf("\n"); } */ //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; //printf(" before assign_sf_ss js= %d\n",js); A.next_plate=js; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile //printf("before assign_unused js= %d \n",js); assign_unused(js,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate); for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate printf(" before pass = %d at %d tiles\n",i,update_intervals[i]); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) { int j = A.suborder[jj]; //printf(" next plate is %d \n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF assign_unused(j,M,P,pp,F,A); //A.next_plate++; } //update target information for interval i //A.next_plate=F.pass_intervals[i]; for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) { //int j = A.suborder[A.next_plate]; //int js=A.suborder[jj]; // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } //if(A.next_plate<F.Nplate){ redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //} if(F.diagnose)diagnostic(M,Secret,F,A); } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>print check of SS SF<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str()); Secret=read_Secretfile(F.Secretfile,F); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } //diagnostic int count_ss=0; int count_sf=0; for(int g=0;g<M.size();++g){ if(M[g].SS) count_ss++; if(M[g].SF) count_sf++; } printf(" number SS = %d number SF = %d\n",count_ss,count_sf); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if any SS or SF are assigned int SS_count=0; int SF_count=0; std::vector <int> class_count(3,0); for( int j=0;j<F.Nplate;++j){ for (int k=0;k<F.Nfiber;++k){ if(A.TF[j][k]!=-1){ if(M[A.TF[j][k]].SS)SS_count++; if(M[A.TF[j][k]].SF)SF_count++; class_count[M[A.TF[j][k]].priority_class]++; } } } printf("after simple assign, SS assigned %d SF assigned %d\n",SS_count,SF_count); printf(" class 0 %d class 1 %d class 2 %d\n", class_count[0],class_count[1],class_count[2]); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //diagnostic /* for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf(" js = %d available SF for fibers\n",js); for (int k=0;k<10;++k){ printf(" %d ",P[js].SF_av_gal_fiber[k*500].size()); } printf("\n petals"); for (int q=0;q<F.Npetal;++q){ printf(" %d",P[js].SF_av_gal[q].size()); } printf("\n"); } */ //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; //printf(" before assign_sf_ss js= %d\n",js); A.next_plate=js; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile //printf("before assign_unused js= %d \n",js); assign_unused(js,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate); for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate printf(" before pass = %d at %d tiles\n",i,update_intervals[i]); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) { int j = A.suborder[jj]; //printf(" next plate is %d \n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF assign_unused(j,M,P,pp,F,A); //A.next_plate++; } //update target information for interval i //A.next_plate=F.pass_intervals[i]; for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) { //int j = A.suborder[A.next_plate]; //int js=A.suborder[jj]; // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } //if(A.next_plate<F.Nplate){ redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //} if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF for(int js=0;js<F.NUsedplate;++js){ printf("\n js = %d\n",js); for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[js][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } printf(" %d %d ",count_SS,count_SF); } printf("\n"); } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: SbrCam.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <math.h> #include "SbrCam.hh" #include "SbrRenW.hh" #include "SbrRen.hh" static float xform[4][4] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; // typecast if neccessary void vlSbrCamera::Render(vlRenderer *ren) { this->Render((vlSbrRenderer *)ren); } // set the appropriate attributes in Sbr for this camera // void vlSbrCamera::Render(vlSbrRenderer *ren) { float aspect[3]; float *viewport; float *background; int width,height; long clr; int left,right,bottom,top; long xmax,ymax,zmax; float twist; int stereo; int fd; camera_arg cam; int *size; int *screen_size; vlSbrRenderWindow *rw; fd = ren->GetFd(); // find out if we should stereo render stereo = ren->GetStereoRender(); // set up the view specification cam.field_of_view = this->ViewAngle; cam.front = this->ClippingRange[0] - this->Distance; cam.back = this->ClippingRange[1] - this->Distance; cam.camx = this->Position[0]; cam.camy = this->Position[1]; cam.camz = this->Position[2]; cam.refx = this->FocalPoint[0]; cam.refy = this->FocalPoint[1]; cam.refz = this->FocalPoint[2]; cam.upx = this->ViewUp[0]; cam.upy = this->ViewUp[1]; cam.upz = this->ViewUp[2]; cam.projection = CAM_PERSPECTIVE; // set this renderer's viewport, must turn off z-buffering when changing // viewport hidden_surface(fd, FALSE, FALSE); vlDebugMacro(<< " SB_hidden_surface: False False\n"); viewport = ren->GetViewport(); // get the background color background = ren->GetBackground(); // get size info rw = (vlSbrRenderWindow*)(ren->GetRenderWindow()); size = rw->GetSize(); screen_size = rw->GetScreenSize(); // make sure the aspect is up to date if (size[0] > size[1]) { aspect[0] = size[0]/size[1]; aspect[1] = 1.0; } else { aspect[0] = 1.0; aspect[1] = size[1]/size[0]; } ren->SetAspect(aspect); vdc_extent(fd,0.0,-screen_size[1]/size[1]+1.0,0.0, screen_size[0]/size[0],1.0,1.0); // set viewport to clear entire window view_port(fd, viewport[0], viewport[1], viewport[2], viewport[3]); hidden_surface(fd, TRUE, FALSE); vlDebugMacro(<< " SB_hidden_surface: True False\n"); // Set the background color and clear the display. // Since clear control was set to clear z buffer, this is done here // also. background_color(fd, background[0], background[1], background[2]); // clear the view surface so the new background color takes effect if (ren->GetErase()) { clear_view_surface(fd); vlDebugMacro(<< " SB_clear_view_surface\n"); } hidden_surface(fd, FALSE, FALSE); vlDebugMacro(<< " SB_hidden_surface: False False\n"); vdc_extent(fd,0.0,-screen_size[1]/size[1]+1.0,0.0, screen_size[0]/size[0],1.0,1.0); view_port(fd, viewport[0], viewport[1], viewport[2], viewport[3]); hidden_surface(fd, TRUE, FALSE); vlDebugMacro(<< " SB_hidden_surface: True False\n"); // install the camera view_camera(fd, &cam); // now handle the anisotropy xform[0][0] = 1.0/aspect[0]; xform[1][1] = 1.0/aspect[1]; xform[3][1] = (1.0 - xform[1][1])/2.0; xform[3][0] = (1.0 - xform[0][0])/2.0; view_matrix3d(fd, xform, POST_CONCAT_VW); // if we have a stereo renderer, draw other eye next time if (stereo) { if (this->LeftEye) this->LeftEye = 0; else this->LeftEye = 1; } } <commit_msg>fixed a tricky camera problem<commit_after>/*========================================================================= Program: Visualization Library Module: SbrCam.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <math.h> #include "SbrCam.hh" #include "SbrRenW.hh" #include "SbrRen.hh" static float xform[4][4] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; // typecast if neccessary void vlSbrCamera::Render(vlRenderer *ren) { this->Render((vlSbrRenderer *)ren); } // set the appropriate attributes in Sbr for this camera // void vlSbrCamera::Render(vlSbrRenderer *ren) { float aspect[3]; float vaspect[2]; float *viewport; float *background; int width,height; long clr; int left,right,bottom,top; long xmax,ymax,zmax; float twist; int stereo; int fd; camera_arg cam; int *size; int *screen_size; vlSbrRenderWindow *rw; float trans[2]; float old; fd = ren->GetFd(); // find out if we should stereo render stereo = ren->GetStereoRender(); // set up the view specification cam.field_of_view = this->ViewAngle; cam.front = this->ClippingRange[0] - this->Distance; cam.back = this->ClippingRange[1] - this->Distance; cam.camx = this->Position[0]; cam.camy = this->Position[1]; cam.camz = - this->Position[2]; cam.refx = this->FocalPoint[0]; cam.refy = this->FocalPoint[1]; cam.refz = - this->FocalPoint[2]; cam.upx = this->ViewUp[0]; cam.upy = this->ViewUp[1]; cam.upz = - this->ViewUp[2]; cam.projection = CAM_PERSPECTIVE; // set this renderer's viewport, must turn off z-buffering when changing // viewport hidden_surface(fd, FALSE, FALSE); vlDebugMacro(<< " SB_hidden_surface: False False\n"); viewport = ren->GetViewport(); // get the background color background = ren->GetBackground(); // get size info rw = (vlSbrRenderWindow*)(ren->GetRenderWindow()); size = rw->GetSize(); screen_size = rw->GetScreenSize(); // make sure the aspect is up to date if (size[0] > size[1]) { aspect[0] = size[0]/(float)size[1]; aspect[1] = 1.0; } else { aspect[0] = 1.0; aspect[1] = size[1]/(float)size[0]; } ren->SetAspect(aspect); vdc_extent(fd,0.0,-screen_size[1]/(float)size[1]+1.0,0.0, screen_size[0]/(float)size[0],1.0,1.0); vlDebugMacro(<< " screen_size " << screen_size[0] << " " << screen_size[1] << endl); vlDebugMacro(<< " size " << size[0] << " " << size[1] << endl); vlDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1] << " " << viewport[2] << " " << viewport[3] << endl); // set viewport to clear entire window view_port(fd, viewport[0], viewport[1], viewport[2], viewport[3]); hidden_surface(fd, TRUE, FALSE); vlDebugMacro(<< " SB_hidden_surface: True False\n"); // Set the background color and clear the display. // Since clear control was set to clear z buffer, this is done here // also. background_color(fd, background[0], background[1], background[2]); // clear the view surface so the new background color takes effect if (ren->GetErase()) { clear_view_surface(fd); vlDebugMacro(<< " SB_clear_view_surface\n"); } hidden_surface(fd, FALSE, FALSE); vlDebugMacro(<< " SB_hidden_surface: False False\n"); vdc_extent(fd,0.0,-screen_size[1]/(float)size[1]+1.0,0.0, screen_size[0]/(float)size[0],1.0,1.0); view_port(fd, viewport[0], viewport[1], viewport[2], viewport[3]); hidden_surface(fd, TRUE, FALSE); vlDebugMacro(<< " SB_hidden_surface: True False\n"); // install the camera view_camera(fd, &cam); // calculate the viewport aspect // we basically compensate for starbases attempt to compensate for // non square windows. vaspect[0] = viewport[2] - viewport[0]; vaspect[1] = viewport[3] - viewport[1]; if ((vaspect[0] >= vaspect[1])&&(aspect[0] <= aspect[1])) { old = vaspect[0]; vaspect[0] = aspect[0]*vaspect[1]/old; vaspect[1] = aspect[1]*vaspect[1]/old; } else { if ((vaspect[0] <= vaspect[1])&&(aspect[0] >= aspect[1])) { old = vaspect[1]; vaspect[1] = aspect[1]*vaspect[0]/old; vaspect[0] = aspect[0]*vaspect[0]/old; } } // another try trans[0] = (viewport[2] + viewport[0])*(1.0 - 1.0/vaspect[0])/2.0; trans[1] = (viewport[3] + viewport[1])*(1.0 - 1.0/vaspect[1])/2.0; // now handle the anisotropy xform[0][0] = 1.0/vaspect[0]; xform[1][1] = 1.0/vaspect[1]; xform[3][1] = trans[1]; xform[3][0] = trans[0]; view_matrix3d(fd, xform, POST_CONCAT_VW); // if we have a stereo renderer, draw other eye next time if (stereo) { if (this->LeftEye) this->LeftEye = 0; else this->LeftEye = 1; } } <|endoftext|>
<commit_before>/* * State.cpp * Contains all the information of a state * */ #ifndef PINBALL_BOT_STATE #define PINBALL_BOT_STATE #include "Ball.cpp" class State{ private: //Ball* ball; //Pointer to the ball inside the simulation public: /** * Gets the expected reward based on a lookup table and the model of the environment * @param s State The State of which the reward is calculated * @return double The expected reward */ double getReward(State s){ return 0.0; } /** * Calculates the expected value the given state will in the next turn and in the future => convergence * @param s State The State of which the value is calculated * @return double The expected value */ double getValue(State s){ return 0.0; } }; #endif /* PINBALL_BOT_STATE */ <commit_msg>Updated State class<commit_after>/* * State.cpp * Contains all the information of a state * */ #ifndef PINBALL_BOT_STATE #define PINBALL_BOT_STATE #include "Ball.cpp" #include <iostream> #include <vector> #include <random> class State{ private: //Ball* ball; //Pointer to the ball inside the simulation /** * Generates a seed. * @return void */ static unsigned int seed(){ return (unsigned int) rand();//FIXME not a good solution, but works for now. } /** * Generates a pseudo-random float * @param min float The minimum possible number to generate [included] * @param max float The maximum possible number to generate [included] * @return float The pseudo random number */ static float randomFloatInRange(float min, float max){ std::default_random_engine generator(seed()); std::uniform_real_distribution<float> distribution = std::uniform_real_distribution<float>(min, max); return distribution(generator); } /** * Generates a pseudo-random int * @param min int The minimum possible number to generate [included] * @param max int The maximum possible number to generate [included] * @return int The pseudo random number */ static int randomIntInRange(int min, int max){ std::default_random_engine generator(seed()); std::uniform_int_distribution<int> distribution = std::uniform_int_distribution<int>(min, max); return distribution(generator); } public: //inits a state State(){ } /** * Gets the expected reward based on a lookup table and the model of the environment * @param s State The State of which the reward is calculated * @return double The expected reward */ float getReward(){ return 0.0f; } /** * Calculates the expected value the given state will in the next turn and in the future => convergence * @param s State The State of which the value is calculated * @return double The expected value */ float getValue(){ return 0.0f; } /** * Returns one state inside of a vector based on a epsilon greedy algorithm * @param states std::vector<State> A vector containing all the possible states * @param epsilon float Range: [0-1]: The percentage of time, which this function should pick a random state * @return State The picked state */ static State epsilonGreedy(std::vector<State> states, float epsilon){ if(epsilon < randomFloatInRange(0.0f, 1.0f)){ //pick a greedy state return greedy(states); }else{ //pick a random state return random(states); } } /** * Picks the state with the highest value * @param states std::vector<State> A vector containing all the possible states * @return State The picked state */ static State greedy(std::vector<State> states){ int maxValue = 0; float tmpValue; std::vector<State> maxStates; for(int i=1;i<states.size();i++){ tmpValue = states[i].getValue(); if(tmpValue > maxValue){ maxValue = tmpValue; maxStates.clear(); maxStates.push_back(states[i]); }else if(tmpValue == maxValue){ maxStates.push_back(states[i]); } } if(maxStates.size() == 1){ return maxStates[0]; }else{ return random(maxStates); } } /** * Picks a random state * @param states std::vector<State> A vector containing all the possible states * @return State The picked state */ static State random(std::vector<State> states){ return states[randomIntInRange(0, states.size()-1)]; } }; #endif /* PINBALL_BOT_STATE */ <|endoftext|>
<commit_before>/* cbr * Timer.cpp * * Copyright (c) 2009, Ewen Cheslack-Postava * 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 cbr 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 "Timer.hpp" namespace CBR { Timer::Timer() { } Timer::~Timer() { } static boost::posix_time::ptime gEpoch(boost::posix_time::time_from_string(std::string("2009-03-12 23:59:59.000"))); Time Timer::getSpecifiedDate(const std::string&dat) { boost::posix_time::time_duration since_epoch=boost::posix_time::time_from_string(dat)-gEpoch; return Time(since_epoch.total_microseconds()); } void Timer::start() { mStart = boost::posix_time::microsec_clock::local_time(); } Time Timer::getTimerStarted() const{ boost::posix_time::time_duration since_start =mStart-gEpoch; return Time(since_start.total_microseconds()); } Duration Timer::sOffset=Duration::seconds(0.0f); void Timer::setSystemClockOffset(const Duration&skew) { sOffset=skew; } Time Timer::now() { boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time()-gEpoch; return Time( since_start.total_microseconds() )+sOffset; } Duration Timer::elapsed() const{ boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time() - mStart; return Duration( since_start.total_microseconds() )+sOffset; } } // namespace CBR <commit_msg>Timers elapsed time shouldn't be affected by the offset to the central clock.<commit_after>/* cbr * Timer.cpp * * Copyright (c) 2009, Ewen Cheslack-Postava * 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 cbr 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 "Timer.hpp" namespace CBR { Timer::Timer() { } Timer::~Timer() { } static boost::posix_time::ptime gEpoch(boost::posix_time::time_from_string(std::string("2009-03-12 23:59:59.000"))); Time Timer::getSpecifiedDate(const std::string&dat) { boost::posix_time::time_duration since_epoch=boost::posix_time::time_from_string(dat)-gEpoch; return Time(since_epoch.total_microseconds()); } void Timer::start() { mStart = boost::posix_time::microsec_clock::local_time(); } Time Timer::getTimerStarted() const{ boost::posix_time::time_duration since_start =mStart-gEpoch; return Time(since_start.total_microseconds()); } Duration Timer::sOffset=Duration::seconds(0.0f); void Timer::setSystemClockOffset(const Duration&skew) { sOffset=skew; } Time Timer::now() { boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time()-gEpoch; return Time( since_start.total_microseconds() )+sOffset; } Duration Timer::elapsed() const{ boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time() - mStart; return Duration( since_start.total_microseconds() ); } } // namespace CBR <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 3/14/2020, 9:19:13 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- vector<string> concat(string A, string B) { int N{static_cast<int>(A.size())}; vector<string> ans; for (auto i = 0; i <= N; ++i) { bool ok{true}; for (auto j = i; j < N; ++j) { if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?') { continue; } else { ok = false; break; } } if (ok) { stringstream SS; for (auto j = 0; j < i; ++j) { SS << A[j]; } for (auto j = i; j < N; ++j) { if (A[j] == '?') { SS << B[j - i]; } else { SS << A[j]; } } for (auto j = N - i; j < static_cast<int>(B.size()); ++j) { SS << B[j]; } ans.push_back(SS.str()); } } return ans; } int concat(vector<string> const &V, string B) { int ans{10000}; for (auto const &A : V) { int N{static_cast<int>(A.size())}; for (auto i = 0; i <= N; ++i) { bool ok{true}; for (auto j = i; j < N; ++j) { if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?') { continue; } else { ok = false; break; } } if (ok) { ch_max(ans, N + static_cast<int>(B.size()) - i); break; } } } return ans; } int solve(vector<string> W) { return concat(concat(W[0], W[1]), W[2]); } int main() { vector<string> V(3); for (auto i = 0; i < 3; ++i) { cin >> V[i]; } vector<int> O{0, 1, 2}; int ans{10000}; do { vector<string> W(3); for (auto i = 0; i < 3; ++i) { W[i] = V[O[i]]; } ch_min(ans, solve(W)); } while (next_permutation(O.begin(), O.end())); cout << ans << endl; } <commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 3/14/2020, 9:19:13 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- vector<string> concat(string A, string B) { int N{static_cast<int>(A.size())}; vector<string> ans; for (auto i = 0; i <= N; ++i) { bool ok{true}; for (auto j = i; j < N; ++j) { if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?') { continue; } else { ok = false; break; } } if (ok) { stringstream SS; for (auto j = 0; j < i; ++j) { SS << A[j]; } for (auto j = i; j < N; ++j) { if (A[j] == '?') { SS << B[j - i]; } else { SS << A[j]; } } for (auto j = N - i; j < static_cast<int>(B.size()); ++j) { SS << B[j]; } ans.push_back(SS.str()); } } return ans; } int concat(vector<string> const &V, string B) { int ans{10000}; for (auto const &A : V) { int N{static_cast<int>(A.size())}; for (auto i = 0; i <= N; ++i) { bool ok{true}; for (auto j = i; j < N; ++j) { if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?') { continue; } else { ok = false; break; } } if (ok) { ch_min(ans, N + static_cast<int>(B.size()) - i); break; } } } return ans; } int solve(vector<string> W) { return concat(concat(W[0], W[1]), W[2]); } int main() { vector<string> V(3); for (auto i = 0; i < 3; ++i) { cin >> V[i]; } vector<int> O{0, 1, 2}; int ans{10000}; do { vector<string> W(3); for (auto i = 0; i < 3; ++i) { W[i] = V[O[i]]; } ch_min(ans, solve(W)); } while (next_permutation(O.begin(), O.end())); cout << ans << endl; } <|endoftext|>
<commit_before>/* * UiMgr.cpp * * Created on: Apr 12, 2017 * Author: chad * Editied: Hadi Rumjahn, Gage Thomas, Jake Shepard */ #include <UiMgr.h> #include <engine.h> template <typename StorageType> bool contains(const StorageType item, const StorageType data[], const int len) { //Iterates through all values in the array for(int index = 0; index < len; index++){ //If the data was found, return true if(data[index] == item) { return true; } } //Item was not found return false; } Token getMyToken(std::ifstream &fin, const char delims[], const int len){ char character; bool leadWS = true, foundDelim = false;; Token result; //Initialize the token result result.data = ""; //Loops until the file is empty or a deliminator is reached (after leading //whitespace is eliminated) while(!fin.eof() && !foundDelim) { fin.get(character); //If the character was not whitespace, set the flag if(leadWS && !(character == ' ' || character == '\t' || character == '\n')) { leadWS = false; } //If not processing leading whitespace if(!leadWS){ //If a deliminator is reached after leading whitespace, end loop if(contains(character, delims, len)) { result.endDelim = character; foundDelim = true; } else { result.data += character;//Else, append the current char } } } //If a deliminator was not found, return an empty string if(!foundDelim) { Token failResult; failResult.data = ""; return failResult; } else {//Else return the token return result; } } UiMgr::UiMgr(Engine* eng): Mgr(eng){ // Initialize the OverlaySystem (changed for Ogre 1.9) mOverlaySystem = new Ogre::OverlaySystem(); engine->gfxMgr->ogreSceneManager->addRenderQueueListener(mOverlaySystem); mTrayMgr = 0; timeMonitor = 0; gameOverLabel = 0; highScores = 0; nameLabel = 0; yourName = 0;//Not a rating for the movie, that movie was good creditsButton = 0; credits = 0; playerSurvived = false; //Ogre::WindowEventUtilities::addWindowEventListener(engine->gfxMgr->ogreRenderWindow, this); } UiMgr::~UiMgr(){ // before gfxMgr destructor } void UiMgr::init(){ //init sdktrays mInputContext.mKeyboard = engine->inputMgr->keyboard; mInputContext.mMouse = engine->inputMgr->mouse; mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", engine->gfxMgr->ogreRenderWindow, mInputContext, this); //mTrayMgr->hideCursor(); } void UiMgr::stop() { } void UiMgr::loadLevel(){ mTrayMgr->hideCursor(); timeMonitor = mTrayMgr->createLabel(OgreBites::TL_TOP, "Timer", timeAsString(engine->gameMgr->gameplayTime)); //timeMonitor->getOverlayElement()->setMaterialName("TransparentBackground.png");//Not working for some reason } void UiMgr::loadGameOver(bool survived) { playerSurvived = survived; int width = engine->gfxMgr->ogreRenderWindow->getWidth(); int height = engine->gfxMgr->ogreRenderWindow->getHeight(); if(!survived) { gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Died!"); } else { gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Survived!"); } gameOverLabel->getOverlayElement()->setPosition((width / 2) - (gameOverLabel->getOverlayElement()->getWidth() / 2), 300); yourName = mTrayMgr->createLabel(OgreBites::TL_NONE, "YourName", "Your name:"); yourName->getOverlayElement()->setPosition((width / 2) - (yourName->getOverlayElement()->getWidth() / 2), 340); mTrayMgr->showCursor(); nameLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "NameLabel", ""); nameLabel->getOverlayElement()->setPosition((width / 2) - (nameLabel->getOverlayElement()->getWidth() / 2), 380); //Handle the credits creditsButton = mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "CreditsButton", "Credits"); credits = mTrayMgr->createTextBox(OgreBites::TL_NONE, "Credits", "Credits:", 300, 600); credits->getOverlayElement()->setPosition(width - 300, height - 50 - 600); credits->setText(getCredits()); //Do not center it, it alligns the left of the string with the center credits->hide(); //For some reason if this call is made now, the text gets cleared credits->setText(getCredits()); } std::string UiMgr::getCredits() { return "Cries\n\nPresented by Code R3d\n\nGage Thomas\n\nJake Shepherd\n\nHadi Rumjahn\n"; } void UiMgr::loadHighScores(bool survived) { std::string names[10]; float scores[10]; std::ifstream fin; std::string filename; int width = engine->gfxMgr->ogreRenderWindow->getWidth(); bool playerUsed = false; if(survived) { filename = "HighScoresSurvived.txt"; } else { filename = "HighScoresDied.txt"; } fin.open(filename); //Enter all the information into the two arrays for(int index = 0; index < 10; index++) { Token nextToken = getMyToken(fin, COLON, 1);//gets the name Token scoreToken = getMyToken(fin, WHITESPACE, 3); float nextScore = stof(scoreToken.data); //If the player beat the score if((survived && engine->gameMgr->gameplayTime < nextScore && !playerUsed) || (!survived && engine->gameMgr->gameplayTime > nextScore && !playerUsed)) { playerUsed = true; if(nameLabel->getCaption().length() == 0) { names[index] = "Kira"; } else { names[index] = nameLabel->getCaption(); } scores[index] = engine->gameMgr->gameplayTime; index++; } //Now handle the current score, so long as the player's score didn't push //index past 10 if(index < 10) { names[index] = nextToken.data; scores[index] = nextScore; } } fin.close(); std::ofstream fout; fout.open(filename); //Now write the new high scores to file for(int index = 0; index < 10; index++) { fout << names[index] << ": " << scores[index] << std::endl; } fout << std::endl; fout.close(); //Now display the high scores yourName->hide(); nameLabel->hide(); std::string scoresText = ""; for(int index = 0; index < 10; index++) { scoresText += std::to_string(index + 1) + ". " + names[index] + ": " + timeAsString(scores[index]) + "\n\n"; } highScores = mTrayMgr->createTextBox(OgreBites::TL_NONE, "HighScores", "High Scores:", 300, 600); highScores->getOverlayElement()->setPosition((width / 2) - (highScores->getOverlayElement()->getWidth() / 2), 340); highScores->setText(scoresText); } void UiMgr::tick(float dt){ mTrayMgr->refreshCursor(); //Update the time since last event if in splash screen if(engine->theState == STATE::SPLASH) { engine->timeSinceLastEvent += dt; //If 3 seconds have passed, go into gameplay if(engine->timeSinceLastEvent >= 3) { engine->theState = STATE::MAIN_MENU; engine->gfxMgr->loadMenu(); loadMenu();//Creates the button } } else if(engine->theState == STATE::GAMEPLAY) { timeMonitor->setCaption(timeAsString(engine->gameMgr->gameplayTime)); } else if(engine->theState == STATE::GAMEOVER) { } } void UiMgr::windowResized(Ogre::RenderWindow* rw){ unsigned int width, height, depth; int left, top; rw->getMetrics(width, height, depth, left, top); const OIS::MouseState &ms = engine->inputMgr->mouse->getMouseState(); ms.width = width; ms.height = height; } void UiMgr::windowClosed(Ogre::RenderWindow* rw){ } bool UiMgr::keyPressed(const OIS::KeyEvent &arg) { std::cout << "Key Pressed: " << arg.key << std::endl; return true; } bool UiMgr::keyReleased(const OIS::KeyEvent &arg){ return true; } bool UiMgr::mouseMoved(const OIS::MouseEvent &arg){ if (mTrayMgr->injectMouseMove(arg)) return true; /* normal mouse processing here... */ return true; } bool UiMgr::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id) { std::cout << "mouse clicked" << std::endl; if (mTrayMgr->injectMouseDown(arg, id)) return true; /* normal mouse processing here... */ return true; } bool UiMgr::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id){ if (mTrayMgr->injectMouseUp(arg, id)) return true; /* normal mouse processing here... */ return true; } void UiMgr::buttonHit(OgreBites::Button *b){ if(b->getName()=="NewGame") { std::cout <<"New Game pressed" << std::endl; engine->theState = STATE::GAMEPLAY; engine->loadLevel(); mTrayMgr->destroyWidget(b); } else if(b->getName() == "CreditsButton") { if(credits->isVisible()) { credits->hide(); } else { credits->setText(getCredits()); credits->show(); } } } void UiMgr::itemSelected(OgreBites::SelectMenu *m){ if(m->getName()=="MyMenu") { std::cout <<"Menu!" << std::endl; } } void UiMgr::loadMenu() { mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "NewGame", "New Game"); // LOAD MAIN MENU SOUND engine->soundMgr->load_song("Menu", "resources/Cries - Theme.ogg"); //load_sound(std::string soundName, std::string filePath); //play_sound(std::string soundName); engine->soundMgr->play_song2D("Menu", true); } std::string UiMgr::timeAsString(float time) { std::string result = ""; int resultTime = (int) time; int seconds = resultTime % 60; int minutes = resultTime / 60; if(minutes < 10) { result += "0"; } result += std::to_string(minutes) + ":"; if(seconds < 10) { result += "0"; } result += std::to_string(seconds); return result; } <commit_msg>Fixing merge conflicts<commit_after>/* * UiMgr.cpp * * Created on: Apr 12, 2017 * Author: chad * Editied: Hadi Rumjahn, Gage Thomas, Jake Shepard */ #include <UiMgr.h> #include <engine.h> template <typename StorageType> bool contains(const StorageType item, const StorageType data[], const int len) { //Iterates through all values in the array for(int index = 0; index < len; index++){ //If the data was found, return true if(data[index] == item) { return true; } } //Item was not found return false; } Token getMyToken(std::ifstream &fin, const char delims[], const int len){ char character; bool leadWS = true, foundDelim = false;; Token result; //Initialize the token result result.data = ""; //Loops until the file is empty or a deliminator is reached (after leading //whitespace is eliminated) while(!fin.eof() && !foundDelim) { fin.get(character); //If the character was not whitespace, set the flag if(leadWS && !(character == ' ' || character == '\t' || character == '\n')) { leadWS = false; } //If not processing leading whitespace if(!leadWS){ //If a deliminator is reached after leading whitespace, end loop if(contains(character, delims, len)) { result.endDelim = character; foundDelim = true; } else { result.data += character;//Else, append the current char } } } //If a deliminator was not found, return an empty string if(!foundDelim) { Token failResult; failResult.data = ""; return failResult; } else {//Else return the token return result; } } UiMgr::UiMgr(Engine* eng): Mgr(eng){ // Initialize the OverlaySystem (changed for Ogre 1.9) mOverlaySystem = new Ogre::OverlaySystem(); engine->gfxMgr->ogreSceneManager->addRenderQueueListener(mOverlaySystem); mTrayMgr = 0; timeMonitor = 0; gameOverLabel = 0; highScores = 0; nameLabel = 0; yourName = 0;//Not a rating for the movie, that movie was good creditsButton = 0; credits = 0; playerSurvived = false; //Ogre::WindowEventUtilities::addWindowEventListener(engine->gfxMgr->ogreRenderWindow, this); } UiMgr::~UiMgr(){ // before gfxMgr destructor } void UiMgr::init(){ //init sdktrays mInputContext.mKeyboard = engine->inputMgr->keyboard; mInputContext.mMouse = engine->inputMgr->mouse; mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", engine->gfxMgr->ogreRenderWindow, mInputContext, this); //mTrayMgr->hideCursor(); } void UiMgr::stop() { } void UiMgr::loadLevel(){ mTrayMgr->hideCursor(); timeMonitor = mTrayMgr->createLabel(OgreBites::TL_TOP, "Timer", timeAsString(engine->gameMgr->gameplayTime)); //timeMonitor->getOverlayElement()->setMaterialName("TransparentBackground.png");//Not working for some reason } void UiMgr::loadGameOver(bool survived) { playerSurvived = survived; int width = engine->gfxMgr->ogreRenderWindow->getWidth(); int height = engine->gfxMgr->ogreRenderWindow->getHeight(); if(!survived) { gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Died!"); } else { gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Survived!"); } gameOverLabel->getOverlayElement()->setPosition((width / 2) - (gameOverLabel->getOverlayElement()->getWidth() / 2), 300); yourName = mTrayMgr->createLabel(OgreBites::TL_NONE, "YourName", "Your name:"); yourName->getOverlayElement()->setPosition((width / 2) - (yourName->getOverlayElement()->getWidth() / 2), 340); mTrayMgr->showCursor(); nameLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "NameLabel", ""); nameLabel->getOverlayElement()->setPosition((width / 2) - (nameLabel->getOverlayElement()->getWidth() / 2), 380); //Handle the credits creditsButton = mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "CreditsButton", "Credits"); credits = mTrayMgr->createTextBox(OgreBites::TL_NONE, "Credits", "Credits:", 300, 600); credits->getOverlayElement()->setPosition(width - 300, height - 50 - 600); credits->setText(getCredits()); //Do not center it, it alligns the left of the string with the center credits->hide(); //For some reason if this call is made now, the text gets cleared credits->setText(getCredits()); } std::string UiMgr::getCredits() { return "Cries\n\nPresented by Code R3d\n\nGage Thomas\n\nJake Shepherd\n\nHadi Rumjahn\n"; } void UiMgr::loadHighScores(bool survived) { std::string names[10]; float scores[10]; std::ifstream fin; std::string filename; int width = engine->gfxMgr->ogreRenderWindow->getWidth(); bool playerUsed = false; if(survived) { filename = "HighScoresSurvived.txt"; } else { filename = "HighScoresDied.txt"; } fin.open(filename); //Enter all the information into the two arrays for(int index = 0; index < 10; index++) { Token nextToken = getMyToken(fin, COLON, 1);//gets the name Token scoreToken = getMyToken(fin, WHITESPACE, 3); float nextScore = stof(scoreToken.data); //If the player beat the score if((survived && engine->gameMgr->gameplayTime < nextScore && !playerUsed) || (!survived && engine->gameMgr->gameplayTime > nextScore && !playerUsed)) { playerUsed = true; if(nameLabel->getCaption().length() == 0) { names[index] = "Kira"; } else { names[index] = nameLabel->getCaption(); } scores[index] = engine->gameMgr->gameplayTime; index++; } //Now handle the current score, so long as the player's score didn't push //index past 10 if(index < 10) { names[index] = nextToken.data; scores[index] = nextScore; } } fin.close(); std::ofstream fout; fout.open(filename); //Now write the new high scores to file for(int index = 0; index < 10; index++) { fout << names[index] << ": " << scores[index] << std::endl; } fout << std::endl; fout.close(); //Now display the high scores yourName->hide(); nameLabel->hide(); std::string scoresText = ""; for(int index = 0; index < 10; index++) { scoresText += std::to_string(index + 1) + ". " + names[index] + ": " + timeAsString(scores[index]) + "\n\n"; } highScores = mTrayMgr->createTextBox(OgreBites::TL_NONE, "HighScores", "High Scores:", 300, 600); highScores->getOverlayElement()->setPosition((width / 2) - (highScores->getOverlayElement()->getWidth() / 2), 340); highScores->setText(scoresText); } void UiMgr::tick(float dt){ mTrayMgr->refreshCursor(); //Update the time since last event if in splash screen if(engine->theState == STATE::SPLASH) { engine->timeSinceLastEvent += dt; //If 3 seconds have passed, go into gameplay if(engine->timeSinceLastEvent >= 3) { engine->theState = STATE::MAIN_MENU; engine->gfxMgr->loadMenu(); loadMenu();//Creates the button } } else if(engine->theState == STATE::GAMEPLAY) { timeMonitor->setCaption(timeAsString(engine->gameMgr->gameplayTime)); } else if(engine->theState == STATE::GAMEOVER) { } } void UiMgr::windowResized(Ogre::RenderWindow* rw){ unsigned int width, height, depth; int left, top; rw->getMetrics(width, height, depth, left, top); const OIS::MouseState &ms = engine->inputMgr->mouse->getMouseState(); ms.width = width; ms.height = height; } void UiMgr::windowClosed(Ogre::RenderWindow* rw){ } bool UiMgr::keyPressed(const OIS::KeyEvent &arg) { std::cout << "Key Pressed: " << arg.key << std::endl; return true; } bool UiMgr::keyReleased(const OIS::KeyEvent &arg){ return true; } bool UiMgr::mouseMoved(const OIS::MouseEvent &arg){ if (mTrayMgr->injectMouseMove(arg)) return true; /* normal mouse processing here... */ return true; } bool UiMgr::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id) { std::cout << "mouse clicked" << std::endl; if (mTrayMgr->injectMouseDown(arg, id)) return true; /* normal mouse processing here... */ return true; } bool UiMgr::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id){ if (mTrayMgr->injectMouseUp(arg, id)) return true; /* normal mouse processing here... */ return true; } void UiMgr::buttonHit(OgreBites::Button *b){ if(b->getName()=="NewGame") { std::cout <<"New Game pressed" << std::endl; engine->theState = STATE::GAMEPLAY; engine->loadLevel(); mTrayMgr->destroyWidget(b); } else if(b->getName() == "CreditsButton") { if(credits->isVisible()) { credits->hide(); } else { credits->setText(getCredits()); credits->show(); } } } void UiMgr::itemSelected(OgreBites::SelectMenu *m){ if(m->getName()=="MyMenu") { std::cout <<"Menu!" << std::endl; } } void UiMgr::loadMenu() { mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "NewGame", "New Game"); // LOAD MAIN MENU SOUND //engine->soundMgr->load_song("Menu", "resources/Cries - Theme.ogg"); engine->soundMgr->load_song("Menu", "resources/theme.wav"); //load_sound(std::string soundName, std::string filePath); //play_sound(std::string soundName); engine->soundMgr->play_song2D("Menu", true); } std::string UiMgr::timeAsString(float time) { std::string result = ""; int resultTime = (int) time; int seconds = resultTime % 60; int minutes = resultTime / 60; if(minutes < 10) { result += "0"; } result += std::to_string(minutes) + ":"; if(seconds < 10) { result += "0"; } result += std::to_string(seconds); return result; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: numfmtlb.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:53:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWNUMFMTLB_HXX #define _SWNUMFMTLB_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _ZFORLIST_HXX //autogen #include <svtools/zforlist.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwView; class SW_DLLPUBLIC NumFormatListBox : public ListBox { short nCurrFormatType; USHORT nStdEntry; BOOL bOneArea; ULONG nDefFormat; SwView* pVw; SvNumberFormatter* pOwnFormatter; LanguageType eCurLanguage; BOOL bShowLanguageControl; //determine whether the language control has //to be shown in the number format dialog BOOL bUseAutomaticLanguage;//determine whether language is automatically assigned SW_DLLPRIVATE DECL_LINK( SelectHdl, ListBox * ); SW_DLLPRIVATE double GetDefValue(const short nFormatType) const; SW_DLLPRIVATE void Init(short nFormatType, BOOL bUsrFmts); SW_DLLPRIVATE SwView* GetView(); public: NumFormatListBox( Window* pWin, const ResId& rResId, short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0, BOOL bUsrFmts = TRUE ); NumFormatListBox( Window* pWin, SwView* pView, const ResId& rResId, short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0, BOOL bUsrFmts = TRUE ); ~NumFormatListBox(); void Clear(); inline void SetOneArea(BOOL bOnlyOne = TRUE) { bOneArea = bOnlyOne; } void SetFormatType(const short nFormatType); inline short GetFormatType() const { return nCurrFormatType; } void SetDefFormat(const ULONG nDefFmt); ULONG GetFormat() const; inline LanguageType GetCurLanguage() const { return eCurLanguage;} void SetLanguage(LanguageType eSet) { eCurLanguage = eSet;} void SetAutomaticLanguage(BOOL bSet){bUseAutomaticLanguage = bSet;} BOOL IsAutomaticLanguage()const {return bUseAutomaticLanguage;} void SetShowLanguageControl(BOOL bSet){bShowLanguageControl = bSet;} }; #endif <commit_msg>INTEGRATION: CWS swwarnings (1.6.710); FILE MERGED 2007/03/26 12:09:08 tl 1.6.710.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: numfmtlb.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:05:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWNUMFMTLB_HXX #define _SWNUMFMTLB_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _ZFORLIST_HXX //autogen #include <svtools/zforlist.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwView; class SW_DLLPUBLIC NumFormatListBox : public ListBox { short nCurrFormatType; USHORT nStdEntry; BOOL bOneArea; ULONG nDefFormat; SwView* pVw; SvNumberFormatter* pOwnFormatter; LanguageType eCurLanguage; BOOL bShowLanguageControl; //determine whether the language control has //to be shown in the number format dialog BOOL bUseAutomaticLanguage;//determine whether language is automatically assigned SW_DLLPRIVATE DECL_LINK( SelectHdl, ListBox * ); SW_DLLPRIVATE double GetDefValue(const short nFormatType) const; SW_DLLPRIVATE void Init(short nFormatType, BOOL bUsrFmts); SW_DLLPRIVATE SwView* GetView(); public: NumFormatListBox( Window* pWin, const ResId& rResId, short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0, BOOL bUsrFmts = TRUE ); NumFormatListBox( Window* pWin, SwView* pView, const ResId& rResId, short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0, BOOL bUsrFmts = TRUE ); ~NumFormatListBox(); void Clear(); inline void SetOneArea(BOOL bOnlyOne = TRUE) { bOneArea = bOnlyOne; } void SetFormatType(const short nFormatType); inline short GetFormatType() const { return nCurrFormatType; } void SetDefFormat(const ULONG nDefFmt); ULONG GetFormat() const; inline LanguageType GetCurLanguage() const { return eCurLanguage;} void SetLanguage(LanguageType eSet) { eCurLanguage = eSet;} void SetAutomaticLanguage(BOOL bSet){bUseAutomaticLanguage = bSet;} BOOL IsAutomaticLanguage()const {return bUseAutomaticLanguage;} void SetShowLanguageControl(BOOL bSet){bShowLanguageControl = bSet;} }; #endif <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "ActiveMQConnectionSupport.h" #include <activemq/exceptions/ActiveMQException.h> #include <activemq/core/ActiveMQConstants.h> #include <decaf/lang/Boolean.h> #include <decaf/lang/Integer.h> #include <decaf/lang/exceptions/IllegalArgumentException.h> using namespace std; using namespace activemq; using namespace activemq::core; using namespace activemq::exceptions; using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// ActiveMQConnectionSupport::ActiveMQConnectionSupport( const Pointer<transport::Transport>& transport, const Pointer<decaf::util::Properties>& properties ) { if( transport == NULL ) { throw decaf::lang::exceptions::IllegalArgumentException( __FILE__, __LINE__, "ActiveMQConnectionSupport::ActiveMQConnectionSupport - " "Required Parameter 'transport' was NULL."); } this->properties = properties; this->transport = transport; // Check the connection options this->setAlwaysSyncSend( Boolean::parseBoolean( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_ALWAYSSYNCSEND ), "false" ) ) ); this->setUseAsyncSend( Boolean::parseBoolean( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_USEASYNCSEND ), "false" ) ) ); this->setProducerWindowSize( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_PRODUCERWINDOWSIZE ), "0" ) ) ); this->setSendTimeout( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_SENDTIMEOUT ), "0" ) ) ); this->setCloseTimeout( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_CLOSETIMEOUT ), "15000" ) ) ); this->setClientId( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_CLIENTID ), "" ) ); this->setUsername( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_USERNAME ), "" ) ); this->setPassword( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_PASSWORD ), "" ) ); } //////////////////////////////////////////////////////////////////////////////// ActiveMQConnectionSupport::~ActiveMQConnectionSupport() { try{ this->shutdownTransport(); } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void ActiveMQConnectionSupport::startupTransport() throw( decaf::lang::Exception ) { try { if( this->transport.get() == NULL ) { throw decaf::lang::exceptions::IllegalArgumentException( __FILE__, __LINE__, "ActiveMQConnectionSupport::startupTransport - " "Required Object 'transport' was NULL."); } this->transport->start(); } AMQ_CATCH_RETHROW( decaf::lang::Exception ) AMQ_CATCHALL_THROW( decaf::lang::Exception ) } //////////////////////////////////////////////////////////////////////////////// void ActiveMQConnectionSupport::shutdownTransport() throw( decaf::lang::Exception ) { bool hasException = false; exceptions::ActiveMQException e; try { if( transport.get() != NULL ){ try{ transport->close(); }catch( exceptions::ActiveMQException& ex ){ if( !hasException ){ hasException = true; ex.setMark(__FILE__, __LINE__ ); e = ex; } } try{ transport.reset( NULL ); }catch( exceptions::ActiveMQException& ex ){ if( !hasException ){ hasException = true; ex.setMark(__FILE__, __LINE__ ); e = ex; } } } // If we encountered an exception - throw the first one we encountered. // This will preserve the stack trace for logging purposes. if( hasException ){ throw e; } } AMQ_CATCH_RETHROW( decaf::lang::Exception ) AMQ_CATCHALL_THROW( decaf::lang::Exception ) } <commit_msg>fix for: http://issues.apache.org/activemq/browse/AMQCPP-290<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "ActiveMQConnectionSupport.h" #include <activemq/exceptions/ActiveMQException.h> #include <activemq/core/ActiveMQConstants.h> #include <decaf/lang/Boolean.h> #include <decaf/lang/Integer.h> #include <decaf/lang/exceptions/IllegalArgumentException.h> using namespace std; using namespace activemq; using namespace activemq::core; using namespace activemq::exceptions; using namespace decaf; using namespace decaf::lang; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// ActiveMQConnectionSupport::ActiveMQConnectionSupport( const Pointer<transport::Transport>& transport, const Pointer<decaf::util::Properties>& properties ) { if( transport == NULL ) { throw decaf::lang::exceptions::IllegalArgumentException( __FILE__, __LINE__, "ActiveMQConnectionSupport::ActiveMQConnectionSupport - " "Required Parameter 'transport' was NULL."); } this->properties = properties; this->transport = transport; // Check the connection options this->setAlwaysSyncSend( Boolean::parseBoolean( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_ALWAYSSYNCSEND ), "false" ) ) ); this->setUseAsyncSend( Boolean::parseBoolean( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_USEASYNCSEND ), "false" ) ) ); this->setProducerWindowSize( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_PRODUCERWINDOWSIZE ), "0" ) ) ); this->setSendTimeout( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_SENDTIMEOUT ), "0" ) ) ); this->setCloseTimeout( decaf::lang::Integer::parseInt( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::CONNECTION_CLOSETIMEOUT ), "15000" ) ) ); this->setClientId( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_CLIENTID ), "" ) ); this->setUsername( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_USERNAME ), "" ) ); this->setPassword( properties->getProperty( core::ActiveMQConstants::toString( core::ActiveMQConstants::PARAM_PASSWORD ), "" ) ); } //////////////////////////////////////////////////////////////////////////////// ActiveMQConnectionSupport::~ActiveMQConnectionSupport() { try{ this->shutdownTransport(); } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void ActiveMQConnectionSupport::startupTransport() throw( decaf::lang::Exception ) { try { if( this->transport.get() == NULL ) { throw decaf::lang::exceptions::IllegalArgumentException( __FILE__, __LINE__, "ActiveMQConnectionSupport::startupTransport - " "Required Object 'transport' was NULL."); } this->transport->start(); } AMQ_CATCH_RETHROW( decaf::lang::Exception ) AMQ_CATCHALL_THROW( decaf::lang::Exception ) } //////////////////////////////////////////////////////////////////////////////// void ActiveMQConnectionSupport::shutdownTransport() throw( decaf::lang::Exception ) { bool hasException = false; exceptions::ActiveMQException e; try { if( transport.get() != NULL ){ // Clear the listener, we don't care about errors at this point. transport->setTransportListener( NULL ); try{ transport->close(); }catch( exceptions::ActiveMQException& ex ){ if( !hasException ){ hasException = true; ex.setMark(__FILE__, __LINE__ ); e = ex; } } try{ transport.reset( NULL ); }catch( exceptions::ActiveMQException& ex ){ if( !hasException ){ hasException = true; ex.setMark(__FILE__, __LINE__ ); e = ex; } } } // If we encountered an exception - throw the first one we encountered. // This will preserve the stack trace for logging purposes. if( hasException ){ throw e; } } AMQ_CATCH_RETHROW( decaf::lang::Exception ) AMQ_CATCHALL_THROW( decaf::lang::Exception ) } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: delete.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:39:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif #ifndef _SWCRSR_HXX #include <swcrsr.hxx> #endif #include <svx/lrspitem.hxx> // #i23725# // --> OD 2006-07-10 #134369# #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DRAWBASE_HXX #include <drawbase.hxx> #endif // <-- inline void SwWrtShell::OpenMark() { StartAllAction(); ResetCursorStack(); KillPams(); SetMark(); } inline void SwWrtShell::CloseMark( BOOL bOkFlag ) { if( bOkFlag ) UpdateAttr(); else SwapPam(); ClearMark(); EndAllAction(); } // #i23725# BOOL SwWrtShell::TryRemoveIndent() { BOOL bResult = FALSE; SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE); GetAttr(aAttrSet); SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE); short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst(); if (aOldFirstLineOfst > 0) { aItem.SetTxtFirstLineOfst(0); bResult = TRUE; } else if (aOldFirstLineOfst < 0) { aItem.SetTxtFirstLineOfst(0); aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst); bResult = TRUE; } else if (aItem.GetLeft() != 0) { aItem.SetLeft(0); bResult = TRUE; } if (bResult) { aAttrSet.Put(aItem); SetAttr(aAttrSet); } return bResult; } /*------------------------------------------------------------------------ Beschreibung: Zeile loeschen ------------------------------------------------------------------------*/ long SwWrtShell::DelLine() { ACT_KONTEXT(this); ResetCursorStack(); // alten Cursor merken Push(); ClearMark(); SwCrsrShell::LeftMargin(); SetMark(); SwCrsrShell::RightMargin(); //Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden? // if(!IsEndOfPara()) // SwCrsrShell::Right(); long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfLine() { OpenMark(); SwCrsrShell::LeftMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfLine() { OpenMark(); SwCrsrShell::RightMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return 1; } long SwWrtShell::DelLeft() { // wenns denn ein Fly ist, wech damit int nSelType = GetSelectionType(); const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW; if( nCmp & nSelType ) { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); nSelType = GetSelectionType(); if ( nCmp & nSelType ) { EnterSelFrmMode(); GotoNextFly(); } return 1L; } // wenn eine Selektion existiert, diese loeschen. if ( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); return 1L; } // JP 29.06.95: nie eine davor stehende Tabelle loeschen. BOOL bSwap = FALSE; const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl(); if( SwCrsrShell::IsSttPara()) { /* If the cursor is at the beginning of a paragraph, try to step backwards. On failure we are done. */ if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) ) return 0; /* If the cursor entered or left a table (or both) we are done. No step back. */ if( SwCrsrShell::IsCrsrInTbl() != pWasInTblNd ) return 0; OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CHARS); SwCrsrShell::SwapPam(); bSwap = TRUE; } else { OpenMark(); SwCrsrShell::Left(1,CRSR_SKIP_CHARS); } long nRet = Delete(); if( !nRet && bSwap ) SwCrsrShell::SwapPam(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelRight(BOOL bDelFrm) { // werden verodert, wenn Tabellenselektion vorliegt; // wird hier auf SEL_TBL umgesetzt. long nRet = 0; int nSelection = GetSelectionType(); if(nSelection & SwWrtShell::SEL_TBL_CELLS) nSelection = SwWrtShell::SEL_TBL; if(nSelection & SwWrtShell::SEL_TXT) nSelection = SwWrtShell::SEL_TXT; const SwTableNode * pWasInTblNd = NULL; switch( nSelection & ~(SEL_BEZ) ) { case SEL_TXT: case SEL_TBL: case SEL_NUM: // wenn eine Selektion existiert, diese loeschen. if( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); nRet = 1L; break; } pWasInTblNd = IsCrsrInTbl(); if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() && SwCrsrShell::IsEndPara() ) { // save cursor SwCrsrShell::Push(); bool bDelFull = false; if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) ) { const SwTableNode * pCurrTblNd = IsCrsrInTbl(); bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd; } // restore cursor SwCrsrShell::Pop( FALSE ); if( bDelFull ) { DelFullPara(); UpdateAttr(); break; } } { /* #108049# Save the startnode of the current cell */ const SwStartNode * pSNdOld; pSNdOld = GetSwCrsr()->GetNode()-> FindTableBoxStartNode(); if ( SwCrsrShell::IsEndPara() ) { // --> FME 2005-01-28 #i41424# Introduced a couple of // Push()-Pop() pairs here. The reason for this is thet a // Right()-Left() combination does not make sure, that // the cursor will be in its initial state, because there // may be a numbering in front of the next paragraph. SwCrsrShell::Push(); // <-- if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) ) { if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl())) { /* #108049# Save the startnode of the current cell. May be different to pSNdOld as we have moved. */ const SwStartNode * pSNdNew = GetSwCrsr() ->GetNode()->FindTableBoxStartNode(); /* #108049# Only move instead of deleting if we have moved to a different cell */ if (pSNdOld != pSNdNew) { SwCrsrShell::Pop( TRUE ); break; } } } // restore cursor SwCrsrShell::Pop( FALSE ); } } OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CELLS); nRet = Delete(); CloseMark( 0 != nRet ); break; case SEL_FRM: case SEL_GRF: case SEL_OLE: case SEL_DRW: case SEL_DRW_TXT: case SEL_DRW_FORM: { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); // --> OD 2006-07-06 #134369# ASSERT( !IsFrmSelected(), "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" ) // <-- // --> OD 2006-07-10 #134369# // leave draw mode, if necessary. { if (GetView().GetDrawFuncPtr()) { GetView().GetDrawFuncPtr()->Deactivate(); GetView().SetDrawFuncPtr(NULL); } if ( GetView().IsDrawMode() ) { GetView().LeaveDrawCreate(); } } // <-- } // --> OD 2006-07-07 #134369# // <IsFrmSelected()> can't be true - see above. // <-- { nSelection = GetSelectionType(); if ( SEL_FRM & nSelection || SEL_GRF & nSelection || SEL_OLE & nSelection || SEL_DRW & nSelection ) { EnterSelFrmMode(); GotoNextFly(); } } nRet = 1; break; } return nRet; } long SwWrtShell::DelToEndOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaEnd)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaStart)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } /* * alle Loeschoperationen sollten mit Find statt mit * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten * -- das ist wohl nicht gewuenscht. */ long SwWrtShell::DelToStartOfSentence() { if(IsStartOfDoc()) return 0; OpenMark(); long nRet = _BwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfSentence() { if(IsEndOfDoc()) return 0; OpenMark(); long nRet = _FwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelNxtWord() { if(IsEndOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if(IsEndWrd() && !IsSttWrd()) _NxtWrd(); if(IsSttWrd() || IsEndPara()) _NxtWrd(); else _EndWrd(); long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } long SwWrtShell::DelPrvWord() { if(IsStartOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if( !IsSttWrd() || !_PrvWrd() ) { if( IsEndWrd() ) { if( _PrvWrd() ) { // skip over all-1 spaces short n = -1; while( ' ' == GetChar( FALSE, n )) --n; if( ++n ) ExtendSelection( FALSE, -n ); } } else if( IsSttPara()) _PrvWrd(); else _SttWrd(); } long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } <commit_msg>INTEGRATION: CWS swnewtable (1.15.14); FILE MERGED 2007/02/15 13:36:48 fme 1.15.14.1: #i4032# New table concept - Don't delete content if backspace forces a cell change<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: delete.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2007-02-28 15:56:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif #ifndef _SWCRSR_HXX #include <swcrsr.hxx> #endif #include <svx/lrspitem.hxx> // #i23725# // --> OD 2006-07-10 #134369# #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DRAWBASE_HXX #include <drawbase.hxx> #endif // <-- inline void SwWrtShell::OpenMark() { StartAllAction(); ResetCursorStack(); KillPams(); SetMark(); } inline void SwWrtShell::CloseMark( BOOL bOkFlag ) { if( bOkFlag ) UpdateAttr(); else SwapPam(); ClearMark(); EndAllAction(); } // #i23725# BOOL SwWrtShell::TryRemoveIndent() { BOOL bResult = FALSE; SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE); GetAttr(aAttrSet); SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE); short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst(); if (aOldFirstLineOfst > 0) { aItem.SetTxtFirstLineOfst(0); bResult = TRUE; } else if (aOldFirstLineOfst < 0) { aItem.SetTxtFirstLineOfst(0); aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst); bResult = TRUE; } else if (aItem.GetLeft() != 0) { aItem.SetLeft(0); bResult = TRUE; } if (bResult) { aAttrSet.Put(aItem); SetAttr(aAttrSet); } return bResult; } /*------------------------------------------------------------------------ Beschreibung: Zeile loeschen ------------------------------------------------------------------------*/ long SwWrtShell::DelLine() { ACT_KONTEXT(this); ResetCursorStack(); // alten Cursor merken Push(); ClearMark(); SwCrsrShell::LeftMargin(); SetMark(); SwCrsrShell::RightMargin(); //Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden? // if(!IsEndOfPara()) // SwCrsrShell::Right(); long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfLine() { OpenMark(); SwCrsrShell::LeftMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfLine() { OpenMark(); SwCrsrShell::RightMargin(); long nRet = Delete(); CloseMark( 0 != nRet ); return 1; } long SwWrtShell::DelLeft() { // wenns denn ein Fly ist, wech damit int nSelType = GetSelectionType(); const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW; if( nCmp & nSelType ) { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); nSelType = GetSelectionType(); if ( nCmp & nSelType ) { EnterSelFrmMode(); GotoNextFly(); } return 1L; } // wenn eine Selektion existiert, diese loeschen. if ( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); return 1L; } // JP 29.06.95: nie eine davor stehende Tabelle loeschen. BOOL bSwap = FALSE; const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl(); if( SwCrsrShell::IsSttPara()) { // --> FME 2007-02-15 #i4032# Don't actually call a 'delete' if we // changed the table cell, compare DelRight(). const SwStartNode * pSNdOld = pWasInTblNd ? GetSwCrsr()->GetNode()->FindTableBoxStartNode() : 0; // <-- /* If the cursor is at the beginning of a paragraph, try to step backwards. On failure we are done. */ if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) ) return 0; /* If the cursor entered or left a table (or both) we are done. No step back. */ const SwTableNode* pIsInTblNd = SwCrsrShell::IsCrsrInTbl(); if( pIsInTblNd != pWasInTblNd ) return 0; const SwStartNode* pSNdNew = pIsInTblNd ? GetSwCrsr()->GetNode()->FindTableBoxStartNode() : 0; // --> FME 2007-02-15 #i4032# Don't actually call a 'delete' if we // changed the table cell, compare DelRight(). if ( pSNdOld != pSNdNew ) return 0; // <-- OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CHARS); SwCrsrShell::SwapPam(); bSwap = TRUE; } else { OpenMark(); SwCrsrShell::Left(1,CRSR_SKIP_CHARS); } long nRet = Delete(); if( !nRet && bSwap ) SwCrsrShell::SwapPam(); CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelRight(BOOL bDelFrm) { // werden verodert, wenn Tabellenselektion vorliegt; // wird hier auf SEL_TBL umgesetzt. long nRet = 0; int nSelection = GetSelectionType(); if(nSelection & SwWrtShell::SEL_TBL_CELLS) nSelection = SwWrtShell::SEL_TBL; if(nSelection & SwWrtShell::SEL_TXT) nSelection = SwWrtShell::SEL_TXT; const SwTableNode * pWasInTblNd = NULL; switch( nSelection & ~(SEL_BEZ) ) { case SEL_TXT: case SEL_TBL: case SEL_NUM: // wenn eine Selektion existiert, diese loeschen. if( IsSelection() ) { //OS: wieder einmal Basic: ACT_KONTEXT muss vor //EnterStdMode verlassen werden! { ACT_KONTEXT(this); ResetCursorStack(); Delete(); UpdateAttr(); } EnterStdMode(); nRet = 1L; break; } pWasInTblNd = IsCrsrInTbl(); if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() && SwCrsrShell::IsEndPara() ) { // save cursor SwCrsrShell::Push(); bool bDelFull = false; if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) ) { const SwTableNode * pCurrTblNd = IsCrsrInTbl(); bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd; } // restore cursor SwCrsrShell::Pop( FALSE ); if( bDelFull ) { DelFullPara(); UpdateAttr(); break; } } { /* #108049# Save the startnode of the current cell */ const SwStartNode * pSNdOld; pSNdOld = GetSwCrsr()->GetNode()-> FindTableBoxStartNode(); if ( SwCrsrShell::IsEndPara() ) { // --> FME 2005-01-28 #i41424# Introduced a couple of // Push()-Pop() pairs here. The reason for this is that a // Right()-Left() combination does not make sure, that // the cursor will be in its initial state, because there // may be a numbering in front of the next paragraph. SwCrsrShell::Push(); // <-- if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) ) { if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl())) { /* #108049# Save the startnode of the current cell. May be different to pSNdOld as we have moved. */ const SwStartNode * pSNdNew = GetSwCrsr() ->GetNode()->FindTableBoxStartNode(); /* #108049# Only move instead of deleting if we have moved to a different cell */ if (pSNdOld != pSNdNew) { SwCrsrShell::Pop( TRUE ); break; } } } // restore cursor SwCrsrShell::Pop( FALSE ); } } OpenMark(); SwCrsrShell::Right(1,CRSR_SKIP_CELLS); nRet = Delete(); CloseMark( 0 != nRet ); break; case SEL_FRM: case SEL_GRF: case SEL_OLE: case SEL_DRW: case SEL_DRW_TXT: case SEL_DRW_FORM: { /* #108205# Remember object's position. */ Point aTmpPt = GetObjRect().TopLeft(); DelSelectedObj(); /* #108205# Set cursor to remembered position. */ SetCrsr(&aTmpPt); LeaveSelFrmMode(); UnSelectFrm(); // --> OD 2006-07-06 #134369# ASSERT( !IsFrmSelected(), "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" ) // <-- // --> OD 2006-07-10 #134369# // leave draw mode, if necessary. { if (GetView().GetDrawFuncPtr()) { GetView().GetDrawFuncPtr()->Deactivate(); GetView().SetDrawFuncPtr(NULL); } if ( GetView().IsDrawMode() ) { GetView().LeaveDrawCreate(); } } // <-- } // --> OD 2006-07-07 #134369# // <IsFrmSelected()> can't be true - see above. // <-- { nSelection = GetSelectionType(); if ( SEL_FRM & nSelection || SEL_GRF & nSelection || SEL_OLE & nSelection || SEL_DRW & nSelection ) { EnterSelFrmMode(); GotoNextFly(); } } nRet = 1; break; } return nRet; } long SwWrtShell::DelToEndOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaEnd)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } long SwWrtShell::DelToStartOfPara() { ACT_KONTEXT(this); ResetCursorStack(); Push(); SetMark(); if( !MovePara(fnParaCurr,fnParaStart)) { Pop(FALSE); return 0; } long nRet = Delete(); Pop(FALSE); if( nRet ) UpdateAttr(); return nRet; } /* * alle Loeschoperationen sollten mit Find statt mit * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten * -- das ist wohl nicht gewuenscht. */ long SwWrtShell::DelToStartOfSentence() { if(IsStartOfDoc()) return 0; OpenMark(); long nRet = _BwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelToEndOfSentence() { if(IsEndOfDoc()) return 0; OpenMark(); long nRet = _FwdSentence() ? Delete() : 0; CloseMark( 0 != nRet ); return nRet; } long SwWrtShell::DelNxtWord() { if(IsEndOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if(IsEndWrd() && !IsSttWrd()) _NxtWrd(); if(IsSttWrd() || IsEndPara()) _NxtWrd(); else _EndWrd(); long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } long SwWrtShell::DelPrvWord() { if(IsStartOfDoc()) return 0; ACT_KONTEXT(this); ResetCursorStack(); EnterStdMode(); SetMark(); if( !IsSttWrd() || !_PrvWrd() ) { if( IsEndWrd() ) { if( _PrvWrd() ) { // skip over all-1 spaces short n = -1; while( ' ' == GetChar( FALSE, n )) --n; if( ++n ) ExtendSelection( FALSE, -n ); } } else if( IsSttPara()) _PrvWrd(); else _SttWrd(); } long nRet = Delete(); if( nRet ) UpdateAttr(); else SwapPam(); ClearMark(); return nRet; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh4.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 11:41:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ FASTBOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ FASTBOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } FASTBOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } FASTBOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.6.476); FILE MERGED 2006/09/01 17:53:37 kaib 1.6.476.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh4.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:40:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ FASTBOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ FASTBOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } FASTBOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } FASTBOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Xinyu Zhu <xyzhu1120@gmail.com> | | shiguangqi <shiguangqi2008@gmail.com> | | Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole_coroutine_scheduler.h" #include "coroutine_c_api.h" #include <queue> using namespace std; using swoole::coroutine::System; using swoole::coroutine::Socket; using swoole::Coroutine; using swoole::PHPCoroutine; struct scheduler_task_t { zend_long count; zend_fcall_info fci; zend_fcall_info_cache fci_cache; }; struct scheduler_t { queue<scheduler_task_t*> *list; bool started; zend_object std; }; static zend_class_entry *swoole_coroutine_scheduler_ce; static zend_object_handlers swoole_coroutine_scheduler_handlers; ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_void, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_add, 0, 0, 1) ZEND_ARG_CALLABLE_INFO(0, func, 0) ZEND_ARG_VARIADIC_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_parallel, 0, 0, 1) ZEND_ARG_INFO(0, n) ZEND_ARG_CALLABLE_INFO(0, func, 0) ZEND_ARG_VARIADIC_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_set, 0, 0, 1) ZEND_ARG_ARRAY_INFO(0, settings, 0) ZEND_END_ARG_INFO() static PHP_METHOD(swoole_coroutine_scheduler, add); static PHP_METHOD(swoole_coroutine_scheduler, parallel); static PHP_METHOD(swoole_coroutine_scheduler, start); static sw_inline scheduler_t* scheduler_get_object(zend_object *obj) { return (scheduler_t *) ((char *) obj - swoole_coroutine_scheduler_handlers.offset); } static zend_object *scheduler_create_object(zend_class_entry *ce) { scheduler_t *s = (scheduler_t *) ecalloc(1, sizeof(scheduler_t) + zend_object_properties_size(ce)); zend_object_std_init(&s->std, ce); object_properties_init(&s->std, ce); s->std.handlers = &swoole_coroutine_scheduler_handlers; return &s->std; } static void scheduler_free_object(zend_object *object) { scheduler_t *s = scheduler_get_object(object); if (s->list) { while(!s->list->empty()) { scheduler_task_t *task = s->list->front(); s->list->pop(); sw_zend_fci_cache_discard(&task->fci_cache); sw_zend_fci_params_discard(&task->fci); efree(task); } delete s->list; s->list = nullptr; } zend_object_std_dtor(&s->std); } static const zend_function_entry swoole_coroutine_scheduler_methods[] = { PHP_ME(swoole_coroutine_scheduler, add, arginfo_swoole_coroutine_scheduler_add, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, parallel, arginfo_swoole_coroutine_scheduler_parallel, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, set, arginfo_swoole_coroutine_scheduler_set, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, start, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_FE_END }; void swoole_coroutine_scheduler_init(int module_number) { SW_INIT_CLASS_ENTRY(swoole_coroutine_scheduler, "Swoole\\Coroutine\\Scheduler", NULL, "Co\\Scheduler", swoole_coroutine_scheduler_methods); SW_SET_CLASS_SERIALIZABLE(swoole_coroutine_scheduler, zend_class_serialize_deny, zend_class_unserialize_deny); SW_SET_CLASS_CLONEABLE(swoole_coroutine_scheduler, sw_zend_class_clone_deny); SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_coroutine_scheduler, sw_zend_class_unset_property_deny); SW_SET_CLASS_CREATE_WITH_ITS_OWN_HANDLERS(swoole_coroutine_scheduler); SW_SET_CLASS_CUSTOM_OBJECT(swoole_coroutine_scheduler, scheduler_create_object, scheduler_free_object, scheduler_t, std); swoole_coroutine_scheduler_ce->ce_flags |= ZEND_ACC_FINAL; zend_declare_property_null(swoole_coroutine_scheduler_ce, ZEND_STRL("_list"), ZEND_ACC_PRIVATE); } PHP_METHOD(swoole_coroutine_scheduler, set) { zval *zset = NULL; HashTable *vht = NULL; zval *ztmp; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ARRAY(zset) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); vht = Z_ARRVAL_P(zset); if (php_swoole_array_get_value(vht, "max_coroutine", ztmp)) { zend_long max_num = zval_get_long(ztmp); PHPCoroutine::set_max_num(max_num <= 0 ? SW_DEFAULT_MAX_CORO_NUM : max_num); } /** * Runtime: hook php function */ if (php_swoole_array_get_value(vht, "hook_flags", ztmp)) { PHPCoroutine::enable_hook(zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "c_stack_size", ztmp) || php_swoole_array_get_value(vht, "stack_size", ztmp)) { Coroutine::set_stack_size(zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "socket_connect_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_connect_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_read_timeout = Socket::default_write_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_read_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_read_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_write_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_write_timeout = t; } } if (php_swoole_array_get_value(vht, "log_level", ztmp)) { zend_long level = zval_get_long(ztmp); SwooleG.log_level = (uint32_t) (level < 0 ? UINT32_MAX : level); } if (php_swoole_array_get_value(vht, "trace_flags", ztmp)) { SwooleG.trace_flags = (uint32_t) SW_MAX(0, zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "dns_cache_expire", ztmp)) { System::set_dns_cache_expire((time_t) zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "dns_cache_capacity", ztmp)) { System::set_dns_cache_capacity((size_t) zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "display_errors", ztmp)) { SWOOLE_G(display_errors) = zval_is_true(ztmp); } } static void scheduler_add_task(scheduler_t *s, scheduler_task_t *task) { if (!s->list) { s->list = new queue<scheduler_task_t*>; } sw_zend_fci_cache_persist(&task->fci_cache); sw_zend_fci_params_persist(&task->fci); s->list->push(task); } static PHP_METHOD(swoole_coroutine_scheduler, add) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is running, unable to execute %s->add", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } scheduler_task_t *task = (scheduler_task_t *) ecalloc(1, sizeof(scheduler_task_t)); ZEND_PARSE_PARAMETERS_START(1, -1) Z_PARAM_FUNC(task->fci, task->fci_cache) Z_PARAM_VARIADIC('*', task->fci.params, task->fci.param_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); task->count = 1; scheduler_add_task(s, task); } static PHP_METHOD(swoole_coroutine_scheduler, parallel) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is running, unable to execute %s->parallel", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } scheduler_task_t *task = (scheduler_task_t *) ecalloc(1, sizeof(scheduler_task_t)); zend_long count; ZEND_PARSE_PARAMETERS_START(2, -1) Z_PARAM_LONG(count) Z_PARAM_FUNC(task->fci, task->fci_cache) Z_PARAM_VARIADIC('*', task->fci.params, task->fci.param_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); task->count = count; scheduler_add_task(s, task); } static PHP_METHOD(swoole_coroutine_scheduler, start) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (SwooleG.main_reactor) { zend_throw_exception_ex(swoole_exception_ce, -2, "eventLoop has already been created. unable to start %s", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is started, unable to execute %s->start", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } php_swoole_reactor_init(); s->started = true; while (!s->list->empty()) { scheduler_task_t *task = s->list->front(); s->list->pop(); for (zend_long i = 0; i < task->count; i++) { PHPCoroutine::create(&task->fci_cache, task->fci.param_count, task->fci.params); } sw_zend_fci_cache_discard(&task->fci_cache); sw_zend_fci_params_discard(&task->fci); efree(task); } php_swoole_event_wait(); delete s->list; s->list = nullptr; s->started = false; } <commit_msg>RETURN_TRUE<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Xinyu Zhu <xyzhu1120@gmail.com> | | shiguangqi <shiguangqi2008@gmail.com> | | Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole_coroutine_scheduler.h" #include "coroutine_c_api.h" #include <queue> using namespace std; using swoole::coroutine::System; using swoole::coroutine::Socket; using swoole::Coroutine; using swoole::PHPCoroutine; struct scheduler_task_t { zend_long count; zend_fcall_info fci; zend_fcall_info_cache fci_cache; }; struct scheduler_t { queue<scheduler_task_t*> *list; bool started; zend_object std; }; static zend_class_entry *swoole_coroutine_scheduler_ce; static zend_object_handlers swoole_coroutine_scheduler_handlers; ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_void, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_add, 0, 0, 1) ZEND_ARG_CALLABLE_INFO(0, func, 0) ZEND_ARG_VARIADIC_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_parallel, 0, 0, 1) ZEND_ARG_INFO(0, n) ZEND_ARG_CALLABLE_INFO(0, func, 0) ZEND_ARG_VARIADIC_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_coroutine_scheduler_set, 0, 0, 1) ZEND_ARG_ARRAY_INFO(0, settings, 0) ZEND_END_ARG_INFO() static PHP_METHOD(swoole_coroutine_scheduler, add); static PHP_METHOD(swoole_coroutine_scheduler, parallel); static PHP_METHOD(swoole_coroutine_scheduler, start); static sw_inline scheduler_t* scheduler_get_object(zend_object *obj) { return (scheduler_t *) ((char *) obj - swoole_coroutine_scheduler_handlers.offset); } static zend_object *scheduler_create_object(zend_class_entry *ce) { scheduler_t *s = (scheduler_t *) ecalloc(1, sizeof(scheduler_t) + zend_object_properties_size(ce)); zend_object_std_init(&s->std, ce); object_properties_init(&s->std, ce); s->std.handlers = &swoole_coroutine_scheduler_handlers; return &s->std; } static void scheduler_free_object(zend_object *object) { scheduler_t *s = scheduler_get_object(object); if (s->list) { while(!s->list->empty()) { scheduler_task_t *task = s->list->front(); s->list->pop(); sw_zend_fci_cache_discard(&task->fci_cache); sw_zend_fci_params_discard(&task->fci); efree(task); } delete s->list; s->list = nullptr; } zend_object_std_dtor(&s->std); } static const zend_function_entry swoole_coroutine_scheduler_methods[] = { PHP_ME(swoole_coroutine_scheduler, add, arginfo_swoole_coroutine_scheduler_add, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, parallel, arginfo_swoole_coroutine_scheduler_parallel, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, set, arginfo_swoole_coroutine_scheduler_set, ZEND_ACC_PUBLIC) PHP_ME(swoole_coroutine_scheduler, start, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_FE_END }; void swoole_coroutine_scheduler_init(int module_number) { SW_INIT_CLASS_ENTRY(swoole_coroutine_scheduler, "Swoole\\Coroutine\\Scheduler", NULL, "Co\\Scheduler", swoole_coroutine_scheduler_methods); SW_SET_CLASS_SERIALIZABLE(swoole_coroutine_scheduler, zend_class_serialize_deny, zend_class_unserialize_deny); SW_SET_CLASS_CLONEABLE(swoole_coroutine_scheduler, sw_zend_class_clone_deny); SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_coroutine_scheduler, sw_zend_class_unset_property_deny); SW_SET_CLASS_CREATE_WITH_ITS_OWN_HANDLERS(swoole_coroutine_scheduler); SW_SET_CLASS_CUSTOM_OBJECT(swoole_coroutine_scheduler, scheduler_create_object, scheduler_free_object, scheduler_t, std); swoole_coroutine_scheduler_ce->ce_flags |= ZEND_ACC_FINAL; zend_declare_property_null(swoole_coroutine_scheduler_ce, ZEND_STRL("_list"), ZEND_ACC_PRIVATE); } PHP_METHOD(swoole_coroutine_scheduler, set) { zval *zset = NULL; HashTable *vht = NULL; zval *ztmp; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ARRAY(zset) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); vht = Z_ARRVAL_P(zset); if (php_swoole_array_get_value(vht, "max_coroutine", ztmp)) { zend_long max_num = zval_get_long(ztmp); PHPCoroutine::set_max_num(max_num <= 0 ? SW_DEFAULT_MAX_CORO_NUM : max_num); } /** * Runtime: hook php function */ if (php_swoole_array_get_value(vht, "hook_flags", ztmp)) { PHPCoroutine::enable_hook(zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "c_stack_size", ztmp) || php_swoole_array_get_value(vht, "stack_size", ztmp)) { Coroutine::set_stack_size(zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "socket_connect_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_connect_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_read_timeout = Socket::default_write_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_read_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_read_timeout = t; } } if (php_swoole_array_get_value(vht, "socket_write_timeout", ztmp)) { double t = zval_get_double(ztmp); if (t != 0) { Socket::default_write_timeout = t; } } if (php_swoole_array_get_value(vht, "log_level", ztmp)) { zend_long level = zval_get_long(ztmp); SwooleG.log_level = (uint32_t) (level < 0 ? UINT32_MAX : level); } if (php_swoole_array_get_value(vht, "trace_flags", ztmp)) { SwooleG.trace_flags = (uint32_t) SW_MAX(0, zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "dns_cache_expire", ztmp)) { System::set_dns_cache_expire((time_t) zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "dns_cache_capacity", ztmp)) { System::set_dns_cache_capacity((size_t) zval_get_long(ztmp)); } if (php_swoole_array_get_value(vht, "display_errors", ztmp)) { SWOOLE_G(display_errors) = zval_is_true(ztmp); } } static void scheduler_add_task(scheduler_t *s, scheduler_task_t *task) { if (!s->list) { s->list = new queue<scheduler_task_t*>; } sw_zend_fci_cache_persist(&task->fci_cache); sw_zend_fci_params_persist(&task->fci); s->list->push(task); } static PHP_METHOD(swoole_coroutine_scheduler, add) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is running, unable to execute %s->add", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } scheduler_task_t *task = (scheduler_task_t *) ecalloc(1, sizeof(scheduler_task_t)); ZEND_PARSE_PARAMETERS_START(1, -1) Z_PARAM_FUNC(task->fci, task->fci_cache) Z_PARAM_VARIADIC('*', task->fci.params, task->fci.param_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); task->count = 1; scheduler_add_task(s, task); } static PHP_METHOD(swoole_coroutine_scheduler, parallel) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is running, unable to execute %s->parallel", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } scheduler_task_t *task = (scheduler_task_t *) ecalloc(1, sizeof(scheduler_task_t)); zend_long count; ZEND_PARSE_PARAMETERS_START(2, -1) Z_PARAM_LONG(count) Z_PARAM_FUNC(task->fci, task->fci_cache) Z_PARAM_VARIADIC('*', task->fci.params, task->fci.param_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); task->count = count; scheduler_add_task(s, task); } static PHP_METHOD(swoole_coroutine_scheduler, start) { scheduler_t *s = scheduler_get_object(Z_OBJ_P(getThis())); if (SwooleG.main_reactor) { php_swoole_fatal_error(E_WARNING, "eventLoop has already been created. unable to start %s", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } if (s->started) { php_swoole_fatal_error(E_WARNING, "scheduler is started, unable to execute %s->start", SW_Z_OBJCE_NAME_VAL_P(getThis())); RETURN_FALSE; } php_swoole_reactor_init(); s->started = true; while (!s->list->empty()) { scheduler_task_t *task = s->list->front(); s->list->pop(); for (zend_long i = 0; i < task->count; i++) { PHPCoroutine::create(&task->fci_cache, task->fci.param_count, task->fci.params); } sw_zend_fci_cache_discard(&task->fci_cache); sw_zend_fci_params_discard(&task->fci); efree(task); } php_swoole_event_wait(); delete s->list; s->list = nullptr; s->started = false; RETURN_TRUE; } <|endoftext|>
<commit_before>/** * @file amici.cpp * @brief core routines for integration */ #include "amici/amici.h" #include "amici/steadystateproblem.h" #include "amici/backwardproblem.h" #include "amici/forwardproblem.h" #include "amici/misc.h" #include <cvodes/cvodes.h> //return codes #include <sundials/sundials_types.h> //realtype #include <cassert> #include <cstdarg> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <type_traits> // ensure definitions are in sync static_assert(amici::AMICI_SUCCESS == CV_SUCCESS, "AMICI_SUCCESS != CV_SUCCESS"); static_assert(amici::AMICI_DATA_RETURN == CV_TSTOP_RETURN, "AMICI_DATA_RETURN != CV_TSTOP_RETURN"); static_assert(amici::AMICI_ROOT_RETURN == CV_ROOT_RETURN, "AMICI_ROOT_RETURN != CV_ROOT_RETURN"); static_assert(amici::AMICI_ILL_INPUT == CV_ILL_INPUT, "AMICI_ILL_INPUT != CV_ILL_INPUT"); static_assert(amici::AMICI_NORMAL == CV_NORMAL, "AMICI_NORMAL != CV_NORMAL"); static_assert(amici::AMICI_ONE_STEP == CV_ONE_STEP, "AMICI_ONE_STEP != CV_ONE_STEP"); static_assert(std::is_same<amici::realtype, realtype>::value, "Definition of realtype does not match"); namespace amici { /** AMICI default application context, kept around for convenience for using * amici::runAmiciSimulation or instantiating Solver and Model without special * needs. */ AmiciApplication defaultContext = AmiciApplication(); std::unique_ptr<ReturnData> runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { return defaultContext.runAmiciSimulation(solver, edata, model, rethrow); } void printErrMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Error] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } void printWarnMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Warning] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } std::vector<std::unique_ptr<ReturnData>> runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, const bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { #if defined(_OPENMP) return defaultContext.runAmiciSimulations( solver, edatas, model, failfast, num_threads); #else return defaultContext.runAmiciSimulations(solver, edatas, model, failfast, 1); #endif } std::unique_ptr<ReturnData> AmiciApplication::runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { /* Applies condition-specific model settings and restores them when going * out of scope */ ConditionContext cc1(&model, edata, FixedParameterContext::simulation); std::unique_ptr<ReturnData> rdata = std::make_unique<ReturnData>(solver, model); std::unique_ptr<SteadystateProblem> preeq {}; std::unique_ptr<ForwardProblem> fwd {}; std::unique_ptr<BackwardProblem> bwd {}; std::unique_ptr<SteadystateProblem> posteq {}; try { if (solver.getPreequilibration() || (edata && !edata->fixedParametersPreequilibration.empty())) { ConditionContext cc2( &model, edata, FixedParameterContext::preequilibration ); preeq = std::make_unique<SteadystateProblem>(solver, model); preeq->workSteadyStateProblem(&solver, &model, -1); } fwd = std::make_unique<ForwardProblem>(edata, &model, &solver, preeq.get()); fwd->workForwardProblem(); if (fwd->getCurrentTimeIteration() < model.nt()) { posteq = std::make_unique<SteadystateProblem>(solver, model); posteq->workSteadyStateProblem(&solver, &model, fwd->getCurrentTimeIteration()); } if (edata && solver.computingASA()) { fwd->getAdjointUpdates(model, *edata); if (posteq) { posteq->getAdjointUpdates(model, *edata); posteq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } bwd = std::make_unique<BackwardProblem>(*fwd, posteq.get()); bwd->workBackwardProblem(); if (preeq) { ConditionContext cc2(&model, edata, FixedParameterContext::preequilibration); preeq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } } rdata->status = AMICI_SUCCESS; } catch (amici::IntegrationFailure const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF("AMICI:simulation", "AMICI forward simulation failed at t = %f:\n%s\n", ex.time, ex.what()); } catch (amici::IntegrationFailureB const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF( "AMICI:simulation", "AMICI backward simulation failed when trying to solve until t = %f" " (see message above):\n%s\n", ex.time, ex.what()); } catch (amici::AmiException const& ex) { rdata->status = AMICI_ERROR; if (rethrow) throw; warningF("AMICI:simulation", "AMICI simulation failed:\n%s\nError occured in:\n%s", ex.what(), ex.getBacktrace()); } rdata->processSimulationObjects(preeq.get(), fwd.get(), bwd.get(), posteq.get(), model, solver, edata); return rdata; } std::vector<std::unique_ptr<ReturnData>> AmiciApplication::runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { std::vector<std::unique_ptr<ReturnData>> results(edatas.size()); // is set to true if one simulation fails and we should skip the rest. // shared across threads. bool skipThrough = false; #if defined(_OPENMP) #pragma omp parallel for num_threads(num_threads) #endif for (int i = 0; i < (int)edatas.size(); ++i) { auto mySolver = std::unique_ptr<Solver>(solver.clone()); auto myModel = std::unique_ptr<Model>(model.clone()); /* if we fail we need to write empty return datas for the python interface */ if (skipThrough) { ConditionContext conditionContext(myModel.get(), edatas[i]); results[i] = std::unique_ptr<ReturnData>(new ReturnData(solver, model)); } else { results[i] = runAmiciSimulation(*mySolver, edatas[i], *myModel); } skipThrough |= failfast && results[i]->status < 0; } return results; } void AmiciApplication::warningF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); warning(identifier, str); } void AmiciApplication::errorF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); error(identifier, str); } int AmiciApplication::checkFinite(gsl::span<const realtype> array, const char* fun) { for (int idx = 0; idx < (int)array.size(); idx++) { if (isNaN(array[idx])) { warningF("AMICI:NaN", "AMICI encountered a NaN value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } if (isInf(array[idx])) { warningF("AMICI:Inf", "AMICI encountered an Inf value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } } return AMICI_SUCCESS; } } // namespace amici <commit_msg>Fix: Invalidate ReturnData::sllh on backwards integration failure (#1327)<commit_after>/** * @file amici.cpp * @brief core routines for integration */ #include "amici/amici.h" #include "amici/steadystateproblem.h" #include "amici/backwardproblem.h" #include "amici/forwardproblem.h" #include "amici/misc.h" #include <cvodes/cvodes.h> //return codes #include <sundials/sundials_types.h> //realtype #include <cassert> #include <cstdarg> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <type_traits> // ensure definitions are in sync static_assert(amici::AMICI_SUCCESS == CV_SUCCESS, "AMICI_SUCCESS != CV_SUCCESS"); static_assert(amici::AMICI_DATA_RETURN == CV_TSTOP_RETURN, "AMICI_DATA_RETURN != CV_TSTOP_RETURN"); static_assert(amici::AMICI_ROOT_RETURN == CV_ROOT_RETURN, "AMICI_ROOT_RETURN != CV_ROOT_RETURN"); static_assert(amici::AMICI_ILL_INPUT == CV_ILL_INPUT, "AMICI_ILL_INPUT != CV_ILL_INPUT"); static_assert(amici::AMICI_NORMAL == CV_NORMAL, "AMICI_NORMAL != CV_NORMAL"); static_assert(amici::AMICI_ONE_STEP == CV_ONE_STEP, "AMICI_ONE_STEP != CV_ONE_STEP"); static_assert(std::is_same<amici::realtype, realtype>::value, "Definition of realtype does not match"); namespace amici { /** AMICI default application context, kept around for convenience for using * amici::runAmiciSimulation or instantiating Solver and Model without special * needs. */ AmiciApplication defaultContext = AmiciApplication(); std::unique_ptr<ReturnData> runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { return defaultContext.runAmiciSimulation(solver, edata, model, rethrow); } void printErrMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Error] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } void printWarnMsgIdAndTxt(std::string const& id, std::string const& message) { std::cerr << "[Warning] "; if (!id.empty()) { std::cerr << id << ": "; } std::cerr << message << std::endl; } std::vector<std::unique_ptr<ReturnData>> runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, const bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { #if defined(_OPENMP) return defaultContext.runAmiciSimulations( solver, edatas, model, failfast, num_threads); #else return defaultContext.runAmiciSimulations(solver, edatas, model, failfast, 1); #endif } std::unique_ptr<ReturnData> AmiciApplication::runAmiciSimulation(Solver& solver, const ExpData* edata, Model& model, bool rethrow) { /* Applies condition-specific model settings and restores them when going * out of scope */ ConditionContext cc1(&model, edata, FixedParameterContext::simulation); std::unique_ptr<ReturnData> rdata = std::make_unique<ReturnData>(solver, model); std::unique_ptr<SteadystateProblem> preeq {}; std::unique_ptr<ForwardProblem> fwd {}; std::unique_ptr<BackwardProblem> bwd {}; std::unique_ptr<SteadystateProblem> posteq {}; // tracks whether backwards integration finished without exceptions bool bwd_success = true; try { if (solver.getPreequilibration() || (edata && !edata->fixedParametersPreequilibration.empty())) { ConditionContext cc2( &model, edata, FixedParameterContext::preequilibration ); preeq = std::make_unique<SteadystateProblem>(solver, model); preeq->workSteadyStateProblem(&solver, &model, -1); } fwd = std::make_unique<ForwardProblem>(edata, &model, &solver, preeq.get()); fwd->workForwardProblem(); if (fwd->getCurrentTimeIteration() < model.nt()) { posteq = std::make_unique<SteadystateProblem>(solver, model); posteq->workSteadyStateProblem(&solver, &model, fwd->getCurrentTimeIteration()); } if (edata && solver.computingASA()) { fwd->getAdjointUpdates(model, *edata); if (posteq) { posteq->getAdjointUpdates(model, *edata); posteq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } bwd_success = false; bwd = std::make_unique<BackwardProblem>(*fwd, posteq.get()); bwd->workBackwardProblem(); bwd_success = true; if (preeq) { ConditionContext cc2(&model, edata, FixedParameterContext::preequilibration); preeq->workSteadyStateBackwardProblem(&solver, &model, bwd.get()); } } rdata->status = AMICI_SUCCESS; } catch (amici::IntegrationFailure const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF("AMICI:simulation", "AMICI forward simulation failed at t = %f:\n%s\n", ex.time, ex.what()); } catch (amici::IntegrationFailureB const& ex) { rdata->status = ex.error_code; if (rethrow) throw; warningF( "AMICI:simulation", "AMICI backward simulation failed when trying to solve until t = %f" " (see message above):\n%s\n", ex.time, ex.what()); } catch (amici::AmiException const& ex) { rdata->status = AMICI_ERROR; if (rethrow) throw; warningF("AMICI:simulation", "AMICI simulation failed:\n%s\nError occured in:\n%s", ex.what(), ex.getBacktrace()); } rdata->processSimulationObjects( preeq.get(), fwd.get(), bwd_success ? bwd.get() : nullptr, posteq.get(), model, solver, edata); return rdata; } std::vector<std::unique_ptr<ReturnData>> AmiciApplication::runAmiciSimulations(const Solver& solver, const std::vector<ExpData*>& edatas, const Model& model, bool failfast, #if defined(_OPENMP) int num_threads #else int /* num_threads */ #endif ) { std::vector<std::unique_ptr<ReturnData>> results(edatas.size()); // is set to true if one simulation fails and we should skip the rest. // shared across threads. bool skipThrough = false; #if defined(_OPENMP) #pragma omp parallel for num_threads(num_threads) #endif for (int i = 0; i < (int)edatas.size(); ++i) { auto mySolver = std::unique_ptr<Solver>(solver.clone()); auto myModel = std::unique_ptr<Model>(model.clone()); /* if we fail we need to write empty return datas for the python interface */ if (skipThrough) { ConditionContext conditionContext(myModel.get(), edatas[i]); results[i] = std::unique_ptr<ReturnData>(new ReturnData(solver, model)); } else { results[i] = runAmiciSimulation(*mySolver, edatas[i], *myModel); } skipThrough |= failfast && results[i]->status < 0; } return results; } void AmiciApplication::warningF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); warning(identifier, str); } void AmiciApplication::errorF(const char* identifier, const char* format, ...) const { va_list argptr; va_start(argptr, format); auto str = printfToString(format, argptr); va_end(argptr); error(identifier, str); } int AmiciApplication::checkFinite(gsl::span<const realtype> array, const char* fun) { for (int idx = 0; idx < (int)array.size(); idx++) { if (isNaN(array[idx])) { warningF("AMICI:NaN", "AMICI encountered a NaN value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } if (isInf(array[idx])) { warningF("AMICI:Inf", "AMICI encountered an Inf value at index %i/%i in %s!", idx, (int)array.size()-1, fun); return AMICI_RECOVERABLE_ERROR; } } return AMICI_SUCCESS; } } // namespace amici <|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" #include "Delegate.hpp" #include "GlobalVector.hpp" #include "Statistics.hpp" #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> using namespace Grappa; BOOST_AUTO_TEST_SUITE( GlobalVector_tests ); static size_t N = (1L<<10) - 21; DEFINE_int64(nelems, N, "number of elements in (large) test arrays"); // DEFINE_int64(buffer_size, 1<<10, "number of elements in buffer"); DEFINE_int64(ntrials, 1, "number of independent trials to average over"); DEFINE_bool(perf, false, "do performance test"); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, push_time, 0); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, push_const_time, 0); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, deq_const_time, 0); template< typename T > inline T next_random() { using engine_t = boost::mt19937_64; using dist_t = boost::uniform_int<T>; using gen_t = boost::variate_generator<engine_t&,dist_t>; // continue using same generator with multiple calls (to not repeat numbers) // but start at different seed on each node so we don't get overlap static engine_t engine(12345L*mycore()); static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max())); return gen(); } enum class Exp { CONST_PUSH, RANDOM_PUSH, CONST_DEQUEUE }; template< Exp EXP, CompletionEvent* CE = &impl::local_ce, int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG > double push_perf_test(GlobalAddress<GlobalVector<int64_t>> qa) { double t = Grappa_walltime(); forall_global_private<CE,TH>(0, N, [qa](int64_t i){ if (EXP == Exp::RANDOM_PUSH) { qa->push(next_random<int64_t>()); } else if (EXP == Exp::CONST_PUSH) { qa->push(42); } else if (EXP == Exp::CONST_DEQUEUE) { CHECK_EQ(qa->dequeue(), 42); } }); t = Grappa_walltime() - t; if (EXP == Exp::RANDOM_PUSH || EXP == Exp::CONST_PUSH) { } else if (EXP == Exp::CONST_DEQUEUE) { } return t; } void test_global_vector() { BOOST_MESSAGE("Testing GlobalVector"); VLOG(1) << "testing global queue"; auto qa = GlobalVector<int64_t>::create(N); VLOG(1) << "queue addr: " << qa; BOOST_CHECK_EQUAL(qa->empty(), true); VLOG(0) << qa->storage(); on_all_cores([qa] { auto f = [qa](int64_t s, int64_t n) { for (int64_t i=s; i<s+n; i++) { qa->push(7); } BOOST_CHECK_EQUAL(qa->empty(), false); }; switch (mycore()) { case 0: forall_here(0, N/2, f); break; case 1: forall_here(N/2, N-N/2, f); break; } }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 7); } // forall_localized(qa->begin(), qa->size(), [](int64_t i, int64_t& e) { e = 9; }); forall_localized(qa, [](int64_t& e){ e = 9; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 9); } qa->destroy(); } void test_dequeue() { auto qa = GlobalVector<long>::create(N); on_all_cores([qa]{ auto NC = N/cores(); for (int i=0; i<NC; i++) { qa->enqueue(37); } auto size = qa->size(); BOOST_CHECK(size >= NC); if (mycore() == 1) barrier(); forall_here(0, NC/2, [qa](long s, long n) { for (int i=s; i<s+n; i++) { auto e = qa->dequeue(); BOOST_CHECK_EQUAL(e, 37); } }); if (mycore() != 1) barrier(); forall_here(0, NC-NC/2, [qa](long s, long n) { for (int i=s; i<s+n; i++) { auto e = qa->dequeue(); BOOST_CHECK_EQUAL(e, 37); } }); }); BOOST_CHECK_EQUAL(qa->size(), 0); qa->destroy(); } void test_stack() { LOG(INFO) << "testing stack..."; auto sa = GlobalVector<long>::create(N); forall_localized(sa->storage(), N, [](int64_t& e){ e = -1; }); on_all_cores([sa]{ forall_here(0, 100, [sa](int64_t i) { sa->push(17); BOOST_CHECK_EQUAL(sa->pop(), 17); }); }); LOG(INFO) << "second phase..."; on_all_cores([sa]{ for (int i=0; i<10; i++) sa->push(43); for (int i=0; i<5; i++) BOOST_CHECK_EQUAL(sa->pop(), 43); }); BOOST_CHECK_EQUAL(sa->size(), cores()*5); while (!sa->empty()) BOOST_CHECK_EQUAL(sa->pop(), 43); BOOST_CHECK_EQUAL(sa->size(), 0); BOOST_CHECK(sa->empty()); sa->destroy(); } void user_main( void * ignore ) { if (FLAGS_perf) { auto qa = GlobalVector<int64_t>::create(N); for (int i=0; i<FLAGS_ntrials; i++) { qa->clear(); VLOG(1) << "random push..."; push_time += push_perf_test<Exp::RANDOM_PUSH>(qa); qa->clear(); VLOG(1) << "const enqueue..."; push_const_time += push_perf_test<Exp::CONST_PUSH>(qa); BOOST_CHECK_EQUAL(qa->size(), N); forall_localized(qa, [](int64_t& e){ BOOST_CHECK_EQUAL(e, 42); }); VLOG(1) << "const dequeue..."; deq_const_time += push_perf_test<Exp::CONST_DEQUEUE>(qa); BOOST_CHECK_EQUAL(qa->size(), 0); } Statistics::merge_and_print(); qa->destroy(); } else { test_global_vector(); test_dequeue(); test_stack(); } } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); N = FLAGS_nelems; Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Setup queue and stack perf tests (with variable push mix)<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" #include "Delegate.hpp" #include "GlobalVector.hpp" #include "Statistics.hpp" #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> #include <random> using namespace Grappa; BOOST_AUTO_TEST_SUITE( GlobalVector_tests ); static size_t N = (1L<<10) - 21; DEFINE_int64(nelems, N, "number of elements in (large) test arrays"); DEFINE_int64(vector_size, N, "number of elements in (large) test arrays"); DEFINE_double(fraction_push, 0.5, "fraction of accesses that should be pushes"); // DEFINE_int64(buffer_size, 1<<10, "number of elements in buffer"); DEFINE_int64(ntrials, 1, "number of independent trials to average over"); DEFINE_bool(queue_perf, false, "do queue performance test"); DEFINE_bool(stack_perf, false, "do stack performance test"); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, trial_time, 0); template< typename T > inline T next_random() { using engine_t = boost::mt19937_64; using dist_t = boost::uniform_int<T>; using gen_t = boost::variate_generator<engine_t&,dist_t>; // continue using same generator with multiple calls (to not repeat numbers) // but start at different seed on each node so we don't get overlap static engine_t engine(12345L*mycore()); static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max())); return gen(); } bool choose_random(double probability) { std::default_random_engine e(12345L); std::uniform_real_distribution<double> dist(0.0, 1.0); return dist(e) < probability; } enum class Exp { PUSH, POP, DEQUEUE, QUEUE, STACK }; template< Exp EXP, CompletionEvent* CE = &impl::local_ce, int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG > double perf_test(GlobalAddress<GlobalVector<int64_t>> qa) { double t = Grappa_walltime(); forall_global_public<CE,TH>(0, FLAGS_nelems, [qa](int64_t i){ if (EXP == Exp::QUEUE) { if (choose_random(FLAGS_fraction_push)) { qa->push(next_random<int64_t>()); } else { qa->dequeue(); } } else if (EXP == Exp::STACK) { if (choose_random(FLAGS_fraction_push)) { qa->push(next_random<int64_t>()); } else { qa->pop(); } } else if (EXP == Exp::PUSH) { qa->push(next_random<int64_t>()); } else if (EXP == Exp::POP) { qa->pop(); } else if (EXP == Exp::DEQUEUE) { qa->dequeue(); } }); t = Grappa_walltime() - t; return t; } void test_global_vector() { BOOST_MESSAGE("Testing GlobalVector"); VLOG(1) << "testing global queue"; auto qa = GlobalVector<int64_t>::create(N); VLOG(1) << "queue addr: " << qa; BOOST_CHECK_EQUAL(qa->empty(), true); VLOG(0) << qa->storage(); on_all_cores([qa] { auto f = [qa](int64_t s, int64_t n) { for (int64_t i=s; i<s+n; i++) { qa->push(7); } BOOST_CHECK_EQUAL(qa->empty(), false); }; switch (mycore()) { case 0: forall_here(0, N/2, f); break; case 1: forall_here(N/2, N-N/2, f); break; } }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 7); } // forall_localized(qa->begin(), qa->size(), [](int64_t i, int64_t& e) { e = 9; }); forall_localized(qa, [](int64_t& e){ e = 9; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 9); } qa->destroy(); } void test_dequeue() { auto qa = GlobalVector<long>::create(N); on_all_cores([qa]{ auto NC = N/cores(); for (int i=0; i<NC; i++) { qa->enqueue(37); } auto size = qa->size(); BOOST_CHECK(size >= NC); if (mycore() == 1) barrier(); forall_here(0, NC/2, [qa](long s, long n) { for (int i=s; i<s+n; i++) { auto e = qa->dequeue(); BOOST_CHECK_EQUAL(e, 37); } }); if (mycore() != 1) barrier(); forall_here(0, NC-NC/2, [qa](long s, long n) { for (int i=s; i<s+n; i++) { auto e = qa->dequeue(); BOOST_CHECK_EQUAL(e, 37); } }); }); BOOST_CHECK_EQUAL(qa->size(), 0); qa->destroy(); } void test_stack() { LOG(INFO) << "testing stack..."; auto sa = GlobalVector<long>::create(N); forall_localized(sa->storage(), N, [](int64_t& e){ e = -1; }); on_all_cores([sa]{ forall_here(0, 100, [sa](int64_t i) { sa->push(17); BOOST_CHECK_EQUAL(sa->pop(), 17); }); }); LOG(INFO) << "second phase..."; on_all_cores([sa]{ for (int i=0; i<10; i++) sa->push(43); for (int i=0; i<5; i++) BOOST_CHECK_EQUAL(sa->pop(), 43); }); BOOST_CHECK_EQUAL(sa->size(), cores()*5); while (!sa->empty()) BOOST_CHECK_EQUAL(sa->pop(), 43); BOOST_CHECK_EQUAL(sa->size(), 0); BOOST_CHECK(sa->empty()); sa->destroy(); } void user_main( void * ignore ) { if (FLAGS_queue_perf || FLAGS_stack_perf) { auto qa = GlobalVector<int64_t>::create(FLAGS_vector_size); for (int i=0; i<FLAGS_ntrials; i++) { qa->clear(); if (FLAGS_fraction_push < 1.0) { // fill halfway so we don't hit either rail forall_global_public(0, FLAGS_vector_size/2, [qa](int64_t i){ qa->push(next_random<int64_t>()); }); } if (FLAGS_queue_perf) { trial_time += perf_test<Exp::QUEUE>(qa); } else if (FLAGS_stack_perf) { trial_time += perf_test<Exp::STACK>(qa); } } Statistics::merge_and_print(); qa->destroy(); } else { test_global_vector(); test_dequeue(); test_stack(); } } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); N = FLAGS_nelems; Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) The Taichi Authors (2016- ). All Rights Reserved. The use of this software is governed by the LICENSE file. *******************************************************************************/ #include "taichi/runtime/metal/api.h" #include "taichi/runtime/gfx/runtime.h" #include "taichi/rhi/dx/dx_api.h" #include "taichi/common/core.h" #include "taichi/common/interface.h" #include "taichi/common/task.h" #include "taichi/math/math.h" #include "taichi/platform/cuda/detect_cuda.h" #include "taichi/program/py_print_buffer.h" #include "taichi/python/exception.h" #include "taichi/python/export.h" #include "taichi/python/memory_usage_monitor.h" #include "taichi/system/benchmark.h" #include "taichi/system/dynamic_loader.h" #include "taichi/system/hacked_signal_handler.h" #include "taichi/system/profiler.h" #include "taichi/util/statistics.h" #if defined(TI_WITH_CUDA) #include "taichi/rhi/cuda/cuda_driver.h" #endif #ifdef TI_WITH_VULKAN #include "taichi/rhi/vulkan/vulkan_loader.h" #endif #ifdef TI_WITH_OPENGL #include "taichi/rhi/opengl/opengl_api.h" #endif #ifdef TI_WITH_DX12 #include "taichi/rhi/dx12/dx12_api.h" #endif #ifdef TI_WITH_CC namespace taichi::lang::cccp { extern bool is_c_backend_available(); } #endif namespace taichi { void test_raise_error() { raise_assertion_failure_in_python("Just a test."); } void print_all_units() { std::vector<std::string> names; auto interfaces = InterfaceHolder::get_instance()->interfaces; for (auto &kv : interfaces) { names.push_back(kv.first); } std::sort(names.begin(), names.end()); int all_units = 0; for (auto &interface_name : names) { auto impls = interfaces[interface_name]->get_implementation_names(); std::cout << " * " << interface_name << " [" << int(impls.size()) << "]" << std::endl; all_units += int(impls.size()); std::sort(impls.begin(), impls.end()); for (auto &impl : impls) { std::cout << " + " << impl << std::endl; } } std::cout << all_units << " units in all." << std::endl; } void export_misc(py::module &m) { py::class_<Config>(m, "Config"); // NOLINT(bugprone-unused-raii) py::register_exception_translator([](std::exception_ptr p) { try { if (p) std::rethrow_exception(p); } catch (const ExceptionForPython &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } }); py::class_<Task, std::shared_ptr<Task>>(m, "Task") .def("initialize", &Task::initialize) .def("run", static_cast<std::string (Task::*)(const std::vector<std::string> &)>( &Task::run)); py::class_<Benchmark, std::shared_ptr<Benchmark>>(m, "Benchmark") .def("run", &Benchmark::run) .def("test", &Benchmark::test) .def("initialize", &Benchmark::initialize); #define TI_EXPORT_LOGGING(X) \ m.def(#X, [](const std::string &msg) { \ taichi::Logger::get_instance().X(msg); \ }); m.def("flush_log", []() { taichi::Logger::get_instance().flush(); }); TI_EXPORT_LOGGING(trace); TI_EXPORT_LOGGING(debug); TI_EXPORT_LOGGING(info); TI_EXPORT_LOGGING(warn); TI_EXPORT_LOGGING(error); TI_EXPORT_LOGGING(critical); m.def("print_all_units", print_all_units); m.def("set_core_state_python_imported", CoreState::set_python_imported); m.def("set_logging_level", [](const std::string &level) { Logger::get_instance().set_level(level); }); m.def("logging_effective", [](const std::string &level) { return Logger::get_instance().is_level_effective(level); }); m.def("set_logging_level_default", []() { Logger::get_instance().set_level_default(); }); m.def("set_core_trigger_gdb_when_crash", CoreState::set_trigger_gdb_when_crash); m.def("test_raise_error", test_raise_error); m.def("get_default_float_size", []() { return sizeof(real); }); m.def("trigger_sig_fpe", []() { int a = 2; a -= 2; return 1 / a; }); m.def("print_profile_info", [&]() { Profiling::get_instance().print_profile_info(); }); m.def("clear_profile_info", [&]() { Profiling::get_instance().clear_profile_info(); }); m.def("start_memory_monitoring", start_memory_monitoring); m.def("get_repo_dir", get_repo_dir); m.def("get_python_package_dir", get_python_package_dir); m.def("set_python_package_dir", set_python_package_dir); m.def("cuda_version", get_cuda_version_string); m.def("test_cpp_exception", [] { try { throw std::exception(); } catch (const std::exception &e) { printf("caught.\n"); } printf("test was successful.\n"); }); m.def("pop_python_print_buffer", []() { return py_cout.pop_content(); }); m.def("toggle_python_print_buffer", [](bool opt) { py_cout.enabled = opt; }); m.def("with_cuda", is_cuda_api_available); #ifdef TI_WITH_METAL m.def("with_metal", taichi::lang::metal::is_metal_api_available); #else m.def("with_metal", []() { return false; }); #endif #ifdef TI_WITH_OPENGL m.def("with_opengl", taichi::lang::opengl::is_opengl_api_available, py::arg("use_gles") = false); #else m.def("with_opengl", []() { return false; }); #endif #ifdef TI_WITH_VULKAN m.def("with_vulkan", taichi::lang::vulkan::is_vulkan_api_available); m.def("set_vulkan_visible_device", taichi::lang::vulkan::set_vulkan_visible_device); #else m.def("with_vulkan", []() { return false; }); #endif #ifdef TI_WITH_DX11 m.def("with_dx11", taichi::lang::directx11::is_dx_api_available); #else m.def("with_dx11", []() { return false; }); #endif #ifdef TI_WITH_DX12 m.def("with_dx12", taichi::lang::directx12::is_dx12_api_available); #else m.def("with_dx12", []() { return false; }); #endif #ifdef TI_WITH_CC m.def("with_cc", taichi::lang::cccp::is_c_backend_available); #else m.def("with_cc", []() { return false; }); #endif py::class_<Statistics>(m, "Statistics") .def(py::init<>()) .def("clear", &Statistics::clear) .def("get_counters", &Statistics::get_counters); m.def( "get_kernel_stats", []() -> Statistics & { return stat; }, py::return_value_policy::reference); py::class_<HackedSignalRegister>(m, "HackedSignalRegister").def(py::init<>()); } } // namespace taichi <commit_msg>[opengl] Fix with_opengl when TI_WITH_OPENGL is off (#6353)<commit_after>/******************************************************************************* Copyright (c) The Taichi Authors (2016- ). All Rights Reserved. The use of this software is governed by the LICENSE file. *******************************************************************************/ #include "taichi/runtime/metal/api.h" #include "taichi/runtime/gfx/runtime.h" #include "taichi/rhi/dx/dx_api.h" #include "taichi/common/core.h" #include "taichi/common/interface.h" #include "taichi/common/task.h" #include "taichi/math/math.h" #include "taichi/platform/cuda/detect_cuda.h" #include "taichi/program/py_print_buffer.h" #include "taichi/python/exception.h" #include "taichi/python/export.h" #include "taichi/python/memory_usage_monitor.h" #include "taichi/system/benchmark.h" #include "taichi/system/dynamic_loader.h" #include "taichi/system/hacked_signal_handler.h" #include "taichi/system/profiler.h" #include "taichi/util/statistics.h" #if defined(TI_WITH_CUDA) #include "taichi/rhi/cuda/cuda_driver.h" #endif #ifdef TI_WITH_VULKAN #include "taichi/rhi/vulkan/vulkan_loader.h" #endif #ifdef TI_WITH_OPENGL #include "taichi/rhi/opengl/opengl_api.h" #endif #ifdef TI_WITH_DX12 #include "taichi/rhi/dx12/dx12_api.h" #endif #ifdef TI_WITH_CC namespace taichi::lang::cccp { extern bool is_c_backend_available(); } #endif namespace taichi { void test_raise_error() { raise_assertion_failure_in_python("Just a test."); } void print_all_units() { std::vector<std::string> names; auto interfaces = InterfaceHolder::get_instance()->interfaces; for (auto &kv : interfaces) { names.push_back(kv.first); } std::sort(names.begin(), names.end()); int all_units = 0; for (auto &interface_name : names) { auto impls = interfaces[interface_name]->get_implementation_names(); std::cout << " * " << interface_name << " [" << int(impls.size()) << "]" << std::endl; all_units += int(impls.size()); std::sort(impls.begin(), impls.end()); for (auto &impl : impls) { std::cout << " + " << impl << std::endl; } } std::cout << all_units << " units in all." << std::endl; } void export_misc(py::module &m) { py::class_<Config>(m, "Config"); // NOLINT(bugprone-unused-raii) py::register_exception_translator([](std::exception_ptr p) { try { if (p) std::rethrow_exception(p); } catch (const ExceptionForPython &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } }); py::class_<Task, std::shared_ptr<Task>>(m, "Task") .def("initialize", &Task::initialize) .def("run", static_cast<std::string (Task::*)(const std::vector<std::string> &)>( &Task::run)); py::class_<Benchmark, std::shared_ptr<Benchmark>>(m, "Benchmark") .def("run", &Benchmark::run) .def("test", &Benchmark::test) .def("initialize", &Benchmark::initialize); #define TI_EXPORT_LOGGING(X) \ m.def(#X, [](const std::string &msg) { \ taichi::Logger::get_instance().X(msg); \ }); m.def("flush_log", []() { taichi::Logger::get_instance().flush(); }); TI_EXPORT_LOGGING(trace); TI_EXPORT_LOGGING(debug); TI_EXPORT_LOGGING(info); TI_EXPORT_LOGGING(warn); TI_EXPORT_LOGGING(error); TI_EXPORT_LOGGING(critical); m.def("print_all_units", print_all_units); m.def("set_core_state_python_imported", CoreState::set_python_imported); m.def("set_logging_level", [](const std::string &level) { Logger::get_instance().set_level(level); }); m.def("logging_effective", [](const std::string &level) { return Logger::get_instance().is_level_effective(level); }); m.def("set_logging_level_default", []() { Logger::get_instance().set_level_default(); }); m.def("set_core_trigger_gdb_when_crash", CoreState::set_trigger_gdb_when_crash); m.def("test_raise_error", test_raise_error); m.def("get_default_float_size", []() { return sizeof(real); }); m.def("trigger_sig_fpe", []() { int a = 2; a -= 2; return 1 / a; }); m.def("print_profile_info", [&]() { Profiling::get_instance().print_profile_info(); }); m.def("clear_profile_info", [&]() { Profiling::get_instance().clear_profile_info(); }); m.def("start_memory_monitoring", start_memory_monitoring); m.def("get_repo_dir", get_repo_dir); m.def("get_python_package_dir", get_python_package_dir); m.def("set_python_package_dir", set_python_package_dir); m.def("cuda_version", get_cuda_version_string); m.def("test_cpp_exception", [] { try { throw std::exception(); } catch (const std::exception &e) { printf("caught.\n"); } printf("test was successful.\n"); }); m.def("pop_python_print_buffer", []() { return py_cout.pop_content(); }); m.def("toggle_python_print_buffer", [](bool opt) { py_cout.enabled = opt; }); m.def("with_cuda", is_cuda_api_available); #ifdef TI_WITH_METAL m.def("with_metal", taichi::lang::metal::is_metal_api_available); #else m.def("with_metal", []() { return false; }); #endif #ifdef TI_WITH_OPENGL m.def("with_opengl", taichi::lang::opengl::is_opengl_api_available, py::arg("use_gles") = false); #else m.def("with_opengl", [](bool use_gles) { return false; }); #endif #ifdef TI_WITH_VULKAN m.def("with_vulkan", taichi::lang::vulkan::is_vulkan_api_available); m.def("set_vulkan_visible_device", taichi::lang::vulkan::set_vulkan_visible_device); #else m.def("with_vulkan", []() { return false; }); #endif #ifdef TI_WITH_DX11 m.def("with_dx11", taichi::lang::directx11::is_dx_api_available); #else m.def("with_dx11", []() { return false; }); #endif #ifdef TI_WITH_DX12 m.def("with_dx12", taichi::lang::directx12::is_dx12_api_available); #else m.def("with_dx12", []() { return false; }); #endif #ifdef TI_WITH_CC m.def("with_cc", taichi::lang::cccp::is_c_backend_available); #else m.def("with_cc", []() { return false; }); #endif py::class_<Statistics>(m, "Statistics") .def(py::init<>()) .def("clear", &Statistics::clear) .def("get_counters", &Statistics::get_counters); m.def( "get_kernel_stats", []() -> Statistics & { return stat; }, py::return_value_policy::reference); py::class_<HackedSignalRegister>(m, "HackedSignalRegister").def(py::init<>()); } } // namespace taichi <|endoftext|>
<commit_before>// Copyright (c) 2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "base58.h" #include "hash.h" #include "pubkey.h" #include "util.h" #include "utilstrencodings.h" #include <openssl/aes.h> #include <openssl/sha.h> #include <secp256k1.h> #include <string> /** 39 bytes - 78 characters * 1) Prefix - 2 bytes - 4 chars - strKey[0..3] * 2) Flagbyte - 1 byte - 2 chars - strKey[4..5] * 3) addresshash - 4 bytes - 8 chars - strKey[6..13] * 4) Owner Entropy - 8 bytes - 16 chars - strKey[14..29] * 5) Encrypted Part 1 - 8 bytes - 16 chars - strKey[30..45] * 6) Encrypted Part 2 - 16 bytes - 32 chars - strKey[46..77] */ void DecryptAES(uint256 encryptedIn, uint256 decryptionKey, uint256& output) { AES_KEY key; AES_set_decrypt_key(decryptionKey.begin(), 256, &key); AES_decrypt(encryptedIn.begin(), output.begin(), &key); } void ComputePreFactor(std::string strPassphrase, std::string strSalt, uint256& prefactor) { //passfactor is the scrypt hash of passphrase and ownersalt (NOTE this needs to handle alt cases too in the future) uint64_t s = uint256(ReverseEndianString(strSalt)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(s), strSalt.size() / 2, BEGIN(prefactor), 16384, 8, 8, 32); } void ComputePassfactor(std::string ownersalt, uint256 prefactor, uint256& passfactor) { //concat prefactor and ownersalt uint512 temp(ReverseEndianString(HexStr(prefactor) + ownersalt)); Hash(temp.begin(), 40, passfactor.begin()); //40 bytes is the length of prefactor + salt Hash(passfactor.begin(), 32, passfactor.begin()); } bool ComputePasspoint(uint256 passfactor, CPubKey& passpoint) { size_t clen = 65; secp256k1_context *ctx = NULL; secp256k1_pubkey pubkey; //passpoint is the ec_mult of passfactor on secp256k1 if (!secp256k1_ec_pubkey_create(ctx, &pubkey, passfactor.begin())) return false; secp256k1_ec_pubkey_serialize(ctx, (unsigned char*)passpoint.begin(), &clen, &pubkey, SECP256K1_EC_COMPRESSED); if (passpoint.size() != clen) return false; if (!passpoint.IsValid()) return false; return true; } void ComputeSeedBPass(CPubKey passpoint, std::string strAddressHash, std::string strOwnerSalt, uint512& seedBPass) { // Derive decryption key for seedb using scrypt with passpoint, addresshash, and ownerentropy string salt = ReverseEndianString(strAddressHash + strOwnerSalt); uint256 s2(salt); scrypt_hash(BEGIN(passpoint), HexStr(passpoint).size() / 2, BEGIN(s2), salt.size() / 2, BEGIN(seedBPass), 1024, 1, 1, 64); } void ComputeFactorB(uint256 seedB, uint256& factorB) { //factorB - a double sha256 hash of seedb Hash(seedB.begin(), 24, factorB.begin()); //seedB is only 24 bytes Hash(factorB.begin(), 32, factorB.begin()); } std::string AddressToBip38Hash(std::string address) { uint256 addrCheck; Hash((void*)address.c_str(), address.size(), addrCheck.begin()); Hash(addrCheck.begin(), 32, addrCheck.begin()); return HexStr(addrCheck).substr(0, 8); } std::string BIP38_Encrypt(std::string strAddress, std::string strPassphrase, uint256 privKey, bool fCompressed) { string strAddressHash = AddressToBip38Hash(strAddress); uint512 hashed; uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); //block1 = (pointb[1...16] xor derivedhalf1[0...15]) uint256 block1 = uint256((privKey << 128) ^ (derivedHalf1 << 128)) >> 128; //encrypt part 1 uint512 encrypted1; AES_KEY key; AES_set_encrypt_key(derivedHalf2.begin(), 256, &key); AES_encrypt(block1.begin(), encrypted1.begin(), &key); //block2 = (pointb[17...32] xor derivedhalf1[16...31] uint256 p2 = privKey >> 128; uint256 dh12 = derivedHalf1 >> 128; uint256 block2 = uint256(p2 ^ dh12); //encrypt part 2 uint512 encrypted2; AES_encrypt(block2.begin(), encrypted2.begin(), &key); string strPrefix = "0142"; strPrefix += (fCompressed ? "E0" : "C0"); uint512 encryptedKey(ReverseEndianString(strPrefix + strAddressHash)); //add encrypted1 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted1 << 56); //add encrypted2 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted2 << (56 + 128)); //Base58 checksum is the 4 bytes of dSHA256 hash of the encrypted key uint256 hashChecksum = Hash(encryptedKey.begin(), encryptedKey.begin() + 39); uint512 b58Checksum(hashChecksum.ToString().substr(64 - 8, 8)); // append the encrypted key with checksum (currently occupies 312 bits) encryptedKey = encryptedKey | (b58Checksum << 312); //43 bytes is the total size that we are encoding return EncodeBase58(encryptedKey.begin(), encryptedKey.begin() + 43); } bool BIP38_Decrypt(std::string strPassphrase, std::string strEncryptedKey, uint256& privKey, bool& fCompressed) { std::string strKey = DecodeBase58(strEncryptedKey.c_str()); //incorrect encoding of key, it must be 39 bytes - and another 4 bytes for base58 checksum if (strKey.size() != (78 + 8)) return false; //invalid prefix if (uint256(ReverseEndianString(strKey.substr(0, 2))) != uint256(0x01)) return false; uint256 type(ReverseEndianString(strKey.substr(2, 2))); uint256 flag(ReverseEndianString(strKey.substr(4, 2))); std::string strAddressHash = strKey.substr(6, 8); std::string ownersalt = strKey.substr(14, 16); uint256 encryptedPart1(ReverseEndianString(strKey.substr(30, 16))); uint256 encryptedPart2(ReverseEndianString(strKey.substr(46, 32))); fCompressed = (flag & uint256(0x20)) != 0; //not ec multiplied if (type == uint256(0x42)) { uint512 hashed; encryptedPart1 = uint256(ReverseEndianString(strKey.substr(14, 32))); uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); uint256 decryptedPart1; DecryptAES(encryptedPart1, derivedHalf2, decryptedPart1); uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //combine decrypted parts into 64 bytes uint256 temp1 = decryptedPart2 << 128; temp1 = temp1 | decryptedPart1; //xor the decryption with the derived half 1 for the final key privKey = temp1 ^ derivedHalf1; return true; } else if (type != uint256(0x43)) //invalid type return false; bool fLotSequence = (flag & 0x04) != 0; std::string prefactorSalt = ownersalt; if (fLotSequence) prefactorSalt = ownersalt.substr(0, 8); uint256 prefactor; ComputePreFactor(strPassphrase, prefactorSalt, prefactor); uint256 passfactor; if (fLotSequence) ComputePassfactor(ownersalt, prefactor, passfactor); else passfactor = prefactor; CPubKey passpoint; if (!ComputePasspoint(passfactor, passpoint)) return false; uint512 seedBPass; ComputeSeedBPass(passpoint, strAddressHash, ownersalt, seedBPass); //get derived halfs, being mindful for endian switch uint256 derivedHalf1(seedBPass.ToString().substr(64, 64)); uint256 derivedHalf2(seedBPass.ToString().substr(0, 64)); /** Decrypt encryptedpart2 using AES256Decrypt to yield the last 8 bytes of seedb and the last 8 bytes of encryptedpart1. **/ uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //xor decryptedPart2 and 2nd half of derived half 1 uint256 x0 = derivedHalf1 >> 128; //drop off the first half (note: endian) uint256 x1 = decryptedPart2 ^ x0; uint256 seedbPart2 = x1 >> 64; /** Decrypt encryptedpart1 to yield the remainder of seedb. **/ uint256 decryptedPart1; uint256 x2 = x1 & uint256("0xffffffffffffffff"); // set x2 to seedbPart1 (still encrypted) x2 = x2 << 64; //make room to add encryptedPart1 to the front x2 = encryptedPart1 | x2; //combine with encryptedPart1 DecryptAES(x2, derivedHalf2, decryptedPart1); //decrypted part 1: seedb[0..15] xor derivedhalf1[0..15] uint256 x3 = derivedHalf1 & uint256("0xffffffffffffffffffffffffffffffff"); uint256 seedbPart1 = decryptedPart1 ^ x3; uint256 seedB = seedbPart1 | (seedbPart2 << 128); uint256 factorB; ComputeFactorB(seedB, factorB); //multiply passfactor by factorb mod N to yield the priv key secp256k1_context *ctx = NULL; privKey = factorB; if (!secp256k1_ec_privkey_tweak_mul(ctx, privKey.begin(), passfactor.begin())) return false; //double check that the address hash matches our final privkey CKey k; k.Set(privKey.begin(), privKey.end(), fCompressed); CPubKey pubkey = k.GetPubKey(); string address = CBitcoinAddress(pubkey.GetID()).ToString(); return strAddressHash == AddressToBip38Hash(address); } <commit_msg>[Crypto] Add ctx initialisation for bip38<commit_after>// Copyright (c) 2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "base58.h" #include "hash.h" #include "pubkey.h" #include "util.h" #include "utilstrencodings.h" #include "random.h" #include <openssl/aes.h> #include <openssl/sha.h> #include <secp256k1.h> #include <string> /** 39 bytes - 78 characters * 1) Prefix - 2 bytes - 4 chars - strKey[0..3] * 2) Flagbyte - 1 byte - 2 chars - strKey[4..5] * 3) addresshash - 4 bytes - 8 chars - strKey[6..13] * 4) Owner Entropy - 8 bytes - 16 chars - strKey[14..29] * 5) Encrypted Part 1 - 8 bytes - 16 chars - strKey[30..45] * 6) Encrypted Part 2 - 16 bytes - 32 chars - strKey[46..77] */ void DecryptAES(uint256 encryptedIn, uint256 decryptionKey, uint256& output) { AES_KEY key; AES_set_decrypt_key(decryptionKey.begin(), 256, &key); AES_decrypt(encryptedIn.begin(), output.begin(), &key); } void ComputePreFactor(std::string strPassphrase, std::string strSalt, uint256& prefactor) { //passfactor is the scrypt hash of passphrase and ownersalt (NOTE this needs to handle alt cases too in the future) uint64_t s = uint256(ReverseEndianString(strSalt)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(s), strSalt.size() / 2, BEGIN(prefactor), 16384, 8, 8, 32); } void ComputePassfactor(std::string ownersalt, uint256 prefactor, uint256& passfactor) { //concat prefactor and ownersalt uint512 temp(ReverseEndianString(HexStr(prefactor) + ownersalt)); Hash(temp.begin(), 40, passfactor.begin()); //40 bytes is the length of prefactor + salt Hash(passfactor.begin(), 32, passfactor.begin()); } bool ComputePasspoint(uint256 passfactor, CPubKey& passpoint) { size_t clen = 65; secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } secp256k1_pubkey pubkey; //passpoint is the ec_mult of passfactor on secp256k1 if (!secp256k1_ec_pubkey_create(ctx, &pubkey, passfactor.begin())) { secp256k1_context_destroy(ctx); return false; } secp256k1_ec_pubkey_serialize(ctx, (unsigned char*)passpoint.begin(), &clen, &pubkey, SECP256K1_EC_COMPRESSED); secp256k1_context_destroy(ctx); if (passpoint.size() != clen) return false; if (!passpoint.IsValid()) return false; return true; } void ComputeSeedBPass(CPubKey passpoint, std::string strAddressHash, std::string strOwnerSalt, uint512& seedBPass) { // Derive decryption key for seedb using scrypt with passpoint, addresshash, and ownerentropy string salt = ReverseEndianString(strAddressHash + strOwnerSalt); uint256 s2(salt); scrypt_hash(BEGIN(passpoint), HexStr(passpoint).size() / 2, BEGIN(s2), salt.size() / 2, BEGIN(seedBPass), 1024, 1, 1, 64); } void ComputeFactorB(uint256 seedB, uint256& factorB) { //factorB - a double sha256 hash of seedb Hash(seedB.begin(), 24, factorB.begin()); //seedB is only 24 bytes Hash(factorB.begin(), 32, factorB.begin()); } std::string AddressToBip38Hash(std::string address) { uint256 addrCheck; Hash((void*)address.c_str(), address.size(), addrCheck.begin()); Hash(addrCheck.begin(), 32, addrCheck.begin()); return HexStr(addrCheck).substr(0, 8); } std::string BIP38_Encrypt(std::string strAddress, std::string strPassphrase, uint256 privKey, bool fCompressed) { string strAddressHash = AddressToBip38Hash(strAddress); uint512 hashed; uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); //block1 = (pointb[1...16] xor derivedhalf1[0...15]) uint256 block1 = uint256((privKey << 128) ^ (derivedHalf1 << 128)) >> 128; //encrypt part 1 uint512 encrypted1; AES_KEY key; AES_set_encrypt_key(derivedHalf2.begin(), 256, &key); AES_encrypt(block1.begin(), encrypted1.begin(), &key); //block2 = (pointb[17...32] xor derivedhalf1[16...31] uint256 p2 = privKey >> 128; uint256 dh12 = derivedHalf1 >> 128; uint256 block2 = uint256(p2 ^ dh12); //encrypt part 2 uint512 encrypted2; AES_encrypt(block2.begin(), encrypted2.begin(), &key); string strPrefix = "0142"; strPrefix += (fCompressed ? "E0" : "C0"); uint512 encryptedKey(ReverseEndianString(strPrefix + strAddressHash)); //add encrypted1 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted1 << 56); //add encrypted2 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted2 << (56 + 128)); //Base58 checksum is the 4 bytes of dSHA256 hash of the encrypted key uint256 hashChecksum = Hash(encryptedKey.begin(), encryptedKey.begin() + 39); uint512 b58Checksum(hashChecksum.ToString().substr(64 - 8, 8)); // append the encrypted key with checksum (currently occupies 312 bits) encryptedKey = encryptedKey | (b58Checksum << 312); //43 bytes is the total size that we are encoding return EncodeBase58(encryptedKey.begin(), encryptedKey.begin() + 43); } bool BIP38_Decrypt(std::string strPassphrase, std::string strEncryptedKey, uint256& privKey, bool& fCompressed) { std::string strKey = DecodeBase58(strEncryptedKey.c_str()); //incorrect encoding of key, it must be 39 bytes - and another 4 bytes for base58 checksum if (strKey.size() != (78 + 8)) return false; //invalid prefix if (uint256(ReverseEndianString(strKey.substr(0, 2))) != uint256(0x01)) return false; uint256 type(ReverseEndianString(strKey.substr(2, 2))); uint256 flag(ReverseEndianString(strKey.substr(4, 2))); std::string strAddressHash = strKey.substr(6, 8); std::string ownersalt = strKey.substr(14, 16); uint256 encryptedPart1(ReverseEndianString(strKey.substr(30, 16))); uint256 encryptedPart2(ReverseEndianString(strKey.substr(46, 32))); fCompressed = (flag & uint256(0x20)) != 0; //not ec multiplied if (type == uint256(0x42)) { uint512 hashed; encryptedPart1 = uint256(ReverseEndianString(strKey.substr(14, 32))); uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); uint256 decryptedPart1; DecryptAES(encryptedPart1, derivedHalf2, decryptedPart1); uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //combine decrypted parts into 64 bytes uint256 temp1 = decryptedPart2 << 128; temp1 = temp1 | decryptedPart1; //xor the decryption with the derived half 1 for the final key privKey = temp1 ^ derivedHalf1; return true; } else if (type != uint256(0x43)) //invalid type return false; bool fLotSequence = (flag & 0x04) != 0; std::string prefactorSalt = ownersalt; if (fLotSequence) prefactorSalt = ownersalt.substr(0, 8); uint256 prefactor; ComputePreFactor(strPassphrase, prefactorSalt, prefactor); uint256 passfactor; if (fLotSequence) ComputePassfactor(ownersalt, prefactor, passfactor); else passfactor = prefactor; CPubKey passpoint; if (!ComputePasspoint(passfactor, passpoint)) return false; uint512 seedBPass; ComputeSeedBPass(passpoint, strAddressHash, ownersalt, seedBPass); //get derived halfs, being mindful for endian switch uint256 derivedHalf1(seedBPass.ToString().substr(64, 64)); uint256 derivedHalf2(seedBPass.ToString().substr(0, 64)); /** Decrypt encryptedpart2 using AES256Decrypt to yield the last 8 bytes of seedb and the last 8 bytes of encryptedpart1. **/ uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //xor decryptedPart2 and 2nd half of derived half 1 uint256 x0 = derivedHalf1 >> 128; //drop off the first half (note: endian) uint256 x1 = decryptedPart2 ^ x0; uint256 seedbPart2 = x1 >> 64; /** Decrypt encryptedpart1 to yield the remainder of seedb. **/ uint256 decryptedPart1; uint256 x2 = x1 & uint256("0xffffffffffffffff"); // set x2 to seedbPart1 (still encrypted) x2 = x2 << 64; //make room to add encryptedPart1 to the front x2 = encryptedPart1 | x2; //combine with encryptedPart1 DecryptAES(x2, derivedHalf2, decryptedPart1); //decrypted part 1: seedb[0..15] xor derivedhalf1[0..15] uint256 x3 = derivedHalf1 & uint256("0xffffffffffffffffffffffffffffffff"); uint256 seedbPart1 = decryptedPart1 ^ x3; uint256 seedB = seedbPart1 | (seedbPart2 << 128); uint256 factorB; ComputeFactorB(seedB, factorB); //multiply passfactor by factorb mod N to yield the priv key secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } privKey = factorB; if (!secp256k1_ec_privkey_tweak_mul(ctx, privKey.begin(), passfactor.begin())) { secp256k1_context_destroy(ctx); return false; } secp256k1_context_destroy(ctx); //double check that the address hash matches our final privkey CKey k; k.Set(privKey.begin(), privKey.end(), fCompressed); CPubKey pubkey = k.GetPubKey(); string address = CBitcoinAddress(pubkey.GetID()).ToString(); return strAddressHash == AddressToBip38Hash(address); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bloom.h" #include "core.h" #include "script.h" #include <math.h> #include <stdlib.h> #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2 0.6931471805599453094172321214581765680755001343602552 using namespace std; static const unsigned char bit_mask[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : // The ideal size for a bloom filter with a given number of elements and false positive rate is: // - nElements * log(fp rate) / ln(2)^2 // We ignore filter parameters which will create a bloom filter larger than the protocol limits vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8), // The ideal number of hash functions is filter size * ln(2) / number of elements // Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits // See http://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas isFull(false), isEmpty(false), nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), nTweak(nTweakIn), nFlags(nFlagsIn) { } inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const { // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8); } void CBloomFilter::insert(const vector<unsigned char>& vKey) { if (isFull) return; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Sets bit nIndex of vData vData[nIndex >> 3] |= bit_mask[7 & nIndex]; } isEmpty = false; } void CBloomFilter::insert(const COutPoint& outpoint) { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); insert(data); } void CBloomFilter::insert(const uint256& hash) { vector<unsigned char> data(hash.begin(), hash.end()); insert(data); } bool CBloomFilter::contains(const vector<unsigned char>& vKey) const { if (isFull) return true; if (isEmpty) return false; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Checks bit nIndex of vData if (!(vData[nIndex >> 3] & bit_mask[7 & nIndex])) return false; } return true; } bool CBloomFilter::contains(const COutPoint& outpoint) const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); return contains(data); } bool CBloomFilter::contains(const uint256& hash) const { vector<unsigned char> data(hash.begin(), hash.end()); return contains(data); } bool CBloomFilter::IsWithinSizeConstraints() const { return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS; } bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash) { bool fFound = false; // Match if the filter contains the hash of tx // for finding tx when they appear in a block if (isFull) return true; if (isEmpty) return false; if (contains(hash)) fFound = true; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx // If this matches, also add the specific output that was matched. // This means clients don't have to update the filter themselves when a new relevant tx // is discovered in order to find spending transactions, which avoids round-tripping and race conditions. CScript::const_iterator pc = txout.scriptPubKey.begin(); vector<unsigned char> data; while (pc < txout.scriptPubKey.end()) { opcodetype opcode; if (!txout.scriptPubKey.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) { fFound = true; if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL) insert(COutPoint(hash, i)); else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) { txnouttype type; vector<vector<unsigned char> > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_MULTISIG)) insert(COutPoint(hash, i)); } break; } } } if (fFound) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Match if the filter contains an outpoint tx spends if (contains(txin.prevout)) return true; // Match if the filter contains any arbitrary script data element in any scriptSig in tx CScript::const_iterator pc = txin.scriptSig.begin(); vector<unsigned char> data; while (pc < txin.scriptSig.end()) { opcodetype opcode; if (!txin.scriptSig.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) return true; } } return false; } void CBloomFilter::UpdateEmptyFull() { bool full = true; bool empty = true; for (unsigned int i = 0; i < vData.size(); i++) { full &= vData[i] == 0xff; empty &= vData[i] == 0; } isFull = full; isEmpty = empty; } <commit_msg>Fix bloom filter not to use bit_mask<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bloom.h" #include "core.h" #include "script.h" #include <math.h> #include <stdlib.h> #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2 0.6931471805599453094172321214581765680755001343602552 using namespace std; CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : // The ideal size for a bloom filter with a given number of elements and false positive rate is: // - nElements * log(fp rate) / ln(2)^2 // We ignore filter parameters which will create a bloom filter larger than the protocol limits vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8), // The ideal number of hash functions is filter size * ln(2) / number of elements // Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits // See http://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas isFull(false), isEmpty(false), nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), nTweak(nTweakIn), nFlags(nFlagsIn) { } inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const { // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values. return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8); } void CBloomFilter::insert(const vector<unsigned char>& vKey) { if (isFull) return; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Sets bit nIndex of vData vData[nIndex >> 3] |= (1 << (7 & nIndex)); } isEmpty = false; } void CBloomFilter::insert(const COutPoint& outpoint) { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); insert(data); } void CBloomFilter::insert(const uint256& hash) { vector<unsigned char> data(hash.begin(), hash.end()); insert(data); } bool CBloomFilter::contains(const vector<unsigned char>& vKey) const { if (isFull) return true; if (isEmpty) return false; for (unsigned int i = 0; i < nHashFuncs; i++) { unsigned int nIndex = Hash(i, vKey); // Checks bit nIndex of vData if (!(vData[nIndex >> 3] & (1 << (7 & nIndex)))) return false; } return true; } bool CBloomFilter::contains(const COutPoint& outpoint) const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; vector<unsigned char> data(stream.begin(), stream.end()); return contains(data); } bool CBloomFilter::contains(const uint256& hash) const { vector<unsigned char> data(hash.begin(), hash.end()); return contains(data); } bool CBloomFilter::IsWithinSizeConstraints() const { return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS; } bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash) { bool fFound = false; // Match if the filter contains the hash of tx // for finding tx when they appear in a block if (isFull) return true; if (isEmpty) return false; if (contains(hash)) fFound = true; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx // If this matches, also add the specific output that was matched. // This means clients don't have to update the filter themselves when a new relevant tx // is discovered in order to find spending transactions, which avoids round-tripping and race conditions. CScript::const_iterator pc = txout.scriptPubKey.begin(); vector<unsigned char> data; while (pc < txout.scriptPubKey.end()) { opcodetype opcode; if (!txout.scriptPubKey.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) { fFound = true; if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL) insert(COutPoint(hash, i)); else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) { txnouttype type; vector<vector<unsigned char> > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_MULTISIG)) insert(COutPoint(hash, i)); } break; } } } if (fFound) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Match if the filter contains an outpoint tx spends if (contains(txin.prevout)) return true; // Match if the filter contains any arbitrary script data element in any scriptSig in tx CScript::const_iterator pc = txin.scriptSig.begin(); vector<unsigned char> data; while (pc < txin.scriptSig.end()) { opcodetype opcode; if (!txin.scriptSig.GetOp(pc, opcode, data)) break; if (data.size() != 0 && contains(data)) return true; } } return false; } void CBloomFilter::UpdateEmptyFull() { bool full = true; bool empty = true; for (unsigned int i = 0; i < vData.size(); i++) { full &= vData[i] == 0xff; empty &= vData[i] == 0; } isFull = full; isEmpty = empty; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "encoder/dash_writer.h" #include <ios> #include <sstream> #include "glog/logging.h" namespace webmlive { const char kIndentStep[] = " "; // Default values for DashConfig. Time values in seconds unless otherwise noted. // TODO(tomfinegan): Not sure if default belongs in the name for schema and // profiles here; should these be configurable? const char kDefaultSchema[] = "urn:mpeg:dash:schema:mpd:2011"; const int kDefaultMinBufferTime = 1; const int kDefaultMediaPresentationDuration = 36000; // 10 hours. const char kDefaultType[] = "static"; const char kDefaultProfiles[] = "urn:mpeg:dash:profile:isoff-live:2011"; const int kDefaultStartTime = 0; const int kDefaultMaxWidth = 1920; const int kDefaultMaxHeight = 1080; const int kDefaultMaxFrameRate = 60; const int kDefaultContentComponentId = 1; const char kContentComponentTypeAudio[] = "audio"; const char kContentComponentTypeVideo[] = "video"; const int kDefaultPeriodDuration = kDefaultMediaPresentationDuration; const int kDefaultTimescale = 1000; // milliseconds. const int kDefaultChunkDuration = 5000; // milliseconds. const std::string kDefaultStartNumber = "1"; const int kDefaultStartWithSap = 1; const int kDefaultBandwidth = 1000000; // Bits. const int kDefaultFrameRate = 30; const int kDefaultAudioSampleRate = 44100; const int kDefaultAudioChannels = 2; const char kAudioMimeType[] = "audio/webm"; const char kVideoMimeType[] = "video/webm"; const char kAudioCodecs[] = "vorbis"; const char kVideoCodecs[] = "vp9"; const char kAudioId[] = "1"; const char kVideoId[] = "2"; // Base strings for initialization and chunk names. const char kChunkPattern[] = "_$RepresentationID$_$Number$.chk"; const char kInitializationPattern[] = "_$RepresentationID$.hdr"; const char kAudioSchemeUri[] = "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"; // // AdaptationSet // AdaptationSet::AdaptationSet() : enabled(false), media_type(kVideo), segment_alignment(true), bitstream_switching(false), cc_id(kVideoId), content_type(kContentComponentTypeVideo), timescale(kDefaultTimescale), chunk_duration(kDefaultChunkDuration), start_number(kDefaultStartNumber), start_with_sap(kDefaultStartWithSap), bandwidth(kDefaultBandwidth) {} // // AudioAdaptationSet // AudioAdaptationSet::AudioAdaptationSet() : audio_sampling_rate(kDefaultAudioSampleRate), scheme_id_uri(kAudioSchemeUri), value(kDefaultAudioChannels) { media_type = kAudio; content_type = kContentComponentTypeAudio; mimetype = kAudioMimeType; codecs = kAudioCodecs; } // // VideoAdaptationSet // VideoAdaptationSet::VideoAdaptationSet() : max_width(kDefaultMaxWidth), max_height(kDefaultMaxHeight), max_frame_rate(kDefaultMaxFrameRate), width(kDefaultMaxWidth), height(kDefaultMaxHeight), frame_rate(kDefaultFrameRate) { media_type = kVideo; cc_id = kAudioId; mimetype = kVideoMimeType; codecs = kVideoCodecs; } // // DashConfig // DashConfig::DashConfig() : type(kDefaultType), min_buffer_time(kDefaultMinBufferTime), media_presentation_duration(kDefaultMediaPresentationDuration), start_time(kDefaultStartTime), period_duration(kDefaultPeriodDuration) {} // // DashWriter // bool DashWriter::Init(const WebmEncoderConfig& webm_config) { if (webm_config.dash_name.empty()) { LOG(ERROR) << "name empty in DashWriter::Init()"; return false; } name_ = webm_config.dash_name; if (!webm_config.disable_audio) { config_.audio_as.enabled = true; config_.audio_as.bandwidth = webm_config.vorbis_config.average_bitrate * 1000; config_.audio_as.media = name_ + kChunkPattern; config_.audio_as.initialization = name_ + kInitializationPattern; config_.audio_as.rep_id = kAudioId; config_.audio_as.audio_sampling_rate = webm_config.actual_audio_config.sample_rate; config_.audio_as.value = webm_config.actual_audio_config.channels; config_.audio_as.start_number = webm_config.dash_start_number; } if (!webm_config.disable_video) { config_.video_as.enabled = true; config_.video_as.bandwidth = webm_config.vpx_config.bitrate * 1000; config_.video_as.media = name_ + kChunkPattern; config_.video_as.initialization = name_ + kInitializationPattern; config_.video_as.rep_id = kVideoId; config_.video_as.width = webm_config.actual_video_config.width; config_.video_as.height = webm_config.actual_video_config.height; config_.video_as.start_number = webm_config.dash_start_number; if (webm_config.vpx_config.decimate != VpxConfig::kUseDefault) { config_.video_as.frame_rate = static_cast<int>( std::ceil(webm_config.actual_video_config.frame_rate / webm_config.vpx_config.decimate)); } else { config_.video_as.frame_rate = static_cast<int>( std::ceil(webm_config.actual_video_config.frame_rate)); } if (config_.video_as.frame_rate > config_.video_as.max_frame_rate) { config_.video_as.max_frame_rate = config_.video_as.frame_rate; } } config_.audio_as.chunk_duration = webm_config.vpx_config.keyframe_interval; config_.video_as.chunk_duration = webm_config.vpx_config.keyframe_interval; initialized_ = true; return true; } bool DashWriter::WriteManifest(std::string* out_manifest) { CHECK_NOTNULL(out_manifest); if (!initialized_) { LOG(ERROR) << "DashWriter not initialized before call to WriteManifest()"; return false; } std::ostringstream manifest; manifest << "<?xml version=\"1.0\"?>\n"; // Open the MPD element. manifest << "<MPD " << "xmlns=\"" << kDefaultSchema << "\" " << "type=\"" << config_.type << "\" " << "minBufferTime=\"PT" << config_.min_buffer_time << "S\" " << "mediaPresentationDuration=\"PT" << config_.media_presentation_duration << "S\" " << "profiles=\"" << kDefaultProfiles << "\">" << "\n"; IncreaseIndent(); // Open the Period element. manifest << indent_ << "<Period " << "start=\"PT" << config_.start_time << "S\" " << "duration=\"PT" << config_.period_duration << "S\">" << "\n"; IncreaseIndent(); if (config_.audio_as.enabled) { std::string audio_as; WriteAudioAdaptationSet(&audio_as); manifest << audio_as; } if (config_.video_as.enabled) { std::string video_as; WriteVideoAdaptationSet(&video_as); manifest << video_as; } // Close open elements. DecreaseIndent(); manifest << indent_ << "</Period>\n"; DecreaseIndent(); manifest << indent_ << "</MPD>\n"; LOG(INFO) << "\nmanifest:\n" << manifest.str(); *out_manifest = manifest.str(); return true; } std::string DashWriter::IdForChunk(AdaptationSet::MediaType media_type, int64 chunk_num) const { CHECK(initialized_); std::string initialization; std::string media; if (media_type == AdaptationSet::kAudio) { initialization = name_ + "_" + kAudioId + ".hdr"; media = name_ + "_" + kAudioId + "_"; } else { initialization = name_ + "_" + kVideoId + ".hdr"; media = name_ + "_" + kVideoId + "_"; } std::ostringstream id; if (chunk_num == 0) { id << initialization << ""; } else { id << media << chunk_num << ".chk"; } return id.str(); } void DashWriter::WriteAudioAdaptationSet(std::string* adaptation_set) { CHECK_NOTNULL(adaptation_set); std::ostringstream a_stream; const AudioAdaptationSet& audio_as = config_.audio_as; // Open the AdaptationSet element. a_stream << indent_ << "<AdaptationSet " << "segmentAlignment=\"" << std::boolalpha << audio_as.segment_alignment << "\" " << "audioSamplingRate=\"" << audio_as.audio_sampling_rate << "\" " << "bitstreamSwitching=\"" << audio_as.bitstream_switching << "\">" << "\n"; IncreaseIndent(); // Write AudioChannelConfiguration element. a_stream << indent_ << "<AudioChannelConfiguration " << "schemeIdUri=\"" << audio_as.scheme_id_uri << "\" " << "value=\"" << audio_as.value << "\">" << "</AudioChannelConfiguration>" << "\n"; // Write ContentComponent element. a_stream << indent_ << "<ContentComponent " << "id=\"" << audio_as.cc_id << "\" " << "contentType=\"" << audio_as.content_type << "\"/>" << "\n"; // Write SegmentTemplate element. a_stream << indent_ << "<SegmentTemplate " << "timescale=\"" << audio_as.timescale << "\" " << "duration=\"" << audio_as.chunk_duration << "\" " << "media=\"" << audio_as.media << "\" " << "startNumber=\"" << audio_as.start_number << "\" " << "initialization=\"" << audio_as.initialization << "\"/>" << "\n"; // Write the Representation element. a_stream << indent_ << "<Representation " << "id=\"" << audio_as.rep_id << "\" " << "mimeType=\"" << audio_as.mimetype << "\" " << "codecs=\"" << audio_as.codecs << "\" " << "startWithSAP=\"" << audio_as.start_with_sap << "\" " << "bandwidth=\"" << audio_as.bandwidth << "\" " << "></Representation>" << "\n"; // Close open the AdaptationSet element. DecreaseIndent(); a_stream << indent_ << "</AdaptationSet>\n"; *adaptation_set = a_stream.str(); } void DashWriter::WriteVideoAdaptationSet(std::string* adaptation_set) { CHECK_NOTNULL(adaptation_set); std::ostringstream v_stream; const VideoAdaptationSet& video_as = config_.video_as; // Open the AdaptationSet element. v_stream << indent_ << "<AdaptationSet " << "segmentAlignment=\"" << std::boolalpha << video_as.segment_alignment << "\" " << "bitstreamSwitching=\"" << video_as.bitstream_switching << "\" " << "maxWidth=\"" << video_as.max_width << "\" " << "maxHeight=\"" << video_as.max_height << "\" " << "maxFrameRate=\"" << video_as.max_frame_rate << "\">" << "\n"; IncreaseIndent(); // Write ContentComponent element. v_stream << indent_ << "<ContentComponent " << "id=\"" << video_as.cc_id << "\" " << "contentType=\"" << video_as.content_type << "\"/>" << "\n"; // Write SegmentTemplate element. v_stream << indent_ << "<SegmentTemplate " << "timescale=\"" << video_as.timescale << "\" " << "duration=\"" << video_as.chunk_duration << "\" " << "media=\"" << video_as.media << "\" " << "startNumber=\"" << video_as.start_number << "\" " << "initialization=\"" << video_as.initialization << "\"/>" << "\n"; // Write the Representation element. v_stream << indent_ << "<Representation " << "id=\"" << video_as.rep_id << "\" " << "mimeType=\"" << video_as.mimetype << "\" " << "codecs=\"" << video_as.codecs << "\" " << "width=\"" << video_as.width << "\" " << "height=\"" << video_as.height << "\" " << "startWithSAP=\"" << video_as.start_with_sap << "\" " << "bandwidth=\"" << video_as.bandwidth << "\" " << "frameRate=\"" << video_as.frame_rate << "\" " << "></Representation>" << "\n"; // Close open the AdaptationSet element. DecreaseIndent(); v_stream << indent_ << "</AdaptationSet>\n"; *adaptation_set = v_stream.str(); } void DashWriter::IncreaseIndent() { indent_ = indent_ + kIndentStep; } void DashWriter::DecreaseIndent() { std::string indent_step = kIndentStep; if (indent_.length() > 0) indent_ = indent_.substr(0, indent_.length() - indent_step.length()); } void DashWriter::ResetIndent() { indent_ = ""; } } // namespace webmlive <commit_msg>dash_writer: Update MPD output to allow live streaming<commit_after>// Copyright (c) 2015 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "encoder/dash_writer.h" #include <ctime> #include <ios> #include <sstream> #include "glog/logging.h" #include "encoder/time_util.h" namespace webmlive { const char kIndentStep[] = " "; // Default values for DashConfig. Time values in seconds unless otherwise noted. // TODO(tomfinegan): Not sure if default belongs in the name for schema and // profiles here; should these be configurable? const char kDefaultSchema[] = "urn:mpeg:dash:schema:mpd:2011"; const int kDefaultMinBufferTime = 1; const int kDefaultMediaPresentationDuration = 36000; // 10 hours. const char kDefaultType[] = "dynamic"; const char kDefaultProfiles[] = "urn:mpeg:dash:profile:isoff-live:2011"; const int kDefaultStartTime = 0; const int kDefaultMaxWidth = 1920; const int kDefaultMaxHeight = 1080; const int kDefaultMaxFrameRate = 60; const int kDefaultContentComponentId = 1; const char kContentComponentTypeAudio[] = "audio"; const char kContentComponentTypeVideo[] = "video"; const int kDefaultPeriodDuration = kDefaultMediaPresentationDuration; const int kDefaultTimescale = 1000; // milliseconds. const int kDefaultChunkDuration = 5000; // milliseconds. const std::string kDefaultStartNumber = "1"; const int kDefaultStartWithSap = 1; const int kDefaultBandwidth = 1000000; // Bits. const int kDefaultFrameRate = 30; const int kDefaultAudioSampleRate = 44100; const int kDefaultAudioChannels = 2; const char kAudioMimeType[] = "audio/webm"; const char kVideoMimeType[] = "video/webm"; const char kAudioCodecs[] = "vorbis"; const char kVideoCodecs[] = "vp9"; const char kAudioId[] = "1"; const char kVideoId[] = "2"; // Base strings for initialization and chunk names. const char kChunkPattern[] = "_$RepresentationID$_$Number$.chk"; const char kInitializationPattern[] = "_$RepresentationID$.hdr"; const char kAudioSchemeUri[] = "urn:mpeg:dash:23003:3:audio_channel_configuration:2011"; // %Y - year // %m - month, zero padded (01-12) // %d - day of month, zero padded (01-31). // %H - hour, zero padded, 24 hour clock (00-23) // %M - minute, zero padded (00-59) // %S - second, zero padded (00-61) const char kAvailabilityStartTimeFormat[] = "%Y-%m-%dT%H:%M:%SZ"; // // AdaptationSet // AdaptationSet::AdaptationSet() : enabled(false), media_type(kVideo), segment_alignment(true), bitstream_switching(false), cc_id(kVideoId), content_type(kContentComponentTypeVideo), timescale(kDefaultTimescale), chunk_duration(kDefaultChunkDuration), start_number(kDefaultStartNumber), start_with_sap(kDefaultStartWithSap), bandwidth(kDefaultBandwidth) {} // // AudioAdaptationSet // AudioAdaptationSet::AudioAdaptationSet() : audio_sampling_rate(kDefaultAudioSampleRate), scheme_id_uri(kAudioSchemeUri), value(kDefaultAudioChannels) { media_type = kAudio; content_type = kContentComponentTypeAudio; mimetype = kAudioMimeType; codecs = kAudioCodecs; } // // VideoAdaptationSet // VideoAdaptationSet::VideoAdaptationSet() : max_width(kDefaultMaxWidth), max_height(kDefaultMaxHeight), max_frame_rate(kDefaultMaxFrameRate), width(kDefaultMaxWidth), height(kDefaultMaxHeight), frame_rate(kDefaultFrameRate) { media_type = kVideo; cc_id = kAudioId; mimetype = kVideoMimeType; codecs = kVideoCodecs; } // // DashConfig // DashConfig::DashConfig() : type(kDefaultType), min_buffer_time(kDefaultMinBufferTime), media_presentation_duration(kDefaultMediaPresentationDuration), start_time(kDefaultStartTime), period_duration(kDefaultPeriodDuration) {} // // DashWriter // bool DashWriter::Init(const WebmEncoderConfig& webm_config) { if (webm_config.dash_name.empty()) { LOG(ERROR) << "name empty in DashWriter::Init()"; return false; } name_ = webm_config.dash_name; if (!webm_config.disable_audio) { config_.audio_as.enabled = true; config_.audio_as.bandwidth = webm_config.vorbis_config.average_bitrate * 1000; config_.audio_as.media = name_ + kChunkPattern; config_.audio_as.initialization = name_ + kInitializationPattern; config_.audio_as.rep_id = kAudioId; config_.audio_as.audio_sampling_rate = webm_config.actual_audio_config.sample_rate; config_.audio_as.value = webm_config.actual_audio_config.channels; config_.audio_as.start_number = webm_config.dash_start_number; } if (!webm_config.disable_video) { config_.video_as.enabled = true; config_.video_as.bandwidth = webm_config.vpx_config.bitrate * 1000; config_.video_as.media = name_ + kChunkPattern; config_.video_as.initialization = name_ + kInitializationPattern; config_.video_as.rep_id = kVideoId; config_.video_as.width = webm_config.actual_video_config.width; config_.video_as.height = webm_config.actual_video_config.height; config_.video_as.start_number = webm_config.dash_start_number; if (webm_config.vpx_config.decimate != VpxConfig::kUseDefault) { config_.video_as.frame_rate = static_cast<int>( std::ceil(webm_config.actual_video_config.frame_rate / webm_config.vpx_config.decimate)); } else { config_.video_as.frame_rate = static_cast<int>( std::ceil(webm_config.actual_video_config.frame_rate)); } if (config_.video_as.frame_rate > config_.video_as.max_frame_rate) { config_.video_as.max_frame_rate = config_.video_as.frame_rate; } } config_.audio_as.chunk_duration = webm_config.vpx_config.keyframe_interval; config_.video_as.chunk_duration = webm_config.vpx_config.keyframe_interval; initialized_ = true; return true; } bool DashWriter::WriteManifest(std::string* out_manifest) { CHECK_NOTNULL(out_manifest); if (!initialized_) { LOG(ERROR) << "DashWriter not initialized before call to WriteManifest()"; return false; } std::ostringstream manifest; manifest << "<?xml version=\"1.0\"?>\n"; time_t raw_time = time(NULL); // Open the MPD element. manifest << "<MPD " << "xmlns=\"" << kDefaultSchema << "\" " << "type=\"" << config_.type << "\" " << "availabilityStartTime=\"" << StrFTime(gmtime(&raw_time), kAvailabilityStartTimeFormat) << "\" " << "minBufferTime=\"PT" << config_.min_buffer_time << "S\" " << "mediaPresentationDuration=\"PT" << config_.media_presentation_duration << "S\" " << "profiles=\"" << kDefaultProfiles << "\">" << "\n"; IncreaseIndent(); // Open the Period element. manifest << indent_ << "<Period " << "start=\"PT" << config_.start_time << "S\" " << "duration=\"PT" << config_.period_duration << "S\">" << "\n"; IncreaseIndent(); if (config_.audio_as.enabled) { std::string audio_as; WriteAudioAdaptationSet(&audio_as); manifest << audio_as; } if (config_.video_as.enabled) { std::string video_as; WriteVideoAdaptationSet(&video_as); manifest << video_as; } // Close open elements. DecreaseIndent(); manifest << indent_ << "</Period>\n"; DecreaseIndent(); manifest << indent_ << "</MPD>\n"; LOG(INFO) << "\nmanifest:\n" << manifest.str(); *out_manifest = manifest.str(); return true; } std::string DashWriter::IdForChunk(AdaptationSet::MediaType media_type, int64 chunk_num) const { CHECK(initialized_); std::string initialization; std::string media; if (media_type == AdaptationSet::kAudio) { initialization = name_ + "_" + kAudioId + ".hdr"; media = name_ + "_" + kAudioId + "_"; } else { initialization = name_ + "_" + kVideoId + ".hdr"; media = name_ + "_" + kVideoId + "_"; } std::ostringstream id; if (chunk_num == 0) { id << initialization << ""; } else { id << media << chunk_num << ".chk"; } return id.str(); } void DashWriter::WriteAudioAdaptationSet(std::string* adaptation_set) { CHECK_NOTNULL(adaptation_set); std::ostringstream a_stream; const AudioAdaptationSet& audio_as = config_.audio_as; // Open the AdaptationSet element. a_stream << indent_ << "<AdaptationSet " << "segmentAlignment=\"" << std::boolalpha << audio_as.segment_alignment << "\" " << "audioSamplingRate=\"" << audio_as.audio_sampling_rate << "\" " << "bitstreamSwitching=\"" << audio_as.bitstream_switching << "\">" << "\n"; IncreaseIndent(); // Write AudioChannelConfiguration element. a_stream << indent_ << "<AudioChannelConfiguration " << "schemeIdUri=\"" << audio_as.scheme_id_uri << "\" " << "value=\"" << audio_as.value << "\">" << "</AudioChannelConfiguration>" << "\n"; // Write ContentComponent element. a_stream << indent_ << "<ContentComponent " << "id=\"" << audio_as.cc_id << "\" " << "contentType=\"" << audio_as.content_type << "\"/>" << "\n"; // Write SegmentTemplate element. a_stream << indent_ << "<SegmentTemplate " << "timescale=\"" << audio_as.timescale << "\" " << "duration=\"" << audio_as.chunk_duration << "\" " << "media=\"" << audio_as.media << "\" " << "startNumber=\"" << audio_as.start_number << "\" " << "initialization=\"" << audio_as.initialization << "\"/>" << "\n"; // Write the Representation element. a_stream << indent_ << "<Representation " << "id=\"" << audio_as.rep_id << "\" " << "mimeType=\"" << audio_as.mimetype << "\" " << "codecs=\"" << audio_as.codecs << "\" " << "startWithSAP=\"" << audio_as.start_with_sap << "\" " << "bandwidth=\"" << audio_as.bandwidth << "\" " << "></Representation>" << "\n"; // Close open the AdaptationSet element. DecreaseIndent(); a_stream << indent_ << "</AdaptationSet>\n"; *adaptation_set = a_stream.str(); } void DashWriter::WriteVideoAdaptationSet(std::string* adaptation_set) { CHECK_NOTNULL(adaptation_set); std::ostringstream v_stream; const VideoAdaptationSet& video_as = config_.video_as; // Open the AdaptationSet element. v_stream << indent_ << "<AdaptationSet " << "segmentAlignment=\"" << std::boolalpha << video_as.segment_alignment << "\" " << "bitstreamSwitching=\"" << video_as.bitstream_switching << "\" " << "maxWidth=\"" << video_as.max_width << "\" " << "maxHeight=\"" << video_as.max_height << "\" " << "maxFrameRate=\"" << video_as.max_frame_rate << "\">" << "\n"; IncreaseIndent(); // Write ContentComponent element. v_stream << indent_ << "<ContentComponent " << "id=\"" << video_as.cc_id << "\" " << "contentType=\"" << video_as.content_type << "\"/>" << "\n"; // Write SegmentTemplate element. v_stream << indent_ << "<SegmentTemplate " << "timescale=\"" << video_as.timescale << "\" " << "duration=\"" << video_as.chunk_duration << "\" " << "media=\"" << video_as.media << "\" " << "startNumber=\"" << video_as.start_number << "\" " << "initialization=\"" << video_as.initialization << "\"/>" << "\n"; // Write the Representation element. v_stream << indent_ << "<Representation " << "id=\"" << video_as.rep_id << "\" " << "mimeType=\"" << video_as.mimetype << "\" " << "codecs=\"" << video_as.codecs << "\" " << "width=\"" << video_as.width << "\" " << "height=\"" << video_as.height << "\" " << "startWithSAP=\"" << video_as.start_with_sap << "\" " << "bandwidth=\"" << video_as.bandwidth << "\" " << "frameRate=\"" << video_as.frame_rate << "\" " << "></Representation>" << "\n"; // Close open the AdaptationSet element. DecreaseIndent(); v_stream << indent_ << "</AdaptationSet>\n"; *adaptation_set = v_stream.str(); } void DashWriter::IncreaseIndent() { indent_ = indent_ + kIndentStep; } void DashWriter::DecreaseIndent() { std::string indent_step = kIndentStep; if (indent_.length() > 0) indent_ = indent_.substr(0, indent_.length() - indent_step.length()); } void DashWriter::ResetIndent() { indent_ = ""; } } // namespace webmlive <|endoftext|>
<commit_before>#include "client_net.h" #include "interactive.h" #include "crc32.h" #include "md5.h" #include "sha1.h" #include "sha256.h" #include "sha3.h" #include "spdlog/spdlog.h" #include "logging.h" #include "auth_common.h" #include "packets/radius_packet.h" #include "packets/eap_packet.h" #include "packets/packet.h" #include "packets/utils.h" using namespace std; const std::vector<byte> temp = {0xe0, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8}; const std::string LOGGER_NAME = "client"; std::string hashString(std::string input, std::string hash); int main(int argc, char **argv) { using namespace TCLAP; try { CmdLine cmd("NAS Test Client", ' '); ValueArg<string> logpathArg("l", "log", "The path where log file shall be written", false, "client.log", "string"); cmd.add(logpathArg); ValueArg<string> loginArg( "u", "username", "The name of a user that wishes to authenticate", false, "Basia", "string"); cmd.add(loginArg); ValueArg<string> passArg("", "password", "The password of a user", false, "password", "string"); cmd.add(passArg); /* SwitchArg interSwitch("i", "interactive", */ /* "Run in the interactive mode", false); */ /* cmd.add(interSwitch); */ SwitchArg verboseSwitch("v", "verbose", "Run in the verbose mode", false); cmd.add(verboseSwitch); ValueArg<string> secretArg("s", "secret", "The secret shared with NAS", true, "", "string"); cmd.add(secretArg); ValueArg<int> portArg("p", "port", "Binded port", false, 0, "number"); cmd.add(portArg); ValueArg<string> bindIpArg("b", "bind-ip", "Binded IP address", false, "0.0.0.0", "IP"); cmd.add(bindIpArg); ValueArg<string> ipArg("a", "address", "Server IP address", true, "", "IP"); cmd.add(ipArg); ValueArg<string> hashArg( "", "hash", "Type of hashing function (crc32 md5 sha1 sha256 sha3)", false, "sha256", "string"); cmd.add(hashArg); cmd.parse(argc, argv); int port = portArg.getValue(); string ip = ipArg.getValue(); string bindIp = ipArg.getValue(); string secret = secretArg.getValue(); string logpath = logpathArg.getValue(); radius::initLogger(logpath, LOGGER_NAME); bool verbose = verboseSwitch.getValue(); if (verbose) { spdlog::set_level(spdlog::level::trace); } auto logger = spdlog::get(LOGGER_NAME); string hash = hashArg.getValue(); string login = loginArg.getValue(); string pas = passArg.getValue(); /* bool inter = interSwitch.getValue(); */ // setup address structure //adres serwera struct sockaddr_in server_addr; memset((char *)&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); /* if (inter) { */ /* login = radius::getUsername(); */ /* pas = radius::getPassword("Enter password:\n"); */ /* } */ pas = hashString(pas, hash); // radius::packets::Packet newPack(temp, server_addr); radius::startClient(ip.c_str(), port); // 1.access-request using namespace radius; using namespace radius::packets; EapPacket eapIdentity; eapIdentity = makeIdentity(login); eapIdentity.setType(EapPacket::RESPONSE); eapIdentity.setIdentifier(1); EapMessage eapMessage; eapMessage.setValue(eapIdentity.getBuffer()); RadiusPacket arPacket; arPacket.setIdentifier(1); arPacket.setCode(RadiusPacket::ACCESS_REQUEST); std::array<radius::byte, 16> authTable = generateRandom16(); arPacket.setAuthenticator(authTable); arPacket.addAVP(static_cast<const RadiusAVP &>(eapMessage)); calcAndSetMsgAuth(arPacket, secret); radius::packets::Packet newPack(arPacket.getBuffer(), server_addr); logger->info() <<"Send Packet"; logger->info() <<"[Packet:]\n" << packet2LogBytes(newPack.bytes); logger->info() <<"[RadiusPacket:]\n"<< arPacket; logger->info() <<"[EapPacket:]\n"<< eapIdentity; radius::sendPack(newPack); // 2.otrzymuj odpowiedz od Radius server newPack = radius::receivePack(); RadiusPacket recArPacket(newPack.bytes); logger->info() <<"Received Packet"; logger->info() <<"[Packet:]\n" <<packet2LogBytes(recArPacket.getBuffer()); logger->info() <<"[RadiusPacket:]\n"<< recArPacket; EapPacket recEapIdentity = extractEapPacket(recArPacket); logger->info() <<"[EapPacket:]\n"<< recEapIdentity; std::array<radius::byte,16> chalArray =calcChalVal(recEapIdentity,secret); //make response EapPacket eapMd5Chal; eapMd5Chal = makeChallengeResp(chalArray); eapMd5Chal.setType(EapPacket::RESPONSE); eapMd5Chal.setIdentifier(2); EapMessage eapMessage2; eapMessage2.setValue(eapMd5Chal.getBuffer()); RadiusPacket responsePacket; responsePacket.setIdentifier(2); responsePacket.setCode(RadiusPacket::ACCESS_REQUEST); authTable = generateRandom16(); responsePacket.setAuthenticator(authTable); responsePacket.addAVP(static_cast<const RadiusAVP &>(eapMessage2)); calcAndSetMsgAuth(responsePacket, secret); radius::packets::Packet responsePack(responsePacket.getBuffer() , server_addr); logger->info() <<"Send Packet"; logger->info() <<"[Packet:]\n" << packet2LogBytes(responsePack.bytes); logger->info() <<"[RadiusPacket:]\n"<< responsePacket; logger->info() <<"[EapPacket:]\n"<< eapMd5Chal; radius::sendPack(responsePack); // 4.success or failure //newPack = radius::receivePack(); radius::stopClient(); } catch (ArgException &e) { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; } } std::string hashString(std::string input, std::string hash) { std::string output; if (hash == "sha256") { SHA256 sha256; output = sha256(input); } else if (hash == "sha1") { SHA1 sha1; output = sha1(input); } else if (hash == "sha3") { SHA3 sha3; output = sha3(input); } else if (hash == "md5") { MD5 md5; output = md5(input); } else if (hash == "crc32") { CRC32 crc32; output = crc32(input); } else { output = input; } return output; } <commit_msg>odbior pakietu<commit_after>#include "client_net.h" #include "interactive.h" #include "crc32.h" #include "md5.h" #include "sha1.h" #include "sha256.h" #include "sha3.h" #include "spdlog/spdlog.h" #include "logging.h" #include "auth_common.h" #include "packets/radius_packet.h" #include "packets/eap_packet.h" #include "packets/packet.h" #include "packets/utils.h" using namespace std; const std::vector<byte> temp = {0xe0, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8}; const std::string LOGGER_NAME = "client"; std::string hashString(std::string input, std::string hash); int main(int argc, char **argv) { using namespace TCLAP; try { CmdLine cmd("NAS Test Client", ' '); ValueArg<string> logpathArg("l", "log", "The path where log file shall be written", false, "client.log", "string"); cmd.add(logpathArg); ValueArg<string> loginArg( "u", "username", "The name of a user that wishes to authenticate", false, "Basia", "string"); cmd.add(loginArg); ValueArg<string> passArg("", "password", "The password of a user", false, "password", "string"); cmd.add(passArg); /* SwitchArg interSwitch("i", "interactive", */ /* "Run in the interactive mode", false); */ /* cmd.add(interSwitch); */ SwitchArg verboseSwitch("v", "verbose", "Run in the verbose mode", false); cmd.add(verboseSwitch); ValueArg<string> secretArg("s", "secret", "The secret shared with NAS", true, "", "string"); cmd.add(secretArg); ValueArg<int> portArg("p", "port", "Binded port", false, 0, "number"); cmd.add(portArg); ValueArg<string> bindIpArg("b", "bind-ip", "Binded IP address", false, "0.0.0.0", "IP"); cmd.add(bindIpArg); ValueArg<string> ipArg("a", "address", "Server IP address", true, "", "IP"); cmd.add(ipArg); ValueArg<string> hashArg( "", "hash", "Type of hashing function (crc32 md5 sha1 sha256 sha3)", false, "sha256", "string"); cmd.add(hashArg); cmd.parse(argc, argv); int port = portArg.getValue(); string ip = ipArg.getValue(); string bindIp = ipArg.getValue(); string secret = secretArg.getValue(); string logpath = logpathArg.getValue(); radius::initLogger(logpath, LOGGER_NAME); bool verbose = verboseSwitch.getValue(); if (verbose) { spdlog::set_level(spdlog::level::trace); } auto logger = spdlog::get(LOGGER_NAME); string hash = hashArg.getValue(); string login = loginArg.getValue(); string pas = passArg.getValue(); /* bool inter = interSwitch.getValue(); */ // setup address structure //adres serwera struct sockaddr_in server_addr; memset((char *)&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); /* if (inter) { */ /* login = radius::getUsername(); */ /* pas = radius::getPassword("Enter password:\n"); */ /* } */ pas = hashString(pas, hash); // radius::packets::Packet newPack(temp, server_addr); radius::startClient(ip.c_str(), port); // 1.access-request using namespace radius; using namespace radius::packets; EapPacket eapIdentity; eapIdentity = makeIdentity(login); eapIdentity.setType(EapPacket::RESPONSE); eapIdentity.setIdentifier(1); EapMessage eapMessage; eapMessage.setValue(eapIdentity.getBuffer()); RadiusPacket arPacket; arPacket.setIdentifier(1); arPacket.setCode(RadiusPacket::ACCESS_REQUEST); std::array<radius::byte, 16> authTable = generateRandom16(); arPacket.setAuthenticator(authTable); arPacket.addAVP(static_cast<const RadiusAVP &>(eapMessage)); calcAndSetMsgAuth(arPacket, secret); radius::packets::Packet newPack(arPacket.getBuffer(), server_addr); logger->info() <<"Send Packet"; logger->info() <<"[Packet:]\n" << packet2LogBytes(newPack.bytes); logger->info() <<"[RadiusPacket:]\n"<< arPacket; logger->info() <<"[EapPacket:]\n"<< eapIdentity; radius::sendPack(newPack); // 2.otrzymuj odpowiedz od Radius server newPack = radius::receivePack(); RadiusPacket recArPacket(newPack.bytes); logger->info() <<"Received Packet"; logger->info() <<"[Packet:]\n" <<packet2LogBytes(recArPacket.getBuffer()); logger->info() <<"[RadiusPacket:]\n"<< recArPacket; EapPacket recEapIdentity = extractEapPacket(recArPacket); logger->info() <<"[EapPacket:]\n"<< recEapIdentity; std::array<radius::byte,16> chalArray =calcChalVal(recEapIdentity,secret); //make response EapPacket eapMd5Chal; eapMd5Chal = makeChallengeResp(chalArray); eapMd5Chal.setType(EapPacket::RESPONSE); eapMd5Chal.setIdentifier(2); EapMessage eapMessage2; eapMessage2.setValue(eapMd5Chal.getBuffer()); RadiusPacket responsePacket; responsePacket.setIdentifier(2); responsePacket.setCode(RadiusPacket::ACCESS_REQUEST); authTable = generateRandom16(); responsePacket.setAuthenticator(authTable); responsePacket.addAVP(static_cast<const RadiusAVP &>(eapMessage2)); calcAndSetMsgAuth(responsePacket, secret); radius::packets::Packet responsePack(responsePacket.getBuffer() , server_addr); logger->info() <<"Send Packet"; logger->info() <<"[Packet:]\n" << packet2LogBytes(responsePack.bytes); logger->info() <<"[RadiusPacket:]\n"<< responsePacket; logger->info() <<"[EapPacket:]\n"<< eapMd5Chal; radius::sendPack(responsePack); // 4.success or failure newPack = radius::receivePack(); newPack = radius::receivePack(); RadiusPacket sucArPacket(newPack.bytes); logger->info() <<"Received Packet"; logger->info() <<"[Packet:]\n" <<packet2LogBytes(sucArPacket.getBuffer()); logger->info() <<"[RadiusPacket:]\n"<< sucArPacket; EapPacket sucEapIdentity = extractEapPacket(recArPacket); logger->info() <<"[EapPacket:]\n"<< sucEapIdentity; if (newPack.bytes[0]==0x02) { logger->info() <<"ACCEPT"; } else { logger->info() <<"REJECT"; } radius::stopClient(); } catch (ArgException &e) { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; } } std::string hashString(std::string input, std::string hash) { std::string output; if (hash == "sha256") { SHA256 sha256; output = sha256(input); } else if (hash == "sha1") { SHA1 sha1; output = sha1(input); } else if (hash == "sha3") { SHA3 sha3; output = sha3(input); } else if (hash == "md5") { MD5 md5; output = md5(input); } else if (hash == "crc32") { CRC32 crc32; output = crc32(input); } else { output = input; } return output; } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -Oz -emit-llvm %s -o - | FileCheck %s -check-prefix=Oz // RUN: %clang_cc1 -O0 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O1 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O2 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O3 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -Os -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // Check that we set the minsize attribute on each function // when Oz optimization level is set. int test1() { return 42; // Oz: @{{.*}}test1{{.*}}minsize // Oz: ret // OTHER: @{{.*}}test1 // OTHER-NOT: minsize // OTHER: ret } int test2() { return 42; // Oz: @{{.*}}test2{{.*}}minsize // Oz: ret // OTHER: @{{.*}}test2 // OTHER-NOT: minsize // OTHER: ret } __attribute__((minsize)) int test3() { return 42; // Oz: @{{.*}}test3{{.*}}minsize // OTHER: @{{.*}}test3{{.*}}minsize } // Check that the minsize attribute is well propagated through // template instantiation template<typename T> __attribute__((minsize)) void test4(T arg) { return; } template void test4<int>(int arg); // Oz: define{{.*}}void @{{.*}}test4 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test4 // OTHER: minsize template void test4<float>(float arg); // Oz: define{{.*}}void @{{.*}}test4 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test4 // OTHER: minsize template<typename T> void test5(T arg) { return; } template void test5<int>(int arg); // Oz: define{{.*}}void @{{.*}}test5 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test5 // OTHER-NOT: minsize template void test5<float>(float arg); // Oz: define{{.*}}void @{{.*}}test5 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test5 // OTHER-NOT: minsize <commit_msg>Update test to not fail with attribute groups.<commit_after>// RUN: %clang_cc1 -Oz -emit-llvm %s -o - | FileCheck %s -check-prefix=Oz // RUN: %clang_cc1 -O0 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O1 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O2 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -O3 -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // RUN: %clang_cc1 -Os -emit-llvm %s -o - | FileCheck %s -check-prefix=OTHER // Check that we set the minsize attribute on each function // when Oz optimization level is set. int test1() { return 42; // Oz: @{{.*}}test1{{.*}}minsize // Oz: ret // OTHER: @{{.*}}test1 // OTHER-NOT: minsize // OTHER: ret } int test2() { return 42; // Oz: @{{.*}}test2{{.*}}minsize // Oz: ret // OTHER: @{{.*}}test2 // OTHER-NOT: minsize // OTHER: ret } __attribute__((minsize)) int test3() { return 42; // Oz: @{{.*}}test3{{.*}}minsize // OTHER: @{{.*}}test3{{.*}}minsize } // Check that the minsize attribute is well propagated through // template instantiation template<typename T> __attribute__((minsize)) void test4(T arg) { return; } template void test4<int>(int arg); // Oz: define{{.*}}void @{{.*}}test4 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test4 // OTHER: minsize template void test4<float>(float arg); // Oz: define{{.*}}void @{{.*}}test4 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test4 // OTHER: minsize template<typename T> void test5(T arg) { return; } template void test5<int>(int arg); // Oz: define{{.*}}void @{{.*}}test5 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test5 // OTHER-NOT: define{{.*}}void @{{.*}}test5{{.*}}minsize template void test5<float>(float arg); // Oz: define{{.*}}void @{{.*}}test5 // Oz: minsize // OTHER: define{{.*}}void @{{.*}}test5 // OTHER-NOT: define{{.*}}void @{{.*}}test5{{.*}}minsize <|endoftext|>
<commit_before>// Catch #include <catch.hpp> #include <catchExtension.hpp> // Mantella #include <mantella> class TestPrintable : public mant::Printable { public: std::string toString() const override { return "ThisIsTestPrintable"; } }; TEST_CASE("printable: Printable", "") { SECTION("Returns the specified class name.") { TestPrintable testPrintable; CHECK(testPrintable.toString() == "ThisIsTestPrintable"); } } TEST_CASE("string: to_string(Printable*)", "") { SECTION("Returns the specified class name.") { std::shared_ptr<mant::Printable> testPrintable = std::shared_ptr<mant::Printable>(new TestPrintable); CHECK(mant::to_string(testPrintable) == "ThisIsTestPrintable"); } } <commit_msg>Improved section notice<commit_after>// Catch #include <catch.hpp> #include <catchExtension.hpp> // Mantella #include <mantella> class TestPrintable : public mant::Printable { public: std::string toString() const override { return "ThisIsTestPrintable"; } }; TEST_CASE("Printable", "") { SECTION(".toString") { SECTION("Returns the expected class name.") { TestPrintable testPrintable; CHECK(testPrintable.toString() == "ThisIsTestPrintable"); } } } TEST_CASE("to_string", "") { SECTION("Returns the expected class name.") { std::shared_ptr<mant::Printable> testPrintable = std::shared_ptr<mant::Printable>(new TestPrintable); CHECK(mant::to_string(testPrintable) == "ThisIsTestPrintable"); } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <fstream> #include <ydsh/ydsh.h> #include <constant.h> #include <vm.h> #include "../test_common.h" #ifndef HISTORY_MOD_PATH #error "require HISTORY_MOD_PATH" #endif class HistoryTest : public ExpectOutput, public TempFileFactory { protected: DSState *state{nullptr}; public: HistoryTest() { this->state = DSState_create(); DSState_loadModule(this->state, HISTORY_MOD_PATH, DS_MOD_FULLPATH, nullptr); std::string value; value += '"'; value += this->tmpFileName; value += '"'; this->assignValue(VAR_HISTFILE, std::move(value)); } ~HistoryTest() override { DSState_delete(&this->state); } void setHistSize(unsigned int size, bool sync = true) { this->assignUintValue(VAR_HISTSIZE, size); if(sync) { this->addHistory(nullptr); } } void setHistFileSize(unsigned int size) { this->assignUintValue(VAR_HISTFILESIZE, size); } unsigned int historySize() { return DSState_lineEdit(this->state, DS_EDIT_HIST_SIZE, 0, nullptr); } const char *getHistory(unsigned int index) { const char *buf = nullptr; DSState_lineEdit(this->state, DS_EDIT_HIST_GET, index, &buf); return buf; } void setHistory(unsigned int index, const char *line) { DSState_lineEdit(this->state, DS_EDIT_HIST_SET, index, &line); } void delHistory(unsigned int index) { DSState_lineEdit(this->state, DS_EDIT_HIST_DEL, index, nullptr); } void addHistory(const char *value) { DSState_lineEdit(this->state, DS_EDIT_HIST_ADD, 0, &value); } void clearHistory() { DSState_lineEdit(this->state, DS_EDIT_HIST_CLEAR, 0, nullptr); } void loadHistory(const char *fileName = nullptr) { DSState_lineEdit(this->state, DS_EDIT_HIST_LOAD, 0, &fileName); } void saveHistory(const char *fileName = nullptr) { DSState_lineEdit(this->state, DS_EDIT_HIST_SAVE, 0, &fileName); } private: void assignValue(const char *varName, std::string &&value) { std::string str = "$"; str += varName; str += " = "; str += value; auto r = DSState_eval(this->state, "(dummy)", str.c_str(), str.size(), nullptr); ASSERT_TRUE(r == 0); } void assignUintValue(const char *varName, unsigned int value) { std::string str = std::to_string(value); this->assignValue(varName, std::move(str)); } }; #define DS_HISTFILESIZE_LIMIT ((unsigned int) 4096) TEST_F(HistoryTest, add) { this->setHistSize(2); this->addHistory("aaa"); this->addHistory("bbb"); ASSERT_EQ(2u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); this->addHistory("ccc"); ASSERT_EQ(2u, this->historySize()); ASSERT_STREQ("bbb", this->getHistory(0)); ASSERT_STREQ("ccc", this->getHistory(1)); ASSERT_EQ(nullptr, this->getHistory(100)); this->addHistory("ccc"); ASSERT_EQ(2u, this->historySize()); // null ASSERT_EQ(nullptr, this->getHistory(100)); } TEST_F(HistoryTest, set) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); ASSERT_EQ(2u, this->historySize()); this->setHistory(1, "ccc"); ASSERT_STREQ("ccc", this->getHistory(1)); this->setHistory(3, "ccc"); // do nothing, if out of range ASSERT_EQ(2u, this->historySize()); ASSERT_EQ(nullptr, this->getHistory(3)); this->setHistory(1000, "ccc"); // do nothing, if out of range ASSERT_EQ(2u, this->historySize()); } TEST_F(HistoryTest, remove) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); this->addHistory("ccc"); this->addHistory("ddd"); this->addHistory("eee"); this->delHistory(2); ASSERT_EQ(4u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); ASSERT_STREQ("eee", this->getHistory(3)); this->delHistory(3); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); // do nothing, if out of range this->delHistory(6); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); // do nothing, if out of range this->delHistory(600); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); } TEST_F(HistoryTest, clear) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); this->addHistory("ccc"); this->addHistory("ddd"); this->addHistory("eee"); ASSERT_EQ(5u, this->historySize()); this->clearHistory(); ASSERT_EQ(0u, this->historySize()); } TEST_F(HistoryTest, resize) { this->setHistSize(10); for(unsigned int i = 0; i < 10; i++) { this->addHistory(std::to_string(i).c_str()); } ASSERT_EQ(10u, this->historySize()); this->setHistSize(5); ASSERT_EQ(5u, this->historySize()); ASSERT_STREQ("0", this->getHistory(0)); ASSERT_STREQ("1", this->getHistory(1)); ASSERT_STREQ("2", this->getHistory(2)); ASSERT_STREQ("3", this->getHistory(3)); ASSERT_STREQ("4", this->getHistory(4)); } TEST_F(HistoryTest, file) { this->setHistSize(10); for(unsigned int i = 0; i < 10; i++) { this->addHistory(std::to_string(i).c_str()); } this->setHistFileSize(15); /** * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 */ this->saveHistory(); this->clearHistory(); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i), this->getHistory(i)); } for(unsigned int i = 0; i < 5; i++) { this->addHistory(std::to_string(i + 10).c_str()); } for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } /** * previous hist file content * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 * * newly added content * 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 * * current hist file content * 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 */ this->saveHistory(); this->clearHistory(); this->setHistSize(15); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } // not overwrite history file when buffer size is 0 this->clearHistory(); this->saveHistory(); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } // not overwrite history file when hist file size is 0 this->setHistFileSize(0); this->clearHistory(); this->addHistory("hoge"); this->saveHistory(); this->loadHistory(); ASSERT_EQ(11u, this->historySize()); ASSERT_STREQ("hoge", this->getHistory(0)); for(unsigned int i = 1; i < 11; i++) { ASSERT_EQ(std::to_string(i + 4), this->getHistory(i)); } } TEST_F(HistoryTest, file2) { this->setHistFileSize(DS_HISTFILESIZE_LIMIT + 10); this->setHistSize(DS_HISTFILESIZE_LIMIT); for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) { this->addHistory(std::to_string(i).c_str()); } ASSERT_EQ(DS_HISTFILESIZE_LIMIT, this->historySize()); this->saveHistory(); this->clearHistory(); this->loadHistory(); ASSERT_EQ(DS_HISTFILESIZE_LIMIT, this->historySize()); for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) { ASSERT_EQ(std::to_string(i), this->getHistory(i)); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>update history test case<commit_after>#include "gtest/gtest.h" #include <fstream> #include <ydsh/ydsh.h> #include <constant.h> #include <vm.h> #include "../test_common.h" #ifndef HISTORY_MOD_PATH #error "require HISTORY_MOD_PATH" #endif class HistoryTest : public ExpectOutput, public TempFileFactory { protected: DSState *state{nullptr}; public: HistoryTest() { this->state = DSState_create(); DSState_loadModule(this->state, HISTORY_MOD_PATH, DS_MOD_FULLPATH, nullptr); std::string value; value += '"'; value += this->tmpFileName; value += '"'; this->assignValue(VAR_HISTFILE, std::move(value)); } ~HistoryTest() override { DSState_delete(&this->state); } void setHistSize(unsigned int size, bool sync = true) { this->assignUintValue(VAR_HISTSIZE, size); if(sync) { this->addHistory(nullptr); } } void setHistFileSize(unsigned int size) { this->assignUintValue(VAR_HISTFILESIZE, size); } unsigned int historySize() { return DSState_lineEdit(this->state, DS_EDIT_HIST_SIZE, 0, nullptr); } const char *getHistory(unsigned int index) { const char *buf = nullptr; DSState_lineEdit(this->state, DS_EDIT_HIST_GET, index, &buf); return buf; } void setHistory(unsigned int index, const char *line) { DSState_lineEdit(this->state, DS_EDIT_HIST_SET, index, &line); } void delHistory(unsigned int index) { DSState_lineEdit(this->state, DS_EDIT_HIST_DEL, index, nullptr); } void addHistory(const char *value) { DSState_lineEdit(this->state, DS_EDIT_HIST_ADD, 0, &value); } void clearHistory() { DSState_lineEdit(this->state, DS_EDIT_HIST_CLEAR, 0, nullptr); } void loadHistory(const char *fileName = nullptr) { DSState_lineEdit(this->state, DS_EDIT_HIST_LOAD, 0, &fileName); } void saveHistory(const char *fileName = nullptr) { DSState_lineEdit(this->state, DS_EDIT_HIST_SAVE, 0, &fileName); } private: void assignValue(const char *varName, std::string &&value) { std::string str = "$"; str += varName; str += " = "; str += value; auto r = DSState_eval(this->state, "(dummy)", str.c_str(), str.size(), nullptr); ASSERT_TRUE(r == 0); } void assignUintValue(const char *varName, unsigned int value) { std::string str = std::to_string(value); this->assignValue(varName, std::move(str)); } }; #define DS_HISTFILESIZE_LIMIT ((unsigned int) 4096) TEST_F(HistoryTest, add) { this->setHistSize(2); this->addHistory("aaa"); this->addHistory("bbb"); ASSERT_EQ(2u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); this->addHistory("ccc"); ASSERT_EQ(2u, this->historySize()); ASSERT_STREQ("bbb", this->getHistory(0)); ASSERT_STREQ("ccc", this->getHistory(1)); ASSERT_EQ(nullptr, this->getHistory(100)); this->addHistory("ccc"); ASSERT_EQ(2u, this->historySize()); // null ASSERT_EQ(nullptr, this->getHistory(100)); } TEST_F(HistoryTest, set) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); ASSERT_EQ(2u, this->historySize()); this->setHistory(1, "ccc"); ASSERT_STREQ("ccc", this->getHistory(1)); this->setHistory(3, "ccc"); // do nothing, if out of range ASSERT_EQ(2u, this->historySize()); ASSERT_EQ(nullptr, this->getHistory(3)); this->setHistory(1000, "ccc"); // do nothing, if out of range ASSERT_EQ(2u, this->historySize()); } TEST_F(HistoryTest, remove) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); this->addHistory("ccc"); this->addHistory("ddd"); this->addHistory("eee"); this->delHistory(2); ASSERT_EQ(4u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); ASSERT_STREQ("eee", this->getHistory(3)); this->delHistory(3); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); // do nothing, if out of range this->delHistory(6); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); // do nothing, if out of range this->delHistory(600); ASSERT_EQ(3u, this->historySize()); ASSERT_STREQ("aaa", this->getHistory(0)); ASSERT_STREQ("bbb", this->getHistory(1)); ASSERT_STREQ("ddd", this->getHistory(2)); } TEST_F(HistoryTest, clear) { this->setHistSize(10); this->addHistory("aaa"); this->addHistory("bbb"); this->addHistory("ccc"); this->addHistory("ddd"); this->addHistory("eee"); ASSERT_EQ(5u, this->historySize()); this->clearHistory(); ASSERT_EQ(0u, this->historySize()); } TEST_F(HistoryTest, resize) { this->setHistSize(10); for(unsigned int i = 0; i < 10; i++) { this->addHistory(std::to_string(i).c_str()); } ASSERT_EQ(10u, this->historySize()); this->setHistSize(5); ASSERT_EQ(5u, this->historySize()); ASSERT_STREQ("0", this->getHistory(0)); ASSERT_STREQ("1", this->getHistory(1)); ASSERT_STREQ("2", this->getHistory(2)); ASSERT_STREQ("3", this->getHistory(3)); ASSERT_STREQ("4", this->getHistory(4)); } TEST_F(HistoryTest, file) { this->setHistSize(10); for(unsigned int i = 0; i < 10; i++) { this->addHistory(std::to_string(i).c_str()); } this->setHistFileSize(15); /** * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 */ this->saveHistory(); this->clearHistory(); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i), this->getHistory(i)); } for(unsigned int i = 0; i < 5; i++) { this->addHistory(std::to_string(i + 10).c_str()); } for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } /** * previous hist file content * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 * * newly added content * 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 * * current hist file content * 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 */ this->saveHistory(); this->clearHistory(); this->setHistSize(15); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } // not overwrite history file when buffer size is 0 this->clearHistory(); this->saveHistory(); this->loadHistory(); ASSERT_EQ(10u, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i + 5), this->getHistory(i)); } // not overwrite history file when hist file size is 0 this->setHistFileSize(0); this->clearHistory(); this->addHistory("hoge"); this->saveHistory(); this->loadHistory(); ASSERT_EQ(11u, this->historySize()); ASSERT_STREQ("hoge", this->getHistory(0)); for(unsigned int i = 1; i < 11; i++) { ASSERT_EQ(std::to_string(i + 4), this->getHistory(i)); } } TEST_F(HistoryTest, file2) { this->setHistFileSize(DS_HISTFILESIZE_LIMIT + 10); this->setHistSize(DS_HISTFILESIZE_LIMIT); for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) { this->addHistory(std::to_string(i).c_str()); } ASSERT_EQ(DS_HISTFILESIZE_LIMIT, this->historySize()); this->saveHistory(); this->clearHistory(); this->loadHistory(); ASSERT_EQ(DS_HISTFILESIZE_LIMIT, this->historySize()); for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) { ASSERT_EQ(std::to_string(i), this->getHistory(i)); } } TEST_F(HistoryTest, file3) { this->setHistSize(10); for(unsigned int i = 0; i < 10; i++) { this->addHistory(std::to_string(i).c_str()); } this->setHistFileSize(15); std::string fileName = this->getTempDirName(); fileName += "/hogehogehgoe"; this->saveHistory(fileName.c_str()); this->clearHistory(); this->loadHistory(fileName.c_str()); ASSERT_EQ(10, this->historySize()); for(unsigned int i = 0; i < 10; i++) { ASSERT_EQ(std::to_string(i), this->getHistory(i)); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>/* Author : David Barnett Date : 03-10-2013 License: MIT License */ #include "Settings.h" #include <iosfwd> #include <iostream> using namespace IO; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sstream> #include <algorithm> #include <iterator> #include "../etc/string.h" //#define SETTINGS_VERBOSE Settings::Settings() { this->loading_flag = SETTING_LOAD_NOTHING; } Settings::Settings(SettingsLoadFlags flag) { this->loading_flag = flag; } Settings::~Settings() { this->stored_settings.clear(); } /** * @brief removes all currently loaded settings */ void Settings::clear() { this->stored_settings.clear(); } /** * @brief Checks if a given setting exists, and loads it if flags permit * @param header section header * @param key name of the setting to be accessed * @return true on exists */ bool Settings::exists (std::string header ,std::string key) { if (this->exists(header)) { INISection* section = &(this->stored_settings[header]); if (section->loaded) { return section->properties.find(key) != section->properties.end(); } else { //Load Header's properties? if ( this->loading_flag == SETTING_LOAD_ON_REQUEST ) { this->load_section ( header , SETTINGS_DUPLICATES_INGORED ); return this->exists ( header , key); } else { return false; } } } else { return false; } } /** * @brief Checks if a header exits * @param header Name of section * @return true on success */ bool Settings::exists (std::string header) { return this->stored_settings.find(header) != this->stored_settings.end(); } /** * @brief Loads settings from a file * @param file_name * @param flag */ void Settings::load(std::string file_name , SettingsDuplicateFlags flag) { #ifdef SETTINGS_VERBOSE std::cout << "Loading " << file_name << std::endl; #endif std::fstream file; file.open(file_name.c_str()); this->file_name = file_name; //Check if the file is open if (!(file.is_open())) { return; } //Seek to the beginning of the file file.seekg( 0 , file.beg ); file.peek(); //Calculate the offset from the 1st byte to the 0th element int sys_error = file.tellg(); std::string line; INISection section; section.header_name = ""; section.loaded = false; section.start_index = 0; #ifdef SETTINGS_VERBOSE std::cout << "sys error is " << sys_error << " Pos " << file.tellg() << std::endl; std::cout << "root S:" << section.start_index; #endif while ( ! file.eof() ) { //Get current position with the sys error offset int start_pos = (int)(file.tellg()) - sys_error; std::getline( file , line ); if (line.length() == 0) continue; line = etc::trim(line); //Treat lines starting with ; as comments and do not process if ( etc::startswith( line , ";" ) ) { continue; } //Check if the line has the beginning of a section if (etc::startswith( line , "[" ) && etc::endswith( line , "]" )) { //Close last section section.end_index = (int)file.tellg(); this->stored_settings[section.header_name] = section; #ifdef SETTINGS_VERBOSE std::cout << " E:" << section.end_index << std::endl; #endif //Refresh section section = INISection(); //Remove the brackets section.header_name = line.substr ( 1 , line.size() - 2 ); if ( this->exists(section.header_name)) { //Warning text std::cout << "ERROR : Another " << this->file_name << "::" << section.header_name << " has been defined!\nSections will be damaged." << std::endl; } else { //-2 constant is to correct the position of the start index section.start_index = start_pos ; section.loaded = false; section.properties = SettingsMap(); #ifdef SETTINGS_VERBOSE std::cout << section.header_name << " S:" << section.start_index; #endif } continue; } } file.seekg (0 , file.end); section.end_index = (int)file.tellg() - sys_error; this->stored_settings[section.header_name] = section; #ifdef SETTINGS_VERBOSE std::cout << " E:" << section.end_index << std::endl; #endif file.close(); } /** * @brief Loads a section's data into memory * @param header Section name * @param flag Settings Duplicate Flags */ void Settings::load_section ( std::string header , SettingsDuplicateFlags flag) { std::fstream file; if (this->exists(header) == false) return; INISection* section = &(this->stored_settings[header]); file.open( this->file_name.c_str() ); int file_pos_max = section->end_index; //Check if the file is open if (!(file.is_open())) { return; } //Seek to the beginning of the file file.seekg( 0 , file.beg ); file.peek(); file.seekg( section->start_index , file.beg ); bool start = false; while ( file.tellg() < file_pos_max && !file.eof() ) { std::string line; std::getline ( file, line ); line = etc::trim ( line ); if (line == "") { continue; } if ( etc::startswith( line , ";" ) ) { continue; } //Check if the line has the beginning of a section if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") ) { std::string header_name = line.substr ( 1 , line.size() - 2 ); //If another section is in contact, LEAVE NOW if (header_name != section->header_name) { break; } else { //Found the start of the section we are looking for start = true; } continue; } if (start == false) { continue; } //Find the equal part of the line std::size_t equal_pos = line.find_first_of('=', 0); if (equal_pos == line.npos) { continue; } std::string key = etc::trim ( line.substr( 0 , equal_pos ) ); std::string value = etc::trim ( line.substr( equal_pos + 1 , line.length() - 1 ) ); if (key == "") { continue; } if ( section->properties.find( key ) != section->properties.end() ) { //There is another copy of the key, check if it is OK to override if (flag == SETTINGS_DUPLICATES_OVERRIDE) { section->properties[key] = value; } } else { section->properties[key] = value; #ifdef SETTINGS_VERBOSE std::cout << section->header_name << "::" << key << "=" << value << std::endl; #endif } } //Update loaded status section->loaded = true; file.close(); } /** * @brief Unloads a specified section * @param header a section name */ void Settings::unload_section (std::string header) { if (this->exists(header)) { this->stored_settings[header].properties.clear(); this->stored_settings[header].loaded = false; } } /** * @brief Gets the string of the given setting and copies it into the out string * @param header the name of the section * @param key the name of setting * @param out A string to be written to * @return true on successful copy */ bool Settings::get (std::string header , std::string key, std::string* out) { if (this->exists(header ,key)) { *out = this->stored_settings[header].properties[key]; return true; } else { return false; } } /** * @brief Gets the value and converts it to a bool * @see Settings::get * @param bol Returns the value * @return */ bool Settings::getBool (std::string header , std::string key , bool* bol) { std::string b; if (this->get(header, key , &b) == false) return false; b = etc::toLower(b); if (b != "") { *bol = ( b == "true" ? true : false ); return true; } else { return false; } } bool Settings::getInt (std::string header , std::string key , int* num) { std::string b; if (this->get(header, key , &b) == false) return false; if ( etc::is_number(b) ) { *num = atoi( b.c_str() ); return true; } else { return false; } } bool Settings::add (std::string header , std::string key , std::string value) { if (!this->exists(header , key)) { this->stored_settings[header].properties[key] = value; return true; } else { return false; } } bool Settings::set (std::string header , std::string key , std::string value) { if (this->exists( header , key ) ) { this->stored_settings[header].properties[key] = value; return true; } return false; } /** * @brief Saves all the sections of a given file * @warning Deletes original file and then renames a temp file to replace it * @param filename Saves all headers that belong to a file * @return bool true on success */ bool Settings::save () { //The File to be read from std::ifstream file_in; //The File to be written to std::fstream file_out; //Stream are separate to prevent cross-contamination //Open the input file file_in.open( this->file_name.c_str() ); //Check for errors if (file_in.is_open() == false) { std::cout << "Error input file : " << this->file_name.c_str() << " could not be opened." << std::endl; return false; } //Open the output file file_out.open( ("temp~" + this->file_name).c_str() , std::ofstream::out ); //Check for errors if (file_out.is_open() == false) { std::cout << "Error output file : " << ("temp~" + this->file_name).c_str() << " could not be opened." << std::endl; return false; } //Go through whole file INISection* current_section = &(this->stored_settings[""]); while ( file_in.eof() == false ) { std::string line; std::getline ( file_in , line ); line = etc::trim ( line ); std::size_t equal_pos = line.find_first_of('=', 0); if (line == "") { } else if ( etc::startswith( line , ";" ) ) { } else if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") ) { //Check if the line has the beginning of a section //Update current_section if (current_section != nullptr) { current_section->end_index = file_out.tellg(); } current_section = &( this->stored_settings[ line.substr ( 1 , line.size() - 2 )] ); current_section->start_index = (int)file_out.tellg() - 1; } else if (equal_pos != line.npos) { std::string key = etc::trim ( line.substr( 0 , equal_pos ) ); std::string value = current_section->properties[key]; if (value == "") { value = etc::trim ( line.substr( equal_pos + 1 , line.length() - 1 ) ); } file_out << key << '=' << value << std::endl; continue; } //Standard copy line out file_out << line << std::endl; } file_out.close(); file_in.close(); //File operations //File operation return value int file_op = 0; //Remove old version file_op = std::remove( this->file_name.c_str() ); //Check if there was an error if (file_op != 0) { std::cout << "Error while removing the file " << this->file_name.c_str() << std::endl; return false; } //Rename the temp version to replace the deleted version file_op = std::rename( ("temp~" + this->file_name).c_str() , this->file_name.c_str() ); //Check if there was an error if (file_op != 0) { std::cout << "Error while renaming the file from " << ("temp~" + this->file_name).c_str() << " to " << this->file_name.c_str() << std::endl; return false; } return true; } <commit_msg>Settings Fix * Fixed bug where the last section had incorrect ending index * Added build option SETTINGS_VERBOOSE for console output of settings loading Conflicts: io/Settings.cpp<commit_after>/* Author : David Barnett Date : 03-10-2013 License: MIT License */ #include "Settings.h" #include <iosfwd> #include <iostream> using namespace IO; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sstream> #include <algorithm> #include <iterator> #include "../etc/string.h" //#define SETTINGS_VERBOSE Settings::Settings() { this->loading_flag = SETTING_LOAD_NOTHING; } Settings::Settings(SettingsLoadFlags flag) { this->loading_flag = flag; } Settings::~Settings() { this->stored_settings.clear(); } /** * @brief removes all currently loaded settings */ void Settings::clear() { this->stored_settings.clear(); } /** * @brief Checks if a given setting exists, and loads it if flags permit * @param header section header * @param key name of the setting to be accessed * @return true on exists */ bool Settings::exists (std::string header ,std::string key) { if (this->exists(header)) { INISection* section = &(this->stored_settings[header]); if (section->loaded) { return section->properties.find(key) != section->properties.end(); } else { //Load Header's properties? if ( this->loading_flag == SETTING_LOAD_ON_REQUEST ) { this->load_section ( header , SETTINGS_DUPLICATES_INGORED ); return this->exists ( header , key); } else { return false; } } } else { return false; } } /** * @brief Checks if a header exits * @param header Name of section * @return true on success */ bool Settings::exists (std::string header) { return this->stored_settings.find(header) != this->stored_settings.end(); } /** * @brief Loads settings from a file * @param file_name * @param flag */ void Settings::load(std::string file_name , SettingsDuplicateFlags flag) { <<<<<<< HEAD #ifdef SETTINGS_VERBOSE ======= #ifdef SETTINGS_VERBOOSE >>>>>>> 86e3c99... Settings Fix std::cout << "Loading " << file_name << std::endl; #endif std::fstream file; file.open(file_name.c_str()); this->file_name = file_name; //Check if the file is open if (!(file.is_open())) { return; } //Seek to the beginning of the file file.seekg( 0 , file.beg ); file.peek(); //Calculate the offset from the 1st byte to the 0th element int sys_error = file.tellg(); file.seekg( 0, file.end ); int file_size = (int)file.tellg(); file.seekg( 0, file.beg ); std::string line; INISection section; section.header_name = ""; section.loaded = false; section.start_index = 0; <<<<<<< HEAD #ifdef SETTINGS_VERBOSE ======= #ifdef SETTINGS_VERBOOSE >>>>>>> 86e3c99... Settings Fix std::cout << "sys error is " << sys_error << " Pos " << file.tellg() << std::endl; std::cout << "root S:" << section.start_index; #endif while ( ! file.eof() ) { //Get current position with the sys error offset int start_pos = (int)(file.tellg()) - sys_error; std::getline( file , line ); if (line.length() == 0) continue; line = etc::trim(line); //Treat lines starting with ; as comments and do not process if ( etc::startswith( line , ";" ) ) { continue; } //Check if the line has the beginning of a section if (etc::startswith( line , "[" ) && etc::endswith( line , "]" )) { //Close last section section.end_index = (int)file.tellg(); this->stored_settings[section.header_name] = section; <<<<<<< HEAD #ifdef SETTINGS_VERBOSE std::cout << " E:" << section.end_index << std::endl; #endif ======= #ifdef SETTINGS_VERBOOSE std::cout << " E:" << section.end_index << std::endl; #endif >>>>>>> 86e3c99... Settings Fix //Refresh section section = INISection(); //Remove the brackets section.header_name = line.substr ( 1 , line.size() - 2 ); if ( this->exists(section.header_name)) { //Warning text std::cout << "ERROR : Another " << this->file_name << "::" << section.header_name << " has been defined!\nSections will be damaged." << std::endl; } else { //-2 constant is to correct the position of the start index section.start_index = start_pos ; section.loaded = false; section.properties = SettingsMap(); <<<<<<< HEAD #ifdef SETTINGS_VERBOSE std::cout << section.header_name << " S:" << section.start_index; #endif ======= #ifdef SETTINGS_VERBOOSE std::cout << section.header_name << " S:" << section.start_index; #endif >>>>>>> 86e3c99... Settings Fix } continue; } } section.end_index = file_size; this->stored_settings[section.header_name] = section; <<<<<<< HEAD #ifdef SETTINGS_VERBOSE std::cout << " E:" << section.end_index << std::endl; #endif ======= #ifdef SETTINGS_VERBOOSE std::cout << " E:" << section.end_index << std::endl; #endif >>>>>>> 86e3c99... Settings Fix file.close(); } /** * @brief Loads a section's data into memory * @param header Section name * @param flag Settings Duplicate Flags */ void Settings::load_section ( std::string header , SettingsDuplicateFlags flag) { std::fstream file; if (this->exists(header) == false) return; INISection* section = &(this->stored_settings[header]); file.open( this->file_name.c_str() ); int file_pos_max = section->end_index; //Check if the file is open if (!(file.is_open())) { return; } //Seek to the beginning of the file file.seekg( 0 , file.beg ); file.peek(); file.seekg( section->start_index , file.beg ); bool start = false; while ( file.tellg() < file_pos_max && !file.eof() ) { std::string line; std::getline ( file, line ); line = etc::trim ( line ); if (line == "") { continue; } if ( etc::startswith( line , ";" ) ) { continue; } //Check if the line has the beginning of a section if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") ) { std::string header_name = line.substr ( 1 , line.size() - 2 ); //If another section is in contact, LEAVE NOW if (header_name != section->header_name) { break; } else { //Found the start of the section we are looking for start = true; } continue; } if (start == false) { continue; } //Find the equal part of the line std::size_t equal_pos = line.find_first_of('=', 0); if (equal_pos == line.npos) { continue; } std::string key = etc::trim ( line.substr( 0 , equal_pos ) ); std::string value = etc::trim ( line.substr( equal_pos + 1 , line.length() - 1 ) ); if (key == "") { continue; } if ( section->properties.find( key ) != section->properties.end() ) { //There is another copy of the key, check if it is OK to override if (flag == SETTINGS_DUPLICATES_OVERRIDE) { section->properties[key] = value; } } else { section->properties[key] = value; <<<<<<< HEAD #ifdef SETTINGS_VERBOSE ======= #ifdef SETTINGS_VERBOOSE >>>>>>> 86e3c99... Settings Fix std::cout << section->header_name << "::" << key << "=" << value << std::endl; #endif } } //Update loaded status section->loaded = true; file.close(); } /** * @brief Unloads a specified section * @param header a section name */ void Settings::unload_section (std::string header) { if (this->exists(header)) { this->stored_settings[header].properties.clear(); this->stored_settings[header].loaded = false; } } /** * @brief Gets the string of the given setting and copies it into the out string * @param header the name of the section * @param key the name of setting * @param out A string to be written to * @return true on successful copy */ bool Settings::get (std::string header , std::string key, std::string* out) { if (this->exists(header ,key)) { *out = this->stored_settings[header].properties[key]; return true; } else { return false; } } /** * @brief Gets the value and converts it to a bool * @see Settings::get * @param bol Returns the value * @return */ bool Settings::getBool (std::string header , std::string key , bool* bol) { std::string b; if (this->get(header, key , &b) == false) return false; b = etc::toLower(b); if (b != "") { *bol = ( b == "true" ? true : false ); return true; } else { return false; } } bool Settings::getInt (std::string header , std::string key , int* num) { std::string b; if (this->get(header, key , &b) == false) return false; if ( etc::is_number(b) ) { *num = atoi( b.c_str() ); return true; } else { return false; } } bool Settings::add (std::string header , std::string key , std::string value) { if (!this->exists(header , key)) { this->stored_settings[header].properties[key] = value; return true; } else { return false; } } bool Settings::set (std::string header , std::string key , std::string value) { if (this->exists( header , key ) ) { this->stored_settings[header].properties[key] = value; return true; } return false; } /** * @brief Saves all the sections of a given file * @warning Deletes original file and then renames a temp file to replace it * @param filename Saves all headers that belong to a file * @return bool true on success */ bool Settings::save () { //The File to be read from std::ifstream file_in; //The File to be written to std::fstream file_out; //Stream are separate to prevent cross-contamination //Open the input file file_in.open( this->file_name.c_str() ); //Check for errors if (file_in.is_open() == false) { std::cout << "Error input file : " << this->file_name.c_str() << " could not be opened." << std::endl; return false; } //Open the output file file_out.open( ("temp~" + this->file_name).c_str() , std::ofstream::out ); //Check for errors if (file_out.is_open() == false) { std::cout << "Error output file : " << ("temp~" + this->file_name).c_str() << " could not be opened." << std::endl; return false; } //Go through whole file INISection* current_section = &(this->stored_settings[""]); while ( file_in.eof() == false ) { std::string line; std::getline ( file_in , line ); line = etc::trim ( line ); std::size_t equal_pos = line.find_first_of('=', 0); if (line == "") { } else if ( etc::startswith( line , ";" ) ) { } else if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") ) { //Check if the line has the beginning of a section //Update current_section if (current_section != nullptr) { current_section->end_index = file_out.tellg(); } current_section = &( this->stored_settings[ line.substr ( 1 , line.size() - 2 )] ); current_section->start_index = (int)file_out.tellg() - 1; } else if (equal_pos != line.npos) { std::string key = etc::trim ( line.substr( 0 , equal_pos ) ); std::string value = current_section->properties[key]; if (value == "") { value = etc::trim ( line.substr( equal_pos + 1 , line.length() - 1 ) ); } file_out << key << '=' << value << std::endl; continue; } //Standard copy line out file_out << line << std::endl; } file_out.close(); file_in.close(); //File operations //File operation return value int file_op = 0; //Remove old version file_op = std::remove( this->file_name.c_str() ); //Check if there was an error if (file_op != 0) { std::cout << "Error while removing the file " << this->file_name.c_str() << std::endl; return false; } //Rename the temp version to replace the deleted version file_op = std::rename( ("temp~" + this->file_name).c_str() , this->file_name.c_str() ); //Check if there was an error if (file_op != 0) { std::cout << "Error while renaming the file from " << ("temp~" + this->file_name).c_str() << " to " << this->file_name.c_str() << std::endl; return false; } return true; } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Genre.h" #include "Album.h" #include "AlbumTrack.h" #include "Artist.h" #include "Media.h" #include "database/SqliteQuery.h" namespace medialibrary { const std::string Genre::Table::Name = "Genre"; const std::string Genre::Table::PrimaryKeyColumn = "id_genre"; int64_t Genre::* const Genre::Table::PrimaryKey = &Genre::m_id; const std::string Genre::FtsTable::Name = "GenreFts"; Genre::Genre( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_name( row.extract<decltype(m_name)>() ) , m_nbTracks( row.extract<decltype(m_nbTracks)>() ) , m_nbPresentTracks( row.extract<decltype(m_nbPresentTracks)>() ) { assert( row.hasRemainingColumns() == false ); } Genre::Genre( MediaLibraryPtr ml, std::string name ) : m_ml( ml ) , m_id( 0 ) , m_name( std::move( name ) ) , m_nbTracks( 0 ) , m_nbPresentTracks( 0 ) { } int64_t Genre::id() const { return m_id; } const std::string& Genre::name() const { return m_name; } uint32_t Genre::nbTracks() const { return m_nbTracks; } uint32_t Genre::nbPresentTracks() const { return m_nbPresentTracks; } void Genre::updateCachedNbTracks( int increment ) { m_nbTracks += increment; } Query<IArtist> Genre::artists( const QueryParameters* params ) const { std::string req = "FROM " + Artist::Table::Name + " a " "INNER JOIN " + AlbumTrack::Table::Name + " att ON att.artist_id = a.id_artist " "WHERE att.genre_id = ?"; std::string groupAndOrderBy = "GROUP BY att.artist_id ORDER BY a.name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) groupAndOrderBy += " DESC"; } return make_query<Artist, IArtist>( m_ml, "a.*", std::move( req ), std::move( groupAndOrderBy ), m_id ); } Query<IArtist> Genre::searchArtists( const std::string& pattern, const QueryParameters* params ) const { return Artist::searchByGenre( m_ml, pattern, params, m_id ); } Query<IMedia> Genre::tracks( TracksIncluded included, const QueryParameters* params ) const { return AlbumTrack::fromGenre( m_ml, m_id, included, params ); } Query<IMedia> Genre::searchTracks( const std::string& pattern, const QueryParameters* params ) const { return Media::searchGenreTracks( m_ml, pattern, m_id, params ); } Query<IAlbum> Genre::albums( const QueryParameters* params ) const { return Album::fromGenre( m_ml, m_id, params ); } Query<IAlbum> Genre::searchAlbums( const std::string& pattern, const QueryParameters* params ) const { return Album::searchFromGenre( m_ml, pattern, m_id, params ); } const std::string&Genre::thumbnailMrl( ThumbnailSizeType sizeType ) const { const auto t = thumbnail( sizeType ); if ( t == nullptr ) return Thumbnail::EmptyMrl; return t->mrl(); } bool Genre::hasThumbnail( ThumbnailSizeType sizeType ) const { if ( m_thumbnails[Thumbnail::SizeToInt( sizeType )] != nullptr ) return true; return thumbnail( sizeType ) != nullptr; } bool Genre::shouldUpdateThumbnail( const Thumbnail& oldThumbnail ) { return oldThumbnail.isShared() == false; } bool Genre::setThumbnail( const std::string& mrl, ThumbnailSizeType sizeType, bool takeOwnership ) { auto thumbnailIdx = Thumbnail::SizeToInt( sizeType ); auto currentThumbnail = thumbnail( sizeType ); auto newThumbnail = std::make_shared<Thumbnail>( m_ml, mrl, Thumbnail::Origin::UserProvided, sizeType, false ); currentThumbnail = Thumbnail::updateOrReplace( m_ml, currentThumbnail, newThumbnail, Genre::shouldUpdateThumbnail, m_id, Thumbnail::EntityType::Genre ); if ( currentThumbnail == nullptr ) return false; m_thumbnails[thumbnailIdx] = std::move( currentThumbnail ); if ( takeOwnership == true ) m_thumbnails[thumbnailIdx]->relocate(); return true; } std::shared_ptr<Thumbnail> Genre::thumbnail( ThumbnailSizeType sizeType ) const { auto idx = Thumbnail::SizeToInt( sizeType ); if ( m_thumbnails[idx] == nullptr ) { auto thumbnail = Thumbnail::fetch( m_ml, Thumbnail::EntityType::Genre, m_id, sizeType ); if ( thumbnail == nullptr ) return nullptr; m_thumbnails[idx] = std::move( thumbnail ); } return m_thumbnails[idx]; } void Genre::createTable( sqlite::Connection* dbConn ) { const std::string reqs[] = { schema( Table::Name, Settings::DbModelVersion ), schema( FtsTable::Name, Settings::DbModelVersion ), }; for ( const auto& req : reqs ) sqlite::Tools::executeRequest( dbConn, req ); } void Genre::createTriggers( sqlite::Connection* dbConn ) { sqlite::Tools::executeRequest( dbConn, trigger( Triggers::InsertFts, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::DeleteFts, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateOnNewTrack, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateOnTrackDelete, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateIsPresent, Settings::DbModelVersion ) ); } std::string Genre::schema( const std::string& tableName, uint32_t dbModel ) { if ( tableName == FtsTable::Name ) { return "CREATE VIRTUAL TABLE " + FtsTable::Name + " USING FTS3(name)"; } assert( tableName == Table::Name ); if ( dbModel < 30 ) { return "CREATE TABLE " + Table::Name + "(" "id_genre INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "nb_tracks INTEGER NOT NULL DEFAULT 0" ")"; } return "CREATE TABLE " + Table::Name + "(" "id_genre INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "nb_tracks INTEGER NOT NULL DEFAULT 0," "is_present INTEGER NOT NULL DEFAULT 0 " "CHECK(is_present <= nb_tracks)" ")"; } std::string Genre::trigger( Triggers trigger, uint32_t dbModel ) { switch ( trigger ) { case Triggers::InsertFts: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER INSERT ON " + Table::Name + " BEGIN" " INSERT INTO " + FtsTable::Name + "(rowid,name)" " VALUES(new.id_genre, new.name);" " END"; case Triggers::DeleteFts: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " BEFORE DELETE ON " + Table::Name + " BEGIN" " DELETE FROM " + FtsTable::Name + " WHERE rowid = old.id_genre;" " END"; case Triggers::UpdateOnNewTrack: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER INSERT ON " + AlbumTrack::Table::Name + " WHEN new.genre_id IS NOT NULL" " BEGIN" " UPDATE " + Table::Name + " SET nb_tracks = nb_tracks + 1," " is_present = is_present + 1" " WHERE id_genre = new.genre_id;" " END"; case Triggers::UpdateOnTrackDelete: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER DELETE ON " + AlbumTrack::Table::Name + " WHEN old.genre_id IS NOT NULL" " BEGIN" " UPDATE " + Table::Name + " SET nb_tracks = nb_tracks - 1," " is_present = is_present - 1" " WHERE id_genre = old.genre_id;" " DELETE FROM " + Table::Name + " WHERE nb_tracks = 0;" " END"; case Triggers::UpdateIsPresent: assert( dbModel >= 30 ); return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER UPDATE OF is_present ON " + Media::Table::Name + " WHEN new.subtype = " + std::to_string( static_cast<typename std::underlying_type<IMedia::SubType>::type>( IMedia::SubType::AlbumTrack ) ) + " AND old.is_present != new.is_present" " BEGIN" " UPDATE " + Table::Name + " SET is_present = is_present + " "(CASE new.is_present WHEN 0 THEN -1 ELSE 1 END) " "WHERE id_genre = " "(SELECT genre_id FROM " + AlbumTrack::Table::Name + " WHERE media_id = new.id_media);" " END"; default: assert( !"Invalid trigger provided" ); } return "<invalid request>"; } std::string Genre::triggerName( Triggers trigger, uint32_t dbModel ) { UNUSED_IN_RELEASE( dbModel ); switch ( trigger ) { case Triggers::InsertFts: return "insert_genre_fts"; case Triggers::DeleteFts: return "delete_genre_fts"; case Triggers::UpdateOnNewTrack: return "update_genre_on_new_track"; case Triggers::UpdateOnTrackDelete: return "update_genre_on_track_deleted"; case Triggers::UpdateIsPresent: assert( dbModel >= 30 ); return "genre_update_is_present"; default: assert( !"Invalid trigger provided" ); } return "<invalid request>"; } bool Genre::checkDbModel(MediaLibraryPtr ml) { if ( sqlite::Tools::checkTableSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ) == false || sqlite::Tools::checkTableSchema( ml->getConn(), schema( FtsTable::Name, Settings::DbModelVersion ), FtsTable::Name ) == false ) return false; auto check = []( sqlite::Connection* dbConn, Triggers t ) { return sqlite::Tools::checkTriggerStatement( dbConn, trigger( t, Settings::DbModelVersion ), triggerName( t, Settings::DbModelVersion ) ); }; return check( ml->getConn(), Triggers::InsertFts ) && check( ml->getConn(), Triggers::DeleteFts ) && check( ml->getConn(), Triggers::UpdateOnNewTrack ) && check( ml->getConn(), Triggers::UpdateOnTrackDelete ) && check( ml->getConn(), Triggers::UpdateIsPresent ); } std::shared_ptr<Genre> Genre::create( MediaLibraryPtr ml, std::string name ) { static const std::string req = "INSERT INTO " + Table::Name + "(name)" "VALUES(?)"; auto self = std::make_shared<Genre>( ml, std::move( name ) ); if ( insert( ml, self, req, self->m_name ) == false ) return nullptr; return self; } std::shared_ptr<Genre> Genre::fromName( MediaLibraryPtr ml, const std::string& name ) { static const std::string req = "SELECT * FROM " + Table::Name + " WHERE name = ?"; return fetch( ml, req, name ); } Query<IGenre> Genre::search( MediaLibraryPtr ml, const std::string& name, const QueryParameters* params ) { std::string req = "FROM " + Table::Name + " WHERE id_genre IN " "(SELECT rowid FROM " + FtsTable::Name + " " "WHERE name MATCH ?)"; std::string orderBy = "ORDER BY name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) orderBy += " DESC"; } return make_query<Genre, IGenre>( ml, "*", std::move( req ), std::move( orderBy ), sqlite::Tools::sanitizePattern( name ) ); } Query<IGenre> Genre::listAll( MediaLibraryPtr ml, const QueryParameters* params ) { std::string req = "FROM " + Table::Name; std::string orderBy = " ORDER BY name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) orderBy += " DESC"; } return make_query<Genre, IGenre>( ml, "*", std::move( req ), std::move( orderBy ) ); } } <commit_msg>Genre: Use enum_to_string<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Genre.h" #include "Album.h" #include "AlbumTrack.h" #include "Artist.h" #include "Media.h" #include "database/SqliteQuery.h" #include "utils/Enums.h" namespace medialibrary { const std::string Genre::Table::Name = "Genre"; const std::string Genre::Table::PrimaryKeyColumn = "id_genre"; int64_t Genre::* const Genre::Table::PrimaryKey = &Genre::m_id; const std::string Genre::FtsTable::Name = "GenreFts"; Genre::Genre( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_name( row.extract<decltype(m_name)>() ) , m_nbTracks( row.extract<decltype(m_nbTracks)>() ) , m_nbPresentTracks( row.extract<decltype(m_nbPresentTracks)>() ) { assert( row.hasRemainingColumns() == false ); } Genre::Genre( MediaLibraryPtr ml, std::string name ) : m_ml( ml ) , m_id( 0 ) , m_name( std::move( name ) ) , m_nbTracks( 0 ) , m_nbPresentTracks( 0 ) { } int64_t Genre::id() const { return m_id; } const std::string& Genre::name() const { return m_name; } uint32_t Genre::nbTracks() const { return m_nbTracks; } uint32_t Genre::nbPresentTracks() const { return m_nbPresentTracks; } void Genre::updateCachedNbTracks( int increment ) { m_nbTracks += increment; } Query<IArtist> Genre::artists( const QueryParameters* params ) const { std::string req = "FROM " + Artist::Table::Name + " a " "INNER JOIN " + AlbumTrack::Table::Name + " att ON att.artist_id = a.id_artist " "WHERE att.genre_id = ?"; std::string groupAndOrderBy = "GROUP BY att.artist_id ORDER BY a.name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) groupAndOrderBy += " DESC"; } return make_query<Artist, IArtist>( m_ml, "a.*", std::move( req ), std::move( groupAndOrderBy ), m_id ); } Query<IArtist> Genre::searchArtists( const std::string& pattern, const QueryParameters* params ) const { return Artist::searchByGenre( m_ml, pattern, params, m_id ); } Query<IMedia> Genre::tracks( TracksIncluded included, const QueryParameters* params ) const { return AlbumTrack::fromGenre( m_ml, m_id, included, params ); } Query<IMedia> Genre::searchTracks( const std::string& pattern, const QueryParameters* params ) const { return Media::searchGenreTracks( m_ml, pattern, m_id, params ); } Query<IAlbum> Genre::albums( const QueryParameters* params ) const { return Album::fromGenre( m_ml, m_id, params ); } Query<IAlbum> Genre::searchAlbums( const std::string& pattern, const QueryParameters* params ) const { return Album::searchFromGenre( m_ml, pattern, m_id, params ); } const std::string&Genre::thumbnailMrl( ThumbnailSizeType sizeType ) const { const auto t = thumbnail( sizeType ); if ( t == nullptr ) return Thumbnail::EmptyMrl; return t->mrl(); } bool Genre::hasThumbnail( ThumbnailSizeType sizeType ) const { if ( m_thumbnails[Thumbnail::SizeToInt( sizeType )] != nullptr ) return true; return thumbnail( sizeType ) != nullptr; } bool Genre::shouldUpdateThumbnail( const Thumbnail& oldThumbnail ) { return oldThumbnail.isShared() == false; } bool Genre::setThumbnail( const std::string& mrl, ThumbnailSizeType sizeType, bool takeOwnership ) { auto thumbnailIdx = Thumbnail::SizeToInt( sizeType ); auto currentThumbnail = thumbnail( sizeType ); auto newThumbnail = std::make_shared<Thumbnail>( m_ml, mrl, Thumbnail::Origin::UserProvided, sizeType, false ); currentThumbnail = Thumbnail::updateOrReplace( m_ml, currentThumbnail, newThumbnail, Genre::shouldUpdateThumbnail, m_id, Thumbnail::EntityType::Genre ); if ( currentThumbnail == nullptr ) return false; m_thumbnails[thumbnailIdx] = std::move( currentThumbnail ); if ( takeOwnership == true ) m_thumbnails[thumbnailIdx]->relocate(); return true; } std::shared_ptr<Thumbnail> Genre::thumbnail( ThumbnailSizeType sizeType ) const { auto idx = Thumbnail::SizeToInt( sizeType ); if ( m_thumbnails[idx] == nullptr ) { auto thumbnail = Thumbnail::fetch( m_ml, Thumbnail::EntityType::Genre, m_id, sizeType ); if ( thumbnail == nullptr ) return nullptr; m_thumbnails[idx] = std::move( thumbnail ); } return m_thumbnails[idx]; } void Genre::createTable( sqlite::Connection* dbConn ) { const std::string reqs[] = { schema( Table::Name, Settings::DbModelVersion ), schema( FtsTable::Name, Settings::DbModelVersion ), }; for ( const auto& req : reqs ) sqlite::Tools::executeRequest( dbConn, req ); } void Genre::createTriggers( sqlite::Connection* dbConn ) { sqlite::Tools::executeRequest( dbConn, trigger( Triggers::InsertFts, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::DeleteFts, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateOnNewTrack, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateOnTrackDelete, Settings::DbModelVersion ) ); sqlite::Tools::executeRequest( dbConn, trigger( Triggers::UpdateIsPresent, Settings::DbModelVersion ) ); } std::string Genre::schema( const std::string& tableName, uint32_t dbModel ) { if ( tableName == FtsTable::Name ) { return "CREATE VIRTUAL TABLE " + FtsTable::Name + " USING FTS3(name)"; } assert( tableName == Table::Name ); if ( dbModel < 30 ) { return "CREATE TABLE " + Table::Name + "(" "id_genre INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "nb_tracks INTEGER NOT NULL DEFAULT 0" ")"; } return "CREATE TABLE " + Table::Name + "(" "id_genre INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "nb_tracks INTEGER NOT NULL DEFAULT 0," "is_present INTEGER NOT NULL DEFAULT 0 " "CHECK(is_present <= nb_tracks)" ")"; } std::string Genre::trigger( Triggers trigger, uint32_t dbModel ) { switch ( trigger ) { case Triggers::InsertFts: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER INSERT ON " + Table::Name + " BEGIN" " INSERT INTO " + FtsTable::Name + "(rowid,name)" " VALUES(new.id_genre, new.name);" " END"; case Triggers::DeleteFts: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " BEFORE DELETE ON " + Table::Name + " BEGIN" " DELETE FROM " + FtsTable::Name + " WHERE rowid = old.id_genre;" " END"; case Triggers::UpdateOnNewTrack: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER INSERT ON " + AlbumTrack::Table::Name + " WHEN new.genre_id IS NOT NULL" " BEGIN" " UPDATE " + Table::Name + " SET nb_tracks = nb_tracks + 1," " is_present = is_present + 1" " WHERE id_genre = new.genre_id;" " END"; case Triggers::UpdateOnTrackDelete: return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER DELETE ON " + AlbumTrack::Table::Name + " WHEN old.genre_id IS NOT NULL" " BEGIN" " UPDATE " + Table::Name + " SET nb_tracks = nb_tracks - 1," " is_present = is_present - 1" " WHERE id_genre = old.genre_id;" " DELETE FROM " + Table::Name + " WHERE nb_tracks = 0;" " END"; case Triggers::UpdateIsPresent: assert( dbModel >= 30 ); return "CREATE TRIGGER " + triggerName( trigger, dbModel ) + " AFTER UPDATE OF is_present ON " + Media::Table::Name + " WHEN new.subtype = " + utils::enum_to_string( IMedia::SubType::AlbumTrack ) + " AND old.is_present != new.is_present" " BEGIN" " UPDATE " + Table::Name + " SET is_present = is_present + " "(CASE new.is_present WHEN 0 THEN -1 ELSE 1 END) " "WHERE id_genre = " "(SELECT genre_id FROM " + AlbumTrack::Table::Name + " WHERE media_id = new.id_media);" " END"; default: assert( !"Invalid trigger provided" ); } return "<invalid request>"; } std::string Genre::triggerName( Triggers trigger, uint32_t dbModel ) { UNUSED_IN_RELEASE( dbModel ); switch ( trigger ) { case Triggers::InsertFts: return "insert_genre_fts"; case Triggers::DeleteFts: return "delete_genre_fts"; case Triggers::UpdateOnNewTrack: return "update_genre_on_new_track"; case Triggers::UpdateOnTrackDelete: return "update_genre_on_track_deleted"; case Triggers::UpdateIsPresent: assert( dbModel >= 30 ); return "genre_update_is_present"; default: assert( !"Invalid trigger provided" ); } return "<invalid request>"; } bool Genre::checkDbModel(MediaLibraryPtr ml) { if ( sqlite::Tools::checkTableSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ) == false || sqlite::Tools::checkTableSchema( ml->getConn(), schema( FtsTable::Name, Settings::DbModelVersion ), FtsTable::Name ) == false ) return false; auto check = []( sqlite::Connection* dbConn, Triggers t ) { return sqlite::Tools::checkTriggerStatement( dbConn, trigger( t, Settings::DbModelVersion ), triggerName( t, Settings::DbModelVersion ) ); }; return check( ml->getConn(), Triggers::InsertFts ) && check( ml->getConn(), Triggers::DeleteFts ) && check( ml->getConn(), Triggers::UpdateOnNewTrack ) && check( ml->getConn(), Triggers::UpdateOnTrackDelete ) && check( ml->getConn(), Triggers::UpdateIsPresent ); } std::shared_ptr<Genre> Genre::create( MediaLibraryPtr ml, std::string name ) { static const std::string req = "INSERT INTO " + Table::Name + "(name)" "VALUES(?)"; auto self = std::make_shared<Genre>( ml, std::move( name ) ); if ( insert( ml, self, req, self->m_name ) == false ) return nullptr; return self; } std::shared_ptr<Genre> Genre::fromName( MediaLibraryPtr ml, const std::string& name ) { static const std::string req = "SELECT * FROM " + Table::Name + " WHERE name = ?"; return fetch( ml, req, name ); } Query<IGenre> Genre::search( MediaLibraryPtr ml, const std::string& name, const QueryParameters* params ) { std::string req = "FROM " + Table::Name + " WHERE id_genre IN " "(SELECT rowid FROM " + FtsTable::Name + " " "WHERE name MATCH ?)"; std::string orderBy = "ORDER BY name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) orderBy += " DESC"; } return make_query<Genre, IGenre>( ml, "*", std::move( req ), std::move( orderBy ), sqlite::Tools::sanitizePattern( name ) ); } Query<IGenre> Genre::listAll( MediaLibraryPtr ml, const QueryParameters* params ) { std::string req = "FROM " + Table::Name; std::string orderBy = " ORDER BY name"; if ( params != nullptr ) { if ( params->sort != SortingCriteria::Default && params->sort != SortingCriteria::Alpha ) LOG_WARN( "Unsupported sorting criteria, falling back to SortingCriteria::Alpha" ); if ( params->desc == true ) orderBy += " DESC"; } return make_query<Genre, IGenre>( ml, "*", std::move( req ), std::move( orderBy ) ); } } <|endoftext|>
<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>. // It is published under the BSD-style license contained in the LICENSE.txt file. #include "../include/Image.h" #include <ImfChannelList.h> #include <ImfInputFile.h> #include <stb_image.h> #include <array> #include <iostream> using namespace std; namespace { bool endsWith(const string& a, const string& b) { return a.length() >= b.length() && a.compare(a.length() - b.length(), b.length(), b) == 0; } } Image::Image(const string& filename) : mName(filename) { if (endsWith(filename, ".exr")) { readExr(filename); } else { readStbi(filename); } } const GlTexture* Image::texture(const std::string& channelName) { auto iter = mTextures.find(channelName); if (iter != end(mTextures)) { return &iter->second; } const auto* chan = channel(channelName); if (!chan) { return nullptr; } mTextures.emplace(channelName, GlTexture{}); auto& texture = mTextures.at(channelName); texture.setData(chan->data(), mSize, 1); return &texture; } void Image::readStbi(const std::string& filename) { // No exr image? Try our best using stbi cout << "Loading "s + filename + " via STBI." << endl; int numChannels; auto data = stbi_load(filename.c_str(), &mSize.x(), &mSize.y(), &numChannels, 0); if (!data) { throw invalid_argument("Could not load texture data from file " + filename); } mNumChannels = static_cast<size_t>(numChannels); vector<string> channelNames = {"R", "G", "B", "A"}; vector<Channel> channels; for (size_t c = 0; c < mNumChannels; ++c) { string name = c < channelNames.size() ? channelNames[c] : to_string(c - channelNames.size()); channels.emplace_back(name); } size_t numPixels = mSize.prod(); for (size_t i = 0; i < numPixels; ++i) { size_t baseIdx = i * mNumChannels; for (size_t c = 0; c < mNumChannels; ++c) { // Assume LDR images were sRGB tonemapped and apply inverse. // For now, approximate sRGB curve by 2.2 gamma. // TODO: Proper sRGB curve. float value = data[baseIdx + c]; channels[c].data().push_back(pow(value / 255.0f, 2.2f)); } } stbi_image_free(data); for (auto& channel : channels) { string name = channel.name(); mChannels.emplace(move(name), move(channel)); } } void Image::readExr(const std::string& filename) { // OpenEXR for reading exr images cout << "Loading "s + filename + " via OpenEXR." << endl; Imf::InputFile file(filename.c_str()); Imath::Box2i dw = file.header().dataWindow(); mSize.x() = dw.max.x - dw.min.x + 1; mSize.y() = dw.max.y - dw.min.y + 1; // Inline helper class for dealing with the raw channels loaded from an exr file. class RawChannel { public: RawChannel(string name, Imf::PixelType type, size_t size) : mName(name), mType(type) { mData.resize(size * bytesPerPixel()); } void registerWith(Imf::FrameBuffer& frameBuffer, const Imath::Box2i& dw) { int width = dw.max.x - dw.min.x + 1; frameBuffer.insert(mName.c_str(), Imf::Slice( mType, mData.data() - (dw.min.x - dw.min.y * width) * bytesPerPixel(), bytesPerPixel(), bytesPerPixel() * width, // stride in x and y 1, 1, 0 )); } void copyTo(Channel& channel) const { int bpp = bytesPerPixel(); auto& dstData = channel.data(); dstData.resize(mData.size() / bpp); for (size_t i = 0; i < dstData.size(); ++i) { size_t rawIdx = i * bpp; switch (mType) { case Imf::HALF: dstData[i] = static_cast<float>(*reinterpret_cast<const half*>(&mData[rawIdx])); break; case Imf::FLOAT: dstData[i] = static_cast<float>(*reinterpret_cast<const float*>(&mData[rawIdx])); break; case Imf::UINT: dstData[i] = static_cast<float>(*reinterpret_cast<const uint32_t*>(&mData[rawIdx])); break; default: throw runtime_error("Invalid pixel type encountered."); } } } const auto& name() const { return mName; } private: int bytesPerPixel() const { return mType == Imf::HALF ? 2 : 4; } string mName; Imf::PixelType mType; vector<char> mData; }; vector<RawChannel> rawChannels; Imf::FrameBuffer frameBuffer; const Imf::ChannelList& imfChannels = file.header().channels(); for (Imf::ChannelList::ConstIterator i = imfChannels.begin(); i != imfChannels.end(); ++i) { rawChannels.emplace_back(i.name(), i.channel().type, mSize.prod()); rawChannels.back().registerWith(frameBuffer, dw); } file.setFrameBuffer(frameBuffer); file.readPixels(dw.min.y, dw.max.y); for (const auto& rawChannel : rawChannels) { mChannels.emplace(rawChannel.name(), Channel{rawChannel.name()}); rawChannel.copyTo(mChannels.at(rawChannel.name())); } } <commit_msg>Directly load linear colors via stbi<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>. // It is published under the BSD-style license contained in the LICENSE.txt file. #include "../include/Image.h" #include <ImfChannelList.h> #include <ImfInputFile.h> #include <stb_image.h> #include <array> #include <iostream> using namespace std; namespace { bool endsWith(const string& a, const string& b) { return a.length() >= b.length() && a.compare(a.length() - b.length(), b.length(), b) == 0; } } Image::Image(const string& filename) : mName(filename) { if (endsWith(filename, ".exr")) { readExr(filename); } else { readStbi(filename); } } const GlTexture* Image::texture(const std::string& channelName) { auto iter = mTextures.find(channelName); if (iter != end(mTextures)) { return &iter->second; } const auto* chan = channel(channelName); if (!chan) { return nullptr; } mTextures.emplace(channelName, GlTexture{}); auto& texture = mTextures.at(channelName); texture.setData(chan->data(), mSize, 1); return &texture; } void Image::readStbi(const std::string& filename) { // No exr image? Try our best using stbi cout << "Loading "s + filename + " via STBI." << endl; int numChannels; auto data = stbi_loadf(filename.c_str(), &mSize.x(), &mSize.y(), &numChannels, 0); if (!data) { throw invalid_argument("Could not load texture data from file " + filename); } mNumChannels = static_cast<size_t>(numChannels); size_t numPixels = mSize.prod(); vector<string> channelNames = {"R", "G", "B", "A"}; vector<Channel> channels; for (size_t c = 0; c < mNumChannels; ++c) { string name = c < channelNames.size() ? channelNames[c] : to_string(c - channelNames.size()); channels.emplace_back(name); channels.back().data().resize(numPixels); } for (size_t i = 0; i < numPixels; ++i) { size_t baseIdx = i * mNumChannels; for (size_t c = 0; c < mNumChannels; ++c) { channels[c].data()[i] = data[baseIdx + c]; } } stbi_image_free(data); for (auto& channel : channels) { string name = channel.name(); mChannels.emplace(move(name), move(channel)); } } void Image::readExr(const std::string& filename) { // OpenEXR for reading exr images cout << "Loading "s + filename + " via OpenEXR." << endl; Imf::InputFile file(filename.c_str()); Imath::Box2i dw = file.header().dataWindow(); mSize.x() = dw.max.x - dw.min.x + 1; mSize.y() = dw.max.y - dw.min.y + 1; // Inline helper class for dealing with the raw channels loaded from an exr file. class RawChannel { public: RawChannel(string name, Imf::PixelType type, size_t size) : mName(name), mType(type) { mData.resize(size * bytesPerPixel()); } void registerWith(Imf::FrameBuffer& frameBuffer, const Imath::Box2i& dw) { int width = dw.max.x - dw.min.x + 1; frameBuffer.insert(mName.c_str(), Imf::Slice( mType, mData.data() - (dw.min.x - dw.min.y * width) * bytesPerPixel(), bytesPerPixel(), bytesPerPixel() * width, // stride in x and y 1, 1, 0 )); } void copyTo(Channel& channel) const { int bpp = bytesPerPixel(); auto& dstData = channel.data(); dstData.resize(mData.size() / bpp); for (size_t i = 0; i < dstData.size(); ++i) { size_t rawIdx = i * bpp; switch (mType) { case Imf::HALF: dstData[i] = static_cast<float>(*reinterpret_cast<const half*>(&mData[rawIdx])); break; case Imf::FLOAT: dstData[i] = static_cast<float>(*reinterpret_cast<const float*>(&mData[rawIdx])); break; case Imf::UINT: dstData[i] = static_cast<float>(*reinterpret_cast<const uint32_t*>(&mData[rawIdx])); break; default: throw runtime_error("Invalid pixel type encountered."); } } } const auto& name() const { return mName; } private: int bytesPerPixel() const { return mType == Imf::HALF ? 2 : 4; } string mName; Imf::PixelType mType; vector<char> mData; }; vector<RawChannel> rawChannels; Imf::FrameBuffer frameBuffer; const Imf::ChannelList& imfChannels = file.header().channels(); for (Imf::ChannelList::ConstIterator i = imfChannels.begin(); i != imfChannels.end(); ++i) { rawChannels.emplace_back(i.name(), i.channel().type, mSize.prod()); rawChannels.back().registerWith(frameBuffer, dw); } file.setFrameBuffer(frameBuffer); file.readPixels(dw.min.y, dw.max.y); for (const auto& rawChannel : rawChannels) { mChannels.emplace(rawChannel.name(), Channel{rawChannel.name()}); rawChannel.copyTo(mChannels.at(rawChannel.name())); } } <|endoftext|>
<commit_before>468108b4-2e4d-11e5-9284-b827eb9e62be<commit_msg>46860d6e-2e4d-11e5-9284-b827eb9e62be<commit_after>46860d6e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd3c2036-2e4e-11e5-9284-b827eb9e62be<commit_msg>cd4119ba-2e4e-11e5-9284-b827eb9e62be<commit_after>cd4119ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>01407d02-2e4d-11e5-9284-b827eb9e62be<commit_msg>01456f1a-2e4d-11e5-9284-b827eb9e62be<commit_after>01456f1a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c88cf90c-2e4e-11e5-9284-b827eb9e62be<commit_msg>c891f718-2e4e-11e5-9284-b827eb9e62be<commit_after>c891f718-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6ae6c932-2e4d-11e5-9284-b827eb9e62be<commit_msg>6aebd738-2e4d-11e5-9284-b827eb9e62be<commit_after>6aebd738-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>936be7a6-2e4e-11e5-9284-b827eb9e62be<commit_msg>9370e5ee-2e4e-11e5-9284-b827eb9e62be<commit_after>9370e5ee-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>af8763f2-2e4e-11e5-9284-b827eb9e62be<commit_msg>af8c6226-2e4e-11e5-9284-b827eb9e62be<commit_after>af8c6226-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fd0e950a-2e4e-11e5-9284-b827eb9e62be<commit_msg>fd139050-2e4e-11e5-9284-b827eb9e62be<commit_after>fd139050-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0d4ad024-2e4e-11e5-9284-b827eb9e62be<commit_msg>0d4fcc28-2e4e-11e5-9284-b827eb9e62be<commit_after>0d4fcc28-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f7545eec-2e4e-11e5-9284-b827eb9e62be<commit_msg>f7595cee-2e4e-11e5-9284-b827eb9e62be<commit_after>f7595cee-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>029e029a-2e4e-11e5-9284-b827eb9e62be<commit_msg>02a2fd9a-2e4e-11e5-9284-b827eb9e62be<commit_after>02a2fd9a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2a851966-2e4d-11e5-9284-b827eb9e62be<commit_msg>2a8a1434-2e4d-11e5-9284-b827eb9e62be<commit_after>2a8a1434-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>07e77e06-2e4f-11e5-9284-b827eb9e62be<commit_msg>07ec714a-2e4f-11e5-9284-b827eb9e62be<commit_after>07ec714a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>283571c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>283a67f6-2e4d-11e5-9284-b827eb9e62be<commit_after>283a67f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>945f16ac-2e4d-11e5-9284-b827eb9e62be<commit_msg>94641f26-2e4d-11e5-9284-b827eb9e62be<commit_after>94641f26-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f239661a-2e4d-11e5-9284-b827eb9e62be<commit_msg>f23e7902-2e4d-11e5-9284-b827eb9e62be<commit_after>f23e7902-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be17e97e-2e4d-11e5-9284-b827eb9e62be<commit_msg>be1cdcea-2e4d-11e5-9284-b827eb9e62be<commit_after>be1cdcea-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2536442a-2e4e-11e5-9284-b827eb9e62be<commit_msg>253b4f74-2e4e-11e5-9284-b827eb9e62be<commit_after>253b4f74-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>68741042-2e4d-11e5-9284-b827eb9e62be<commit_msg>68791b64-2e4d-11e5-9284-b827eb9e62be<commit_after>68791b64-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a93a668e-2e4e-11e5-9284-b827eb9e62be<commit_msg>a93f5d88-2e4e-11e5-9284-b827eb9e62be<commit_after>a93f5d88-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>99e1b89a-2e4e-11e5-9284-b827eb9e62be<commit_msg>99e6e48c-2e4e-11e5-9284-b827eb9e62be<commit_after>99e6e48c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9aadba80-2e4e-11e5-9284-b827eb9e62be<commit_msg>9ab2effa-2e4e-11e5-9284-b827eb9e62be<commit_after>9ab2effa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dfde31e4-2e4d-11e5-9284-b827eb9e62be<commit_msg>dfe33d7e-2e4d-11e5-9284-b827eb9e62be<commit_after>dfe33d7e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e62eb5aa-2e4d-11e5-9284-b827eb9e62be<commit_msg>e633b974-2e4d-11e5-9284-b827eb9e62be<commit_after>e633b974-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>02198254-2e4e-11e5-9284-b827eb9e62be<commit_msg>021e8cae-2e4e-11e5-9284-b827eb9e62be<commit_after>021e8cae-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bf505b38-2e4c-11e5-9284-b827eb9e62be<commit_msg>bf55ad90-2e4c-11e5-9284-b827eb9e62be<commit_after>bf55ad90-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>220022d6-2e4d-11e5-9284-b827eb9e62be<commit_msg>220516c4-2e4d-11e5-9284-b827eb9e62be<commit_after>220516c4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f6736d74-2e4e-11e5-9284-b827eb9e62be<commit_msg>f678687e-2e4e-11e5-9284-b827eb9e62be<commit_after>f678687e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e0342f18-2e4d-11e5-9284-b827eb9e62be<commit_msg>e0393738-2e4d-11e5-9284-b827eb9e62be<commit_after>e0393738-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b9f73076-2e4c-11e5-9284-b827eb9e62be<commit_msg>b9fc4da4-2e4c-11e5-9284-b827eb9e62be<commit_after>b9fc4da4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be073526-2e4c-11e5-9284-b827eb9e62be<commit_msg>be0c2806-2e4c-11e5-9284-b827eb9e62be<commit_after>be0c2806-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>58433b30-2e4d-11e5-9284-b827eb9e62be<commit_msg>58483d4c-2e4d-11e5-9284-b827eb9e62be<commit_after>58483d4c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fa48f7d4-2e4e-11e5-9284-b827eb9e62be<commit_msg>fa4dff04-2e4e-11e5-9284-b827eb9e62be<commit_after>fa4dff04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d8b0dee4-2e4d-11e5-9284-b827eb9e62be<commit_msg>d8b5dbba-2e4d-11e5-9284-b827eb9e62be<commit_after>d8b5dbba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2cdd0ab6-2e4d-11e5-9284-b827eb9e62be<commit_msg>2ce1fbac-2e4d-11e5-9284-b827eb9e62be<commit_after>2ce1fbac-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>af4d6ffe-2e4d-11e5-9284-b827eb9e62be<commit_msg>af527a12-2e4d-11e5-9284-b827eb9e62be<commit_after>af527a12-2e4d-11e5-9284-b827eb9e62be<|endoftext|>