hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
347a33b9a8cc5b8581d4094543dd9a5abb969da8
38,090
inl
C++
src/fonts/stb_font_consolas_32_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_consolas_32_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_consolas_32_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_32_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_consolas_32_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_consolas_32_usascii_BITMAP_WIDTH 256 #define STB_FONT_consolas_32_usascii_BITMAP_HEIGHT 138 #define STB_FONT_consolas_32_usascii_BITMAP_HEIGHT_POW2 256 #define STB_FONT_consolas_32_usascii_FIRST_CHAR 32 #define STB_FONT_consolas_32_usascii_NUM_CHARS 95 #define STB_FONT_consolas_32_usascii_LINE_SPACING 21 static unsigned int stb__consolas_32_usascii_pixels[]={ 0x04000993,0x2654c000,0x00015793,0x99930620,0x40019999,0xccca8008, 0x26004ccc,0x654c001a,0x000000ac,0x06600000,0x00000000,0x00000000, 0x401fee00,0x000ba25d,0x53ffff4c,0x0019ffff,0xb877fc40,0x1fffffff, 0x7fff6440,0xffff902d,0x3a001fff,0xffb1002f,0x001dffff,0x7ccdfb00, 0xff70002f,0x37ec05ff,0x2e7fd800,0xfe8001ff,0x39dff32f,0xfffffd80, 0x00ff704f,0x3ff63ff9,0x7ffc4002,0x3fb264df,0x320004ff,0x99933fff, 0x5403ffb9,0xfffddfff,0xcccffc82,0x07fe004c,0x3bfffe60,0x001effff, 0xfd0ffe20,0xbff7000b,0xff503fff,0x9ff60003,0xe8001ffb,0xffff32ff, 0x3ff603df,0xf704ffff,0x23ffc80f,0x2001ffe8,0x4c00bffc,0x70001ffe, 0x7d407fff,0x19ff701f,0x7e42ffb8,0xff510007,0x7ffc4015,0x1fff660b, 0xa87fc800,0x3e2000ff,0x889fd12f,0x360004fe,0x007fee7f,0x544bffa0, 0x82ffffcb,0x4ffa9998,0x7d40ff70,0x0fff884f,0x400ffd00,0x10003ffb, 0xffa80bfb,0x202ff981,0x03fe46fc,0xfffff910,0xff903fff,0x01ffec07, 0xff04ff80,0x23fcc009,0x037e46fc,0xfb9ff600,0xffe8001f,0x3fff9102, 0x704ff880,0x1bfe20ff,0xf005ff98,0x7fc4009f,0xa8000004,0x04fe81ff, 0x1ff21fe8,0x7ffffd40,0x441fffff,0x7fc406ff,0x0ffa8006,0x5400ff90, 0xf337d47f,0xfd80003f,0x0007fee7,0xf7007ff6,0x4ff880bf,0x3f20ff70, 0x0ffec01f,0x000ffe20,0x00000bfd,0xfb83ff50,0x649f9006,0xfff9807f, 0xb98dfb9c,0x401ffdc0,0x74001ffe,0x0bfe205f,0xf707fcc0,0x00027f4b, 0x3ff73fec,0x03ffb000,0x4401fff0,0x0ff704ff,0xf1009ff3,0x3ff880df, 0x102ff400,0x99999999,0x7fd40199,0xa8017f41,0x201ff27f,0x13f22ffd, 0x7001ff90,0x7cc005ff,0x037ec02f,0xf88cff88,0x001ff93f,0x76776dd4, 0x4c7fee7f,0xfb03dfdb,0x5ffb003f,0xb827fc40,0x00ffd87f,0x4405ff70, 0x7f4003ff,0x3fffe605,0x00ffffff,0x7fa87fea,0x8898aa88,0x201ff27f, 0x01fec7ff,0x7d401ff6,0x1bf2003f,0x4007fea0,0x36fffffb,0x3a2005ff, 0xffffffff,0x3ea3fee7,0xd85fffff,0xffc801ff,0x413fe201,0x2ffc47fb, 0x40bff100,0x74003ff8,0x3332205f,0x0ffecccc,0xfd87fea0,0x3ffff624, 0x3f21ff1f,0x20fff807,0x37f402ff,0x004ff980,0x3a007ff1,0x3faa005f, 0x4017fa4e,0xbabdfff9,0x3fee7ffd,0xfecbdffc,0x00ffec4f,0xf1007ff4, 0x51fee09f,0xfe8005ff,0x03ff100f,0x0005fd80,0xfa803ff2,0xfe87fe1f, 0xff0fffcf,0x3601ff23,0x007fe4ff,0x3e600dff,0x1ff7005f,0x003fee00, 0x001ff700,0x7ec07bfa,0x0bfffee7,0x7e41ffd1,0x3ff2600f,0x827fc405, 0x03fec7fb,0xb817fdc0,0xffa8007f,0x1ff90000,0xf88ffd40,0x2e1ff50f, 0x7e4bfa7f,0xefff9807,0x7fc00ffb,0x09ff3006,0x88013fa0,0x260003ff, 0xff7002ff,0xf73fec05,0x3fee03ff,0xfb03ff23,0x801fffff,0xff704ff8, 0x98005ff8,0x3ee624ff,0xff88004f,0x7e4001ae,0x47fea00f,0xc93f66fa, 0x7e4bfa6f,0xffff5007,0x7ff801ff,0x007ff300,0xc8003ff5,0x3fa0007f, 0x01bfa005,0x17fdcffb,0x7e49ff10,0x77ffec0f,0x4ff8800c,0x7fc4ff70, 0x4ff88005,0x005dfff7,0x3fffe440,0x401ff900,0x2bf71ffa,0x97f62ff8, 0x00ff91fe,0x7ffffec4,0x00ffd00c,0x3600bfea,0xff98006f,0x0ffb8002, 0xb017fe00,0x00ffdcff,0x0ffc97fe,0x44003fe4,0x4ff704ff,0xf0004ff8, 0x3bffeebf,0x7fdc0002,0x3ff2007f,0x647fea00,0x741ff54f,0x7e43fe3f, 0xffd88007,0xffd83fff,0x01ffc801,0x80017fc4,0x7c4005fe,0x3dffd33f, 0x6c04ff88,0x007fee7f,0x07fdcdff,0x22001bf2,0x4ff704ff,0xf0003ff9, 0x7fe4c4df,0xeff88005,0x3f20009a,0x47fea00f,0xf8ff73fd,0x7e43fe2f, 0xdbfb0007,0xffb87fff,0x807ff804,0x2a0007fc,0x3f6001ff,0xffffff56, 0x201ffcc1,0x07fee7fd,0x3fdcdff0,0x440037e4,0x4ff704ff,0xf0004ff9, 0x01fee0df,0x0003fea0,0xf5007fe4,0x7e4ff63f,0x7c47fe66,0x4001ff27, 0x3fff52fe,0x2e037fc4,0x4ff803ff,0x027fc000,0x9fd0ffa8,0xff897fa2, 0xf73fec04,0x27fc403f,0x0df90ff7,0x209ff100,0x13fe27fb,0x982ffc00, 0x7e4001ff,0x3ff20005,0x747fea00,0x7d4df92f,0x7e4bf50f,0x43ff0007, 0x7fec3ffb,0x01fff305,0x0000ffb8,0x22007fdc,0x41ff13ff,0x13fe26fb, 0x7fdcffd0,0x00ffe601,0x3fe20000,0xff8ff704,0x4ff88005,0x8007ff10, 0x320005fe,0x3fea00ff,0x9fee7fb1,0xc8bf67fd,0xff88007f,0xf113fea0, 0xf9537dff,0xbfd005ff,0x7ff10000,0x3ea6fd80,0x3fe3fd47,0xb9fff607, 0x3ff201ff,0x88000001,0x8ff704ff,0xfa8007fe,0x07ff102f,0x0005fe80, 0xfa803ff2,0x3ea7f91f,0xa9fffa9f,0x01ff20ff,0xffb1fe60,0xfffff305, 0x3005ffff,0x200003ff,0x3fea06fd,0xfa83fe61,0x6417fe46,0x3fee7fff, 0xa8bff301,0x0275c0cd,0xb827fc40,0x00ffe47f,0x4403ff20,0x7f4003ff, 0x3ff20005,0x647fea00,0x37fffe4f,0x642ffffb,0x7d40807f,0x403ffea6, 0xcffffeb8,0x00dfb001,0x417fcc00,0x7fc44ff8,0xff313fa4,0x9dfd515f, 0x4e7fdcff,0x41fff730,0x3e64fff8,0x4ccc03ff,0x999dffa9,0xff98ff71, 0x037fc004,0xe8007ff1,0x3f20005f,0x47fea00f,0x33f225fb,0xc82dfc88, 0x677cc07f,0xfffdefdc,0x1ff9003f,0x01ffc400,0x217fa000,0xdff906fc, 0xff701fff,0xf71dffff,0x7ffffdcf,0x4c1effff,0x3fea5fff,0x3ffe604f, 0xffffffff,0xfe87fb9f,0x0ffea007,0x4003ff88,0x320005fe,0x3fea00ff, 0x0000ff51,0xff980ff9,0xffffffff,0x3fea002f,0x03fee003,0x1ff70000, 0xf700ffd4,0x75c01dff,0xff70ceff,0x7fffed44,0x3ff603ef,0x807ffa22, 0xfffffff9,0xfb9fffff,0x003ffb87,0xff880ffd,0x02ff4003,0xa80ffb00, 0x03ff11ff,0x407fc800,0xfffeecb8,0xf88003ce,0x20ea0aff,0x000004ff, 0x4c0009ff,0x00022000,0x02600088,0x8000004c,0x1ffd07fb,0x802ffb80, 0x3e2005ff,0x3fa0004f,0xb0ffd406,0xfc80009f,0x02ff8007,0xffffb800, 0x3ea1fffe,0x9000001f,0x000000ff,0x00000000,0x70000000,0x17fe60ff, 0xd006ff88,0x3ee001ff,0xff30003f,0x21ffa809,0x20001ff9,0xff8007fc, 0xff700001,0x741bffff,0x2000005f,0x00002ff8,0x00000000,0x00000000, 0xff903fdc,0x007ff607,0x1016ffdc,0x6401ffd7,0x07ffdc41,0xfd07fea0, 0xc805403f,0x7fcc007f,0x2a200000,0x1aa81acb,0x55400000,0x00000001, 0x00000000,0x7dc00000,0x0bffa207,0xe8005ff9,0x3aa6ffff,0x7c04ffff, 0xffffeeff,0x77777543,0xeffd81ff,0x01ffdcbc,0xdddddff9,0x00132601, 0x00000000,0x00000000,0x00000000,0x00000000,0x3a203fdc,0x07ff71ff, 0xffff9100,0x017fffd4,0x7ffffff4,0xffffb81e,0xff901fff,0x019dffff, 0x3ffffff2,0x0000000f,0x00000000,0x00000000,0x00000000,0x70000000, 0x1df100ff,0x100013ea,0x04d44553,0x2aeea600,0x2aaaa601,0x54400aaa, 0xaa9801aa,0x0002aaaa,0x00000000,0x00000000,0x00000000,0x00000000, 0x401fee00,0x00000c09,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x5c000000,0x0000007f,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x0000154c, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x59751000,0x20000001,0xca800ccb, 0x0004c00c,0xfd930000,0x199999bd,0x01331000,0x59ddb750,0x73264cd9, 0x4c007bfb,0x654c0003,0x555400ac,0x2aaaaaaa,0x0acca880,0x5554c000, 0x332ea200,0x077ae02b,0x7fffffd4,0x027fc403,0x804ffb80,0x7fec07ff, 0x007fee02,0xfffffc80,0x01ffffff,0xfffff910,0xfffd105f,0x5cffffff, 0xfffff57f,0x1ff900bf,0xfffb1000,0x3a01dfff,0xffffffff,0xffb100ff, 0x8009ffff,0x2fffffeb,0xffffff70,0xfffa87ff,0xedfffa86,0x3e203fff, 0xff10004f,0x04ff980f,0xb81bffe6,0xf90001ff,0xffb313bf,0xf300199f, 0x5fffffff,0xabcfff98,0x3ee7ffdb,0xecbdffbf,0x7fe404ff,0x7ffcc000, 0x1efffeef,0xffffffe8,0xe880ffff,0xfffddfff,0x7ffd400d,0xb82fffff, 0xffdcefff,0x3ffee2ff,0x30fff40f,0x7fc40fff,0x3ff60004,0x807ff202, 0x2e05fff9,0xf88001ff,0x03ff906f,0x45efff40,0x77f40a98,0x7dcffb01, 0x7f442fff,0x03ff200f,0x0bfff880,0x3a1fff62,0xffd0005f,0x03ffd887, 0x06b7ffea,0x701dff30,0x7ffccfff,0x6c27fc46,0x9ff100ff,0x2ffcc000, 0xf700dff0,0x0ffdc03d,0x817fd400,0xf3004ff9,0x3fee00df,0xfb9ff602, 0x7ff701ff,0x0007fe40,0x7ec07ff9,0x002ff43f,0xe8827fcc,0x3dff107f, 0x01ffdc00,0x66d41ffd,0x641ffcc0,0x9ff100ff,0x0ffe8000,0x0003ffa8, 0x0007fee0,0x7c407fee,0x7ff7004f,0xb01bfa00,0x017fdcff,0x66649ff1, 0xccccffec,0x3fe20ccc,0x237fc406,0xfd8005fe,0x0bfee00f,0x90003ff6, 0x7fe401ff,0x0bff1000,0x7fc40dfd,0x7fdc0004,0x000ffd83,0x007fee00, 0x4c0bfee0,0xff9003ff,0x017fe001,0x0ffdcffb,0xfff97fe0,0xffffffff, 0x3fee0fff,0x21ffe803,0x7c4005fe,0x2ffe405f,0x2000ffe2,0x3fe03ffa, 0x07ffc006,0x7c407ff9,0x0f32e04f,0x3e237fc4,0x9999705f,0x7fdc0599, 0x07bfdb31,0x7ec1bfe2,0x0ffb001f,0xb013fe20,0x00ffdcff,0xcccc9bfe, 0xcccccffe,0x03ff20cc,0xfe8bfee0,0x17fcc005,0x46fffd88,0xf0000ffb, 0x7ff905ff,0x8dffb800,0x7c405ffd,0x1dff904f,0xf50ffec0,0x3fff605f, 0x3ee04fff,0xfffffc8f,0x5dff905f,0x009ffb53,0xf9803fec,0x73fec03f, 0x6ff803ff,0x4003ff20,0xff5007fd,0x4d577f47,0x417fd400,0x47fffffa, 0x2f2a67fd,0x3ffee009,0x0dffe98c,0xffffe800,0x4ff8803f,0x400effb8, 0x1ff64ffa,0xffccccb8,0x3f7fee04,0x2fffdadf,0xffffffd8,0x2aa604ff, 0xaabffeaa,0x3fe22aaa,0xf73fec04,0x04ff803f,0x74003ff2,0x9ff3006f, 0x7ffffff4,0x1ffb81cf,0x7e5fffe4,0x7fe77f47,0x203fffff,0xfffffff9, 0x3ff20003,0xff1001ef,0x00effb89,0x3fe2ffd0,0x13fe2004,0x41ffffb8, 0x7fd46ff9,0x01cdedba,0x7fffffec,0x7fffffff,0xfd013fe2,0x300ffdcf, 0x7fe407ff,0x00dff000,0xffe97fe6,0x2fffffff,0xfe887fe4,0x41ff71ef, 0xcdefffff,0x2604fffe,0x00efffff,0xfffffb00,0x7c44cb83,0x03bfee4f, 0xfbaffb80,0x3fe2001f,0x07ffee04,0x17f63ffc,0xeeeec800,0xeeeeefff, 0xb03ffc5e,0x0ffdcfff,0x6403ff90,0xdff000ff,0x013fe600,0x45fffb53, 0xfffa8ffb,0xff07fe45,0xffd3019f,0xfdffd303,0x57105fff,0xff99ffb0, 0x2237f41d,0x1dff74ff,0xedff8800,0x7fc4006f,0x80bfee04,0x3ffa0ffd, 0x3f600000,0x0bff2007,0xfb9ffff2,0x0bff301f,0xf000ffc8,0x3fe600ff, 0x97fee003,0x2fffdffb,0x2ffc7fc8,0xf713fea0,0x3ff665df,0x93ffe23f, 0x3ff65ffa,0xff117fe5,0x001dff79,0x0fffff60,0x409ff100,0x3f201ffb, 0x3bfff20f,0x00acccde,0x9801ff60,0xfea8afff,0x3fee7fde,0xfff7309c, 0x00ffc801,0x2a00ffd0,0x7fc002ff,0x3bfffea7,0xff8ffb01,0x266ff806, 0xffb80eff,0x1ffff70f,0xfe883ff6,0x444ff9cf,0x00fffeff,0x3fffea00, 0x27fc4000,0x6403ff70,0x3ff620ff,0xffffffff,0x00ffb004,0xffffffb8, 0x3ee7fc8e,0xffffffff,0x0ffc801e,0x003ffb00,0xd8003ff9,0x9fff30ff, 0x7f46fe80,0x327fe807,0x3ff201ff,0x21ffff73,0xfff986ff,0x7fc42ffd, 0x0005ffcc,0x40027ffc,0x3ee04ff8,0x83ff201f,0xdcccffe8,0x804ffffe, 0xeb8007fd,0xff90ceff,0x7fffffdc,0x3f2003ef,0x7ff7000f,0x000fff00, 0x37fc4ffd,0xfb13fe60,0x26ff801f,0x7fcc06fe,0xff8fffa4,0xfffff505, 0xfb4ff881,0x7fc0009f,0xff88000f,0x807fee04,0x3ffa0ffc,0x01ffea00, 0x88001ff6,0x3ee7fd80,0x0000989f,0x22005ff7,0x7fd406ff,0x2ffc4003, 0xfc807ff2,0x01ffdc0f,0x3fe29ff1,0x227fcc06,0x903ffc09,0xff109fff, 0x00fffa29,0x0013fee0,0xf7027fc4,0x87fe403f,0xfd803ff9,0x03fec00f, 0x73fec000,0x500003ff,0x7e400bff,0x0fff305f,0x42ffe880,0xff506ff9, 0x40dff10b,0x3ffa1ffd,0x00bff601,0x7cc0fff6,0x4ff885ff,0x800fffa2, 0x0000fff9,0x7dc09ff1,0x43ff201f,0xfe803ffb,0x007fd807,0x2e7fd800, 0x880001ff,0x998bdfff,0x77ffcc0b,0x2fffca9b,0x4cc4cd44,0xfb03fffc, 0xff7313df,0x3bff203f,0x713ff661,0x31137fff,0x3001dffb,0x73339fff, 0x889fffff,0x7ffcc4ff,0x1fffb802,0x13fe2000,0x3201ffb8,0x3fff30ff, 0x013ff220,0x00001ff6,0x1ffb9ff6,0xfff50000,0x101fffff,0xfffffffd, 0xffff305f,0x807fffff,0xfffffffd,0x7ffec01e,0xb05fffff,0xffffffff, 0x7dc001df,0xefffffff,0x3e22fffb,0x2fffa84f,0x3ffffff8,0x54cccc00, 0x21999dff,0x3f201ffb,0x3ffff60f,0x6fffedce,0x000ffb00,0x7dcffb00, 0x2600001f,0x0efffffd,0xdfffd910,0x3ffe601b,0x000cefff,0x19dfffd7, 0x3fffae00,0x7f4c02df,0x003effff,0xdffffb30,0x88fffd47,0xfff704ff, 0x1effff83,0x7fffcc00,0xffffffff,0x6403ff71,0x7ffe40ff,0x03efffff, 0x0001ff60,0xffb9ff60,0x31000001,0x00980013,0x00133310,0x80001300, 0x33100009,0x00880000,0x9027fc40,0x55543fff,0xfff30000,0xffffffff, 0x807fee3f,0x75300ffc,0xb0003559,0x300000ff,0x00554c55,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x3bd70000,0x79973100, 0x99953005,0x55550359,0x23555555,0xaa801aa8,0x665cc402,0xccb980ac, 0x555402bc,0xaaaaaaaa,0x02aaa1aa,0xaa86aa60,0x2aa6001a,0xaccb9881, 0x00155500,0xaa88554c,0x00aa6000,0xaaa80997,0xa88d5401,0xaaaaaaaa, 0x7d41aaaa,0x3f6206ff,0x2fffffff,0xfffffea8,0x7ff41fff,0x5fffffff, 0xfd007ff3,0x3fff620d,0x3a4fffff,0xefffffff,0xffffff02,0x9fffffff, 0x2202ffe4,0x3fee0fff,0x1fff1006,0xffffffc8,0x03ffc82f,0x7cc7ff60, 0x1bf2002f,0x103fff54,0xfe80dfff,0xffffff15,0x9fffffff,0x80ffffb8, 0xeeffffe9,0x7fdc3fff,0xffeeeeef,0x7fffff41,0xff35ffff,0x50dfd007, 0xfddfffff,0x777f4bff,0x82ffffed,0xffffffff,0x744fffff,0x3ff201ff, 0x802ffe83,0x3fa23ffc,0xffffeeff,0x0037fcc2,0x17fc4dff,0xea8bfb00, 0x2207ffff,0x3a02ffff,0xfffff15f,0xffffffff,0x86fff989,0x981dfff9, 0x07ffe63c,0x3e200098,0x007ff35f,0xfffb8dfd,0x2a4c981c,0x87ffc880, 0x99999999,0x540fff99,0xdff306ff,0x101bfea0,0xbff98dff,0x207ffdc0, 0xfa800fff,0x00ffe23f,0xffd35fd8,0x440fffdf,0x3a06ffff,0x2666665f, 0xffb99999,0xd80cda83,0x7ec004ff,0x4400003f,0x07ff35ff,0x7fc4dfd0, 0x2200002f,0xd8001fff,0x7ffb03ff,0x6c03ffd0,0x3ff203ff,0x3f601a82, 0x01ffe42f,0x3fe0ffec,0x653fa003,0x0fff2eff,0x0fff7fc4,0xe8005fe8, 0xffa8007f,0x07ff8005,0x5ff88000,0xfd007ff3,0x001ffe4d,0x00ffe400, 0x881bfea0,0x3fee0fff,0x07ffcc04,0x80037fcc,0x7fcc3ffa,0xf86ff805, 0x53fa004f,0x03ffc3f9,0x0bff7ff1,0xf50017fa,0xffd0007f,0x1ffd0003, 0xff880000,0xd007ff35,0x01bfe6df,0x03fe4000,0x003ffe20,0x3fe2bff7, 0x09ff9006,0x20003ffb,0xfff84ff9,0x20ffea00,0x3fa004fe,0x103ffc03, 0x03ff97ff,0xfe800bfd,0x0dff0007,0x037ff200,0x5ff88000,0xfd007ff3, 0x000ffead,0x002ff400,0x7400fff2,0x01ffdaff,0x4c1fff10,0x2a0005ff, 0x2ffc83ff,0x3a07ff20,0x7c1e445f,0x03ffc03f,0xbff17ff1,0x4c00bfd0, 0xf98003ff,0xff30005f,0x200005df,0x7ff35ff8,0x3f2dfd00,0x4400001f, 0x2a001ffd,0x3e6006ff,0x4004ffff,0x3ff64ffb,0x3ff20000,0x205ff981, 0x8bfb06ff,0x17fc0ffb,0xf881ffe0,0xe81ffb3f,0x3ff6005f,0x4ffa8000, 0x3ffea000,0x20000bef,0x7ff35ff8,0x3f6dfd00,0xaaaaa80f,0xfeccc82a, 0x3e2000df,0x7e4000ff,0xf8000fff,0x04ff98ff,0x81bfe200,0x7ff307ff, 0xffd1bf60,0x2017fc47,0x3fe207ff,0xfe89ff33,0x09ff3005,0x00ffee00, 0xffffb100,0xf100019f,0x00ffe6bf,0x43ff5bfa,0x6ffffff8,0xdffffff8, 0x0fff2001,0x13ffe200,0x6e7fd400,0x3a0000ff,0x3ff201ff,0x900ffc82, 0x2fffc4df,0xff803ff1,0xd8ffe207,0x017fa0ff,0x32007fec,0x0ffee1ef, 0x7fe44000,0x44003fff,0x07ff35ff,0x1ffadfd0,0x3fffffe2,0xfedccc86, 0xff9804ff,0xfff70006,0x3fa0001f,0x20003fff,0x7cc04ffd,0x206fe84f, 0x3fbee6fb,0x803ff10f,0x3fe207ff,0xfe8ffea3,0x04ff9805,0xf537ffd4, 0x7000009f,0x4007fffd,0x7ff35ff8,0x3f6dfd00,0x06ff800f,0x409ffb30, 0x8001ffe8,0x05fffff9,0x0dfff300,0x02ffe400,0x7fcc7ff8,0xfe9fee03, 0x1ff33ffa,0x2207ff80,0x87ff43ff,0xffd805fe,0x7fffd400,0x000bff31, 0x07ffe400,0xf35ff880,0x2dfd007f,0xff801ffc,0x07ff4006,0x0003ffc8, 0x5ffd3ffd,0x0bff6000,0x02ffe400,0x7dc3ff90,0x45fea00f,0xf36fd8ff, 0x40fff00f,0x7fd43ff8,0xf980bfd3,0xfffd004f,0x001bfe25,0x05ffb000, 0x7cd7fe20,0x76ff803f,0xdff007ff,0x81ffc800,0x70006ff9,0x3ffe6bff, 0x1ffc8000,0x05ffc800,0xfd27fd40,0xb8ffa80d,0xf51ff55f,0x40fff00f, 0x6fe83ff8,0xffd80bfd,0x3fff3000,0x00017ff4,0x007ff500,0x7fc53fea, 0xf34ff804,0x0dff00df,0xe81ffc80,0xf88001ff,0x13ff20ff,0x007ff200, 0x000bff90,0x1ffcdffe,0x3f63fe60,0x1feaffe2,0xf881ffe0,0xeaffb83f, 0x17fe605f,0x541fff00,0x000006ff,0x6400bfee,0x01bfe2ff,0x7fec7ff5, 0x0037fc02,0x3ff21ffa,0x7ffb0003,0x002fff88,0x9000ffe4,0x64000bff, 0x00ffb9ff,0x07fd7fcc,0x00df5df9,0x7fc40fff,0xbfdbff03,0x000ffec0, 0xffd0bff3,0x4000801d,0x0510fff8,0xfd83ffe2,0x83ffa02f,0x3e03fff9, 0x3fee006f,0x0037fcc4,0xf506ffa8,0xffc800df,0x0bff9001,0xecffa800, 0xdff8806f,0x7effd45f,0x207ff806,0xff703ff8,0x3fe60bff,0x3ffea005, 0xcffffa80,0x33fcaa9b,0x5333559d,0x7c47fff9,0xfffc9abe,0x4e7ffcc4, 0x83ffea88,0x9abdfffc,0x3516ffb9,0x3ffae663,0xccdffe86,0x3ccccccc, 0xe807ffe2,0x3f2004ff,0xfffb801f,0xcccccccc,0x7fffc03c,0xfff8803f, 0x5ffff83f,0x3f333322,0x12ccccff,0x3fe207ff,0x3ffb05ff,0xffffe880, 0x3fffa601,0x33ffffff,0xffffffff,0xff889fff,0x0dffffff,0xffffffb8, 0x3ea04fff,0xffffffff,0xfffff76f,0x981bffff,0xffffffff,0x366fffff, 0x7fcc04ff,0x3ff9001f,0xfffffb00,0xbfffffff,0x0ffffc80,0x01ffff00, 0x7ccbfff9,0xffffffff,0x7ff14fff,0x42fffe40,0xf8805ff9,0x36e004ef, 0x0bceffff,0xffffffb1,0x3aa039ff,0x403effff,0xdfffffd8,0xffec8801, 0xf70befff,0x3bdfffff,0x3ffffe60,0xffffffff,0x001fff56,0x3200dff9, 0xffd801ff,0xffffffff,0x7fd405ff,0x3ffe006f,0x49fff305,0xfffffff9, 0xf14fffff,0x7ffc407f,0x002ffd85,0x18800013,0x03333100,0x20003300, 0x4c000098,0x26662019,0x00000001,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x4c02aa88,0x02aa62aa,0x2a62aa98, 0xaaaaaaaa,0x510aaaaa,0x55555555,0x06aa2555,0x5544aaa0,0x4009aaaa, 0xaaaaaaaa,0x55551aaa,0x35555555,0x2aaaaaa2,0x06a60001,0x55530551, 0x00133555,0x00055550,0x202aaa60,0x9aaaaaa9,0x002aa201,0xabcba880, 0x05fff300,0xff937ff4,0x87ffe203,0xfffffffc,0x1fffffff,0xfffffff3, 0x3e6dffff,0x56fe803f,0xffffffff,0x3fff605d,0x5fffffff,0xfffffffd, 0x3fe6bfff,0x4effffff,0x262fe400,0xffffb87f,0x00cfffff,0x01ffff50, 0xffff9800,0xfffffb81,0x540befff,0xf50003ff,0x05ffffff,0x260bfff5, 0x3ff27fff,0xc85ffb01,0xffffffff,0x31ffffff,0xffffffff,0x3fe6dfff, 0xf56fe803,0xffffffff,0xffffb09f,0x2bffffff,0xfffffffe,0xfff35fff, 0xdfffffff,0x513f6005,0xffff70df,0x1dffffff,0x5ffffb00,0xfffe8000, 0xeeffb81f,0x0efffffe,0x2000ffea,0xfdcdfffc,0x7ffd44ff,0x7fffc80f, 0x3f207ff2,0x3ff2004f,0x1ffc8001,0xd007ff30,0x50ffeadf,0xfd83fff9, 0x01ffa007,0x4c43ff98,0xd802fffd,0x5c37dc3f,0x7f5441ff,0xfdff805f, 0x3ee0005f,0xfb81ffdf,0x6ffea81f,0x3000ffea,0xfe881bff,0x3fb7ea0f, 0x27fcff83,0x7fd41ffc,0x0ffe4005,0x80ffe400,0xfe803ff9,0x3607ff56, 0x03fec4ff,0x4c00ffd0,0x3fee03ff,0x642fe806,0x01ffb85f,0xfa80fff1, 0x0007fe9f,0x3ff79ff1,0x7403ff70,0x07ff52ff,0x100ffe80,0x66fdcbff, 0x7d77d46f,0xf987ff27,0x7e4000ef,0xffc8001f,0x007ff301,0x0ffeadfd, 0x3f62ffd4,0x01ffa007,0x6c03ff98,0x4ccc43ff,0xfd999bff,0x3ff7199d, 0xb007ff40,0x00bfeeff,0x3ee3ff60,0x01ffb81f,0x7fd53fe6,0x13fe2003, 0x3ee1ffb0,0x3f60ff9d,0xff90ffab,0x003ffa23,0x0007ff20,0x7cc07ff2, 0x56fe803f,0x3fe207ff,0xd003fec5,0x7fcc00ff,0x237fc403,0xfffffffb, 0x7fffffff,0x7f403ff7,0xf9affc06,0x7fd4005f,0xf703ff72,0xaffc403f, 0x2a003ffa,0x7fdc03ff,0x4ffabf91,0x0ffa8ff8,0x3ff63ff9,0x3ff90001, 0x03ff9000,0x3a00ffe6,0x207ff56f,0x3fec4ffa,0x400ffd00,0xfe803ff9, 0x7ff77547,0xeeffeeee,0x203ff75e,0x3ea04ff8,0x801ffa2f,0x3fee5ff8, 0x201ffb81,0x7ff55ff8,0x01ffd400,0xafe4bfea,0x26bf76fb,0x73ff90ff, 0x640005ff,0xfc8001ff,0x07ff301f,0x3feadfd0,0x41ffe883,0x3fa007fd, 0x0ffe6007,0x4c03ff60,0xb81ff87f,0xefe981ff,0xc83ff601,0xffb002ff, 0x5c0ffdc1,0x3fe601ff,0x4007ff54,0x7cc04ff9,0x3e2bf93f,0xff32fe9f, 0x3fefff23,0x7fe40004,0x1ffc8001,0xddddff30,0xdffddddd,0x2aab3fea, 0xfd83fffc,0xaaaaaaaf,0xdddffd0a,0x265ddddd,0xffc803ff,0xf88df501, 0xcdffb80f,0x00cffedc,0x3fe62ffc,0x42ffa804,0xffb81ffb,0x547ffa01, 0x7fc003ff,0x53fea00f,0x3f7f65fd,0x7e47fe67,0x0000ffff,0x4000ffe4, 0xff301ffc,0xffffffff,0x3feadfff,0x2effffff,0xffffffb0,0x3fa3ffff, 0xffffffff,0x007ff32f,0x3ee05ff7,0x5c07fcc5,0xffffffff,0x3fea01cf, 0x4407ff82,0x1ffb85fe,0xd981ffb8,0x0ffea4ff,0x35fff700,0x4ffff6a6, 0x3ffea4fd,0x7e4bfe64,0x0006ffcf,0x4000ffe4,0xff301ffc,0x9999999d, 0x3feadff9,0x00efffff,0x3ffffff6,0xffd1ffff,0x99999999,0x200ffe63, 0xbf902ffc,0xff707f98,0xfffd999b,0x03ff605f,0xfc80bff2,0x81ffb80f, 0xeeeeeffb,0x7fd45fff,0xfffd8003,0xffffffff,0x7fc49fd2,0x64bfe21f, 0x04ffc9ff,0x007ff200,0x4c07ff20,0x6fe803ff,0x7fd47ff5,0x00ffb00f, 0xf3003ff4,0x3ffb007f,0xdf513f60,0x2207fee0,0xff81fffb,0x209ff506, 0xff703ff9,0xfffff703,0xf505ffff,0x36a0007f,0xf9adffff,0xfd89fd1f, 0xfc97fc46,0x007ffd1f,0x0007ff20,0x7cc07ff2,0x56fe803f,0x5ffa87ff, 0x7400ffb0,0x3fe6007f,0x30ffe803,0xdddffddd,0x1dddffdd,0xfb807fee, 0x01ffd44f,0x1bfa0fff,0xfb81ffb8,0x01acccdf,0x0000ffea,0x743fee02, 0x220d444f,0x23ff93ff,0x8001fff8,0xc8001ffc,0x7ff301ff,0x3eadfd00, 0x81ffd83f,0x3fa007fd,0x0ffe6007,0x7d4dff10,0xffffffff,0x70ffffff, 0x7fcc03ff,0x7ffffec5,0x1fffffff,0x7fffffd4,0xffffffff,0x003ff75f, 0x0003ffa8,0x7fcffb00,0x27ff1004,0x3fea1ffc,0x7fe4000e,0x1ffc8001, 0xd007ff30,0x20ffeadf,0x7fd85ff9,0x801ffa00,0x7e403ff9,0x3e66624f, 0xcfd999af,0x07fee199,0x7fc5ff88,0xffffffff,0x7fd44fff,0xffffffff, 0xf75fffff,0xffa8003f,0xf9800003,0x800ffe3f,0x83ff93ff,0x64005ffc, 0xfc8001ff,0x07ff301f,0x3feadfd0,0xd83ffd03,0x1ffa007f,0x203ff980, 0xf100fff9,0x703fe81f,0x7fd403ff,0x3337fea3,0xffcccccc,0x55555447, 0xcffdaaaa,0x03ff72aa,0x003ffa80,0x237f4400,0x3fe003ff,0xfb03ff94, 0x7fe4009f,0x1ffc8001,0xd007ff30,0x40ffeadf,0x3fec5ffa,0x400ffd00, 0xff703ff9,0x07fcc07f,0x7fdc0bfe,0x43fff101,0xfd800ffd,0xffb8001f, 0x001ffb81,0x0001ffd4,0x443ffd50,0x3fe003ff,0xf103ff94,0x3f2005ff, 0x5554401f,0xaaabffda,0xd007ff32,0x80ffeadf,0x1ff61ffe,0xaaaffe80, 0xf31aaaaa,0xfdb955bf,0x7fa809ff,0xff701ff8,0xffb75557,0x006ff87f, 0x70009ff5,0x3ff703ff,0xadffa800,0x0aaaaaaa,0x3b72eaa2,0x7fc43fff, 0x653fe003,0xfff301ff,0x03ff9001,0xffffff98,0xf36fffff,0x2dfd007f, 0x3ea03ffa,0x801ff65f,0xfffffffe,0xfff35fff,0x5dffffff,0xf88df500, 0xffff700f,0x87ffffff,0xf1003ffa,0xff7000ff,0x003ff703,0xffffffa8, 0x222fffff,0xcfffffff,0x003ff980,0x0ffe57fe,0x900dff70,0xff9803ff, 0xffffffff,0x007ff36f,0x0ffeadfd,0x3f61fff0,0x3fffa007,0x5fffffff, 0xddfffff3,0x2fdc0039,0x7dc03fe6,0x2cefffff,0x4003ff90,0x5c001ffd, 0x1ffb81ff,0x7fffd400,0x2fffffff,0x2f37bfe2,0x00000001,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x80000000,0x7765c400,0x372a00bd,0x000ceefe,0x17bddb95,0x37bb6e20, 0x2000000b,0x32a00cc9,0xffdb7104,0x666447bd,0xcccccccc,0x6f5472a2, 0x930bbaa2,0x66440199,0x5cc5970c,0x4c982ded,0x20f7fb66,0xca800ccb, 0x0019930c,0x1bb02654,0x2fa80000,0xfffffd30,0xfff905ff,0x07ffffff, 0x7fffff4c,0xfffb85ff,0x002fffff,0xf7003fee,0x07fe403f,0x3fffffea, 0x3ffe66ff,0xffffffff,0x3feaff25,0xffff98ff,0xb027fec3,0xaa7f47ff, 0x44ffffff,0xffff97fb,0x4ffb8bff,0x3e67ff80,0x1bf6002f,0x000f7fdc, 0x40fffb80,0xca9bfff9,0x77e41fff,0xfffecabc,0xcefffa81,0x7e45fcca, 0xffdbacff,0x1ff7003f,0x201ffb80,0x3fe60ffc,0x5cbaaabf,0x33333322, 0x324ffecc,0xafeaefcf,0x445fdafe,0xffa82fff,0x7fdeff45,0x21fffdad, 0xacffcffb,0x3e22fffd,0x27fd406f,0x74007ff1,0x3ffee05f,0x7fe40002, 0x80efe80e,0x004c6ff9,0xff88bff7,0xff98603f,0x0fffa80e,0x400ffb80, 0x3f201ffb,0x003ff60f,0x237fcc00,0xff70fffc,0x261fea5f,0x3fe20fff, 0x7ffff40e,0xf72ffd41,0xff983fff,0xb00ffec6,0x04ff83ff,0xf5013fe0, 0xb10007ff,0xff501bff,0x00ffe405,0xfc8dff10,0x3ff6003f,0x013fee00, 0xf7003fee,0x07fe403f,0x20000dfd,0x7e40fff8,0xa97fee4f,0x5ffb80ff, 0x3fa07ff6,0x6ff880ff,0x7c07ffee,0x827fd47f,0x5fe86ff8,0x3fe22f4c, 0x4ffe9803,0x13ffa600,0x7cc07fd8,0x3fec003f,0xf8801bfe,0x2ffc404f, 0x2007fdc0,0x3f201ffb,0x00bff60f,0x20bff600,0x3fee0ffc,0x6c03fe61, 0x03ffbaff,0x7f403ffd,0xd80bfee7,0x507ff87f,0x8dfb05ff,0x3fe60ffc, 0xbffb1001,0x3fffa801,0x2202ff40,0x4ccc04ff,0x3fe67fd9,0x0bfe6004, 0x2e01ffa0,0x7fdc00ff,0xa83ff201,0x000adfff,0xf903ffc8,0x7cc7fb8d, 0xffff100f,0x037f40bf,0x1ffb8662,0xf903ff20,0x20ffb05f,0x1fffc7fb, 0xc8001ff5,0xff700eff,0xffff003f,0xffffffff,0xfffc88bf,0x2a7fffff, 0x3ee002ff,0x27fd801f,0xfeeeeeec,0x1eeeeeef,0x7e403ff7,0x7fffdc0f, 0xff5002df,0x2e37e40b,0x007fcc7f,0x401ffff5,0xfb8006fe,0x03ff201f, 0xff88bff1,0x261ff504,0x1fee6fff,0x0fffdc00,0x2003bff2,0xfffffff8, 0x25ffffff,0xeeeffffb,0x3fee7ffe,0x07fee002,0x7ec3ff20,0xffffffff, 0xf71fffff,0x07fe403f,0x7ffffe44,0x3bfe201e,0xf71bf200,0x200ff98f, 0x7405fff8,0xffb8006f,0x203ff201,0x3fee0ffd,0x323ff301,0xdf91ffcf, 0x7ffdc000,0x001fff90,0x4c002ffc,0xffb02eff,0x5001ffd4,0xffb005ff, 0x76666654,0xccccccff,0x6403ff70,0x7ed400ff,0xffd01fff,0x5c6fc803, 0x007fcc7f,0x407ffffd,0xfb8006fe,0x03ff201f,0x6fe8ffea,0x7f4bfe20, 0x0bfb4fd9,0x07ffea00,0x2003dff9,0xfc8006fe,0x99ff601f,0x3e6004ff, 0x05ff803f,0x5c00ffb8,0x3ff201ff,0xbffb1000,0x9007ff90,0x4c7fb8df, 0x7ff900ff,0x3fa03ffd,0x1ffb8006,0x7c03ff20,0x807ff36f,0xf76f9bff, 0x20013f6f,0xf700effc,0xffb005ff,0x07fe8003,0x3ffe3fec,0x0dff1000, 0xb803ffa8,0x7fd400ff,0x01fff303,0x7dc6ff80,0x8df9005f,0x07fcc7fb, 0xff8affd4,0x006fe80f,0x3201ffb8,0x3ff900ff,0xfe801ff9,0x3ff14fcc, 0x6c4007ff,0x7cc00dff,0x7fcc03ff,0x07ff4006,0x323ffec4,0xf9000dff, 0x3ffa207f,0x00ffb800,0x7cc2ffcc,0x26000fff,0x1bfe65ff,0x7dc6fc80, 0x2607fcc7,0x3fee0fff,0x8006fe86,0x3f201ffb,0xf9ff300f,0xdbfb00bf, 0x7fe7ec3f,0x9ffd1001,0x27ff4400,0x06bfff60,0x6ffe4753,0xfffff731, 0x337fffd0,0x7fc49b53,0xfea889df,0x1ff7003f,0x13bfff00,0x21ffdff7, 0x2a619bd8,0xffd13ffe,0x33333335,0x3ee37e43,0xd107fcc7,0x9ffb05ff, 0xb8006fe8,0x3ff201ff,0x3ffffa00,0x6fffb801,0x007fffd4,0x001fffcc, 0x806ffec4,0xffffffd8,0x3fe26fff,0xbcffffff,0xfffe987f,0x4c5fffff, 0xffffffff,0x3fee003f,0xffffb800,0x0ffabfff,0xfffffff1,0x7fdc9fff, 0xffffffff,0xb8df91ff,0xb07fcc7f,0x3fe209ff,0x001bfa2f,0xfc807fee, 0x3ffea00f,0x9fff5006,0x807fff88,0x0001fffb,0x500f7fe4,0xdffffffd, 0xffffd889,0x5c0ff71d,0x2dfffffe,0xfffffc88,0x7fdc001d,0xffff5000, 0x443fea5d,0xfffffffe,0x7fffdc2d,0xffffffff,0x7fb8df91,0xffb87fcc, 0x3ffea00e,0x7000dfd1,0x7fe403ff,0x01fffc00,0xd81fff98,0x7fdc06ff, 0xf700000e,0x331001ff,0x00066003,0x88002620,0x00000009,0x88001310, 0x00001999,0x00000000,0x00000000,0x00000000,0x001bb000,0x002f9800, 0x00000000,0x00000000,0x00000000,0x00000000,0x00005530,0x55555554, 0x01aaaaaa,0xcdc98000,0x06f64001,0xddddddd9,0x0000005d,0x00000001, 0x00000000,0x00000000,0xf3000000,0x6fec400d,0x02ffe800,0xffe8fffe, 0xfffffff3,0x27ffffff,0xffb84fff,0xffff701f,0x5cfba07f,0x3ffa6fff, 0x02ffffff,0x00000000,0x00000000,0x00000000,0x00000000,0x400df300, 0x5c05fffb,0xfd00efff,0xf9ffec5f,0xffffffff,0xffd3ffff,0x07ffe607, 0xfffbfff3,0xfd2ff889,0x37721fff,0x01dddddd,0x00000000,0x00000000, 0x00000000,0x00000000,0x22fc4150,0xffff700a,0x3a7fe201,0x45ffd04f, 0x80002ffd,0x36203ffe,0x43ff21ff,0xf90dffe8,0x3ffff63f,0x00000000, 0x00000000,0x00000000,0x00000000,0x7c400000,0x7ec53e3f,0x3ffff104, 0x7fd53f20,0x361ffd81,0xd80002ff,0xdeb802ff,0xfe88bfd0,0x225fffff, 0x00002ffe,0x00000000,0x00000000,0x00000000,0x00000000,0xf8dffc88, 0x203fffac,0xf980fffb,0x3617f60f,0x07ff21ff,0x0bff6000,0xc81ee400, 0x980effff,0x00000000,0x00000000,0x00000000,0x00000000,0x44000000, 0x3ffffffc,0xb07ff980,0x42ff989f,0x3ff20ffc,0xfffffff1,0x27ffffff, 0x00001ffc,0x000aee60,0x00000000,0x00000000,0x00000000,0x00000000, 0x7cc00000,0x3ee005ff,0x80ffa84f,0x3ff20ffc,0x7fc3fee0,0xffffffff, 0x3ff93fff,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x22000000,0x2efffffb,0xe837fdc0,0x49ff103f,0x50cc4198,0x55555555, 0x26235555,0x00000001,0x00000000,0x00000000,0x00000000,0x00000000, 0x88000000,0xbcf9effc,0x3fa62eff,0x6fb81eff,0x000ffdc0,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x27ff1000, 0x49fb14f8,0x3203eff9,0x02cc801c,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x10540000,0x0620b8bf,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x05f98000,0xddddd000,0xdddddddd,0x0007dddd,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00df3000,0x3ffffe00, 0xffffffff,0x0004ffff,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00013000,0x2aaaaaa0,0xaaaaaaaa,0x00001aaa, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000, }; static signed short stb__consolas_32_usascii_x[95]={ 0,6,4,0,1,0,0,7,4,4,2,1,3,4, 6,1,1,2,2,2,0,2,1,1,1,1,6,3,2,2,3,4,0,0,2,1,1,3,3,1,1,2,2,2, 3,0,1,0,2,0,2,1,1,1,0,0,0,0,1,5,2,4,1,0,0,2,2,2,1,1,0,1,2,2, 2,2,2,1,2,1,2,1,3,2,0,2,1,0,1,0,2,2,7,3,1, }; static signed short stb__consolas_32_usascii_y[95]={ 23,0,0,2,-1,0,1,0,-1,-1,0,6,17,13, 18,0,2,2,2,2,2,2,2,2,2,2,7,7,5,10,5,0,0,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,27,0,7,0,7,0,7,0,7,0,0, 0,0,0,7,7,7,7,7,7,7,2,7,7,7,7,7,7,0,-3,0,11, }; static unsigned short stb__consolas_32_usascii_w[95]={ 0,5,10,17,15,18,18,4,10,9,14,16,9,10, 6,15,16,14,14,14,17,14,15,15,15,15,6,9,13,14,13,11,18,18,14,15,16,12,12,15,15,13,12,15, 13,17,15,17,14,18,15,15,16,15,18,17,18,18,15,9,14,9,15,18,11,14,14,13,15,15,17,16,14,14, 12,15,14,16,14,16,14,15,14,13,16,14,16,18,16,17,14,13,4,13,16, }; static unsigned short stb__consolas_32_usascii_h[95]={ 0,24,9,21,28,24,23,9,31,31,15,17,12,3, 6,27,22,21,21,22,21,22,22,21,22,21,17,22,19,9,19,24,30,21,21,22,21,21,21,22,21,21,22,21, 21,21,21,22,21,27,21,22,21,22,21,21,21,21,21,30,27,30,11,3,8,17,24,17,24,17,23,23,23,23, 30,23,23,16,16,17,23,23,16,17,22,17,16,16,16,23,16,30,33,30,7, }; static unsigned short stb__consolas_32_usascii_s[95]={ 241,223,178,141,107,173,1,204,6,17,137, 91,152,245,238,142,200,209,157,88,193,185,217,240,233,240,249,1,15,189,1, 229,78,174,159,11,124,111,98,72,66,52,43,19,226,1,224,167,211,123,82, 27,35,56,172,191,119,138,103,97,158,68,162,162,209,45,208,60,192,29,101, 84,69,54,55,20,241,152,201,74,135,119,186,123,150,108,216,233,169,36,137, 27,1,41,221, }; static unsigned short stb__consolas_32_usascii_t[95]={ 25,1,121,82,1,1,35,121,1,1,121, 104,121,121,121,1,35,59,59,59,82,35,35,59,35,82,35,59,104,121,104, 1,1,82,82,59,82,82,82,59,82,82,59,82,82,82,59,35,82,1,82, 59,82,59,59,59,59,59,59,1,1,1,121,133,121,104,1,104,1,104,35, 35,35,35,1,35,1,104,104,104,35,35,104,104,35,104,104,104,104,35,104, 1,1,1,121, }; static unsigned short stb__consolas_32_usascii_a[95]={ 282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 282,282,282,282,282,282,282, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_consolas_32_usascii_BITMAP_HEIGHT or STB_FONT_consolas_32_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_consolas_32_usascii(stb_fontchar font[STB_FONT_consolas_32_usascii_NUM_CHARS], unsigned char data[STB_FONT_consolas_32_usascii_BITMAP_HEIGHT][STB_FONT_consolas_32_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__consolas_32_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_consolas_32_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_consolas_32_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_consolas_32_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_consolas_32_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_consolas_32_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__consolas_32_usascii_s[i]) * recip_width; font[i].t0 = (stb__consolas_32_usascii_t[i]) * recip_height; font[i].s1 = (stb__consolas_32_usascii_s[i] + stb__consolas_32_usascii_w[i]) * recip_width; font[i].t1 = (stb__consolas_32_usascii_t[i] + stb__consolas_32_usascii_h[i]) * recip_height; font[i].x0 = stb__consolas_32_usascii_x[i]; font[i].y0 = stb__consolas_32_usascii_y[i]; font[i].x1 = stb__consolas_32_usascii_x[i] + stb__consolas_32_usascii_w[i]; font[i].y1 = stb__consolas_32_usascii_y[i] + stb__consolas_32_usascii_h[i]; font[i].advance_int = (stb__consolas_32_usascii_a[i]+8)>>4; font[i].s0f = (stb__consolas_32_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__consolas_32_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__consolas_32_usascii_s[i] + stb__consolas_32_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__consolas_32_usascii_t[i] + stb__consolas_32_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__consolas_32_usascii_x[i] - 0.5f; font[i].y0f = stb__consolas_32_usascii_y[i] - 0.5f; font[i].x1f = stb__consolas_32_usascii_x[i] + stb__consolas_32_usascii_w[i] + 0.5f; font[i].y1f = stb__consolas_32_usascii_y[i] + stb__consolas_32_usascii_h[i] + 0.5f; font[i].advance = stb__consolas_32_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_consolas_32_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_32_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_32_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_32_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_32_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_32_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_32_usascii_LINE_SPACING #endif
65
123
0.787792
348159ff209f445fb25dd54f0c7f876f36c2bb02
623
cpp
C++
QEdit/src/CFGReader.cpp
JannikNickel/QEdit
8d09bcdc6fd4a8e2ecf969edb852de8a1c43dd7e
[ "MIT" ]
null
null
null
QEdit/src/CFGReader.cpp
JannikNickel/QEdit
8d09bcdc6fd4a8e2ecf969edb852de8a1c43dd7e
[ "MIT" ]
null
null
null
QEdit/src/CFGReader.cpp
JannikNickel/QEdit
8d09bcdc6fd4a8e2ecf969edb852de8a1c43dd7e
[ "MIT" ]
null
null
null
#include "CFGReader.h" CFGReader::CFGReader(std::ifstream* file) { if(file == nullptr) { return; } std::string line; while(getline(*file, line)) { long index = line.find('='); if(index != std::string::npos) { std::string attribute = line.substr(0, index); std::string value = line.substr(index + 1, line.length() - (index + 1)); if(!pairs.contains(attribute)) { pairs.insert(std::pair<std::string, std::string>(attribute, value)); } } } file->close(); } std::string CFGReader::Read(std::string attribute) { if(pairs.contains(attribute)) { return pairs[attribute]; } return ""; }
18.878788
75
0.629213
34851f8db2d45beda90ff00a004978998bc317ea
2,863
hpp
C++
include/codegen/include/System/Threading/AbandonedMutexException.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Threading/AbandonedMutexException.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Threading/AbandonedMutexException.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:45 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.SystemException #include "System/SystemException.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: Mutex class Mutex; // Forward declaring type: WaitHandle class WaitHandle; } // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; // Forward declaring type: StreamingContext struct StreamingContext; } // Completed forward declares // Type namespace: System.Threading namespace System::Threading { // Autogenerated type: System.Threading.AbandonedMutexException class AbandonedMutexException : public System::SystemException { public: // private System.Int32 m_MutexIndex // Offset: 0x88 int m_MutexIndex; // private System.Threading.Mutex m_Mutex // Offset: 0x90 System::Threading::Mutex* m_Mutex; // public System.Void .ctor(System.Int32 location, System.Threading.WaitHandle handle) // Offset: 0x13C0370 static AbandonedMutexException* New_ctor(int location, System::Threading::WaitHandle* handle); // private System.Void SetupException(System.Int32 location, System.Threading.WaitHandle handle) // Offset: 0x13C040C void SetupException(int location, System::Threading::WaitHandle* handle); // public System.Void .ctor() // Offset: 0x13C02F4 // Implemented from: System.SystemException // Base method: System.Void SystemException::.ctor() // Base method: System.Void Exception::.ctor() // Base method: System.Void Object::.ctor() static AbandonedMutexException* New_ctor(); // protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x13C0494 // Implemented from: System.SystemException // Base method: System.Void SystemException::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) static AbandonedMutexException* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context); }; // System.Threading.AbandonedMutexException } DEFINE_IL2CPP_ARG_TYPE(System::Threading::AbandonedMutexException*, "System.Threading", "AbandonedMutexException"); #pragma pack(pop)
46.934426
162
0.747468
348607e6739ad68f3ca92c3db60ded07b791a985
2,734
cpp
C++
src/scexpressionparser.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
1
2020-12-13T16:56:32.000Z
2020-12-13T16:56:32.000Z
src/scexpressionparser.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
null
null
null
src/scexpressionparser.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
null
null
null
#include "include/scexpressionparser.h" #include <QStack> #include <QDebug> #include "include/sctokenoperations.h" const SCExpressionParser SCExpressionParser::shared; SCExpressionParser::SCExpressionParser() {} SCParsedExpression SCExpressionParser::parse(const SCInExpression &exp) { QStack<SCToken> opStack; SCParsedExpression parsedExp; QList<SCToken> tokens = exp.getTokens(); QString partialToken = exp.getPartialToken(); if (!partialToken.isEmpty()) { SCToken *tokenFromPartial = SCTokenOperations::token(exp.getPartialToken()); tokens.append(*tokenFromPartial); delete tokenFromPartial; } for (auto token : tokens) { SCTokenTypes::TokenType type = token.getType(); if (type == SCTokenTypes::operand) parsedExp.addToken(token); else if (type == SCTokenTypes::lParenthesis) opStack.push(token); else if (type == SCTokenTypes::rParenthesis) { SCToken topOp(opStack.pop()); while (topOp.getType() != SCTokenTypes::lParenthesis) { parsedExp.addToken(topOp); topOp = opStack.pop(); } } else if (type == SCTokenTypes::lBracket) opStack.push(token); else if (type == SCTokenTypes::rBracket) { SCToken topOp(opStack.pop()); while (topOp.getType() != SCTokenTypes::lBracket) { parsedExp.addToken(topOp); topOp = opStack.pop(); } } else if (type == SCTokenTypes::unaryOperator || type == SCTokenTypes::binaryOperator) { SCOperator *newOp = static_cast<SCOperator *>(SCTokenOperations::token(token.getToken())); bool shouldLook = true; while (shouldLook && !opStack.isEmpty()) { SCOperator *topOp = static_cast<SCOperator *>(SCTokenOperations::token(opStack.top().getToken())); if ((topOp->getType() == binaryOperator || topOp->getType() == unaryOperator) && newOp->getPrecedence() <= topOp->getPrecedence()) { opStack.pop(); parsedExp.addToken(*topOp); delete topOp; if (!opStack.isEmpty()) topOp = static_cast<SCOperator *>(SCTokenOperations::token(opStack.top().getToken())); } else shouldLook = false; } opStack.push(*newOp); delete newOp; } } while (!opStack.isEmpty()) parsedExp.addToken(opStack.pop()); return parsedExp; }
30.719101
114
0.557059
348bafc7e3314b9fc89b277c6e4b7730831638be
1,001
cpp
C++
Server/Server/src/core/item/item.cpp
vahmoh26/Messenger
3413b2eedbb5ed867928c2dfe17ad2c118712f6e
[ "MIT" ]
null
null
null
Server/Server/src/core/item/item.cpp
vahmoh26/Messenger
3413b2eedbb5ed867928c2dfe17ad2c118712f6e
[ "MIT" ]
null
null
null
Server/Server/src/core/item/item.cpp
vahmoh26/Messenger
3413b2eedbb5ed867928c2dfe17ad2c118712f6e
[ "MIT" ]
null
null
null
#include "item.h" #include <sstream> #include <boost/iostreams/stream.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> namespace server::core { using namespace boost; item::item() { _type = type::unknown; } item::item(type type) : item() { set_type(type); } item::item(const protocol::package& package) { iostreams::array_source array_source(package.get_buffer().data(), package.get_buffer().size()); iostreams::stream<boost::iostreams::array_source> stream(array_source); archive::text_iarchive text_iarchive(stream); text_iarchive >> _type; } item::~item() { } void item::set_type(type type) { _type = type; } void item::set_ip(const string& ip) { _ip = ip; } item::type item::get_type() { return _type; } const string& item::get_ip() const { return _ip; } bool item::valid() { return _type > type::unknown && _type <= type::logout; } protocol::package item::to_package() { return {}; } }
15.4
97
0.669331
348e1436324a8a5116a0d47c51a987498a14e5ac
28,923
hpp
C++
src/attention_layer.hpp
isi-nlp/Zoph_RNN
1e3e7da688cfcd0cdfb0c117cb84705399d1a967
[ "MIT" ]
199
2015-08-30T18:45:02.000Z
2021-11-04T09:04:20.000Z
src/attention_layer.hpp
isi-nlp/Zoph_RNN
1e3e7da688cfcd0cdfb0c117cb84705399d1a967
[ "MIT" ]
12
2016-03-07T04:37:23.000Z
2019-04-10T08:14:06.000Z
src/attention_layer.hpp
isi-nlp/Zoph_RNN
1e3e7da688cfcd0cdfb0c117cb84705399d1a967
[ "MIT" ]
72
2015-08-17T23:00:21.000Z
2021-11-29T14:03:58.000Z
template<typename dType> attention_layer<dType>::attention_layer(int LSTM_size,int minibatch_size, int device_number, int D, int longest_sent,cublasHandle_t &handle,neuralMT_model<dType> *model, bool feed_input,bool clip_gradients,dType norm_clip,bool dropout,dType dropout_rate,global_params &params,bool bi_side) { this->handle = handle; this->model = model; this->device_number = device_number; this->LSTM_size = LSTM_size; this->minibatch_size = minibatch_size; this->clip_gradients = clip_gradients; this->norm_clip = norm_clip; this->feed_input = feed_input; this->longest_sent = longest_sent; this->multi_attention_v2 = params.multi_src_params.multi_attention_v2; cudaSetDevice(device_number); layer_info.init(device_number,D); dType *h_temp; full_matrix_setup(&h_temp,&d_W_a,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p,1,LSTM_size); full_matrix_setup(&h_temp,&d_output_bias,LSTM_size,1); full_matrix_setup(&h_temp,&d_W_c_p1,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_a_grad,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p_grad,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p_grad,1,LSTM_size); full_matrix_setup(&h_temp,&d_output_bias_grad,LSTM_size,1); full_matrix_setup(&h_temp,&d_W_c_p1_grad,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p2_grad,LSTM_size,LSTM_size); if(multi_attention_v2) { full_matrix_setup(&h_temp,&d_W_a_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p_v2,1,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p3_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_a_grad_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p_grad_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p_grad_v2,1,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p3_grad_v2,LSTM_size,LSTM_size); } //cudaMemset(d_output_bias,0,LSTM_size*sizeof(dType)); full_matrix_setup(&h_temp,&d_ERRnTOt_tan_htild,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_ct,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_ht_p1,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_as,2*D+1,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_pt,1,minibatch_size); full_matrix_setup(&h_temp,&d_temp_1,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_h_t_Wa_factor,2*D+1,minibatch_size); if(multi_attention_v2) { full_matrix_setup(&h_temp,&d_ERRnTOt_ct_v2,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_as_v2,2*D+1,minibatch_size); full_matrix_setup(&h_temp,&d_ERRnTOt_pt_v2,1,minibatch_size); full_matrix_setup(&h_temp,&d_temp_1_v2,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_h_t_Wa_factor_v2,2*D+1,minibatch_size); } full_vector_setup_ones(&h_temp,&d_ones_minibatch,minibatch_size); curandCreateGenerator(&rand_gen,CURAND_RNG_PSEUDO_DEFAULT); boost::uniform_int<> unif_boost( 1, 1000000 ); curandSetPseudoRandomGeneratorSeed(rand_gen,BZ_CUDA::curr_seed); BZ_CUDA::curr_seed+=7; thrust_d_W_a_grad = thrust::device_pointer_cast(d_W_a_grad); thrust_d_v_p_grad = thrust::device_pointer_cast(d_v_p_grad); thrust_d_W_p_grad = thrust::device_pointer_cast(d_W_p_grad); thrust_d_W_c_p1_grad = thrust::device_pointer_cast(d_W_c_p1_grad); thrust_d_W_c_p2_grad = thrust::device_pointer_cast(d_W_c_p2_grad); thrust_d_output_bias_grad = thrust::device_pointer_cast(d_output_bias_grad); if(multi_attention_v2) { thrust_d_W_a_grad_v2 = thrust::device_pointer_cast(d_W_a_grad_v2); thrust_d_v_p_grad_v2 = thrust::device_pointer_cast(d_v_p_grad_v2); thrust_d_W_p_grad_v2 = thrust::device_pointer_cast(d_W_p_grad_v2); thrust_d_W_c_p3_grad_v2 = thrust::device_pointer_cast(d_W_c_p3_grad_v2); } CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_result, 1*sizeof(dType)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_temp_result, NORM_THREADS*sizeof(dType)),"GPU memory allocation failed\n"); clear_gradients(); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_t_sum, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_s_sum, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); if(multi_attention_v2) { CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_t_sum_v2, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_s_sum_v2, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); } for(int i=0; i<longest_sent; i++) { nodes.push_back( attention_node<dType>(LSTM_size,minibatch_size,device_number,D,feed_input,this,i,dropout,dropout_rate,params.multi_src_params.multi_attention,multi_attention_v2) ); } //now construct d_total_hs_mat dType **h_total_hs_mat = (dType **)malloc(longest_sent*sizeof(dType*)); dType **h_total_hs_error = (dType **)malloc(longest_sent*sizeof(dType*)); dType **h_total_hs_mat_v2; dType **h_total_hs_error_v2; if(multi_attention_v2) { h_total_hs_mat_v2 = (dType **)malloc(longest_sent*sizeof(dType*)); h_total_hs_error_v2 = (dType **)malloc(longest_sent*sizeof(dType*)); } for(int i=0; i<longest_sent; i++) { if(params.bi_dir_params.bi_dir) { h_total_hs_mat[i] = model->bi_dir_source.d_final_mats[i]; h_total_hs_error[i] = model->bi_dir_source.d_final_errors[i]; } else { if(model->source_hidden_layers.size() == 0) { if(!bi_side) { h_total_hs_mat[i] = model->input_layer_source.nodes[i].d_h_t; h_total_hs_error[i] = model->input_layer_source.nodes[i].d_d_ERRt_ht; if(multi_attention_v2) { h_total_hs_mat_v2[i] = model->input_layer_source_bi.nodes[i].d_h_t; h_total_hs_error_v2[i] = model->input_layer_source_bi.nodes[i].d_d_ERRt_ht; } } else { h_total_hs_mat[i] = model->input_layer_source_bi.nodes[i].d_h_t; h_total_hs_error[i] = model->input_layer_source_bi.nodes[i].d_d_ERRt_ht; } } else { if(!bi_side) { h_total_hs_mat[i] = model->source_hidden_layers[model->source_hidden_layers.size()-1].nodes[i].d_h_t; h_total_hs_error[i] = model->source_hidden_layers[model->source_hidden_layers.size()-1].nodes[i].d_d_ERRt_ht; if(multi_attention_v2) { h_total_hs_mat_v2[i] = model->source_hidden_layers_bi[model->source_hidden_layers.size()-1].nodes[i].d_h_t; h_total_hs_error_v2[i] = model->source_hidden_layers_bi[model->source_hidden_layers.size()-1].nodes[i].d_d_ERRt_ht; } } else { h_total_hs_mat[i] = model->source_hidden_layers_bi[model->source_hidden_layers.size()-1].nodes[i].d_h_t; h_total_hs_error[i] = model->source_hidden_layers_bi[model->source_hidden_layers.size()-1].nodes[i].d_d_ERRt_ht; } } } } CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_mat, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_error, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_batch_info, 2*minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); cudaMemcpy(d_total_hs_mat,h_total_hs_mat,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); cudaMemcpy(d_total_hs_error,h_total_hs_error,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); free(h_total_hs_mat); if(multi_attention_v2) { CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_mat_v2, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_error_v2, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_batch_info_v2, 2*minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); cudaMemcpy(d_total_hs_mat_v2,h_total_hs_mat_v2,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); cudaMemcpy(d_total_hs_error_v2,h_total_hs_error_v2,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); free(h_total_hs_mat_v2); } } template<typename dType> void attention_layer<dType>::init_att_decoder(int LSTM_size,int beam_size, int device_number, int D, int longest_sent,cublasHandle_t &handle,neuralMT_model<dType> *model, bool feed_input,std::vector<dType*> &top_source_states,bool multi_attention_v2,std::vector<dType*> &top_source_states_v2) { this->handle = handle; this->model = model; this->device_number = device_number; this->LSTM_size = LSTM_size; this->minibatch_size = beam_size; this->longest_sent = longest_sent; this->multi_attention_v2 = multi_attention_v2; cudaSetDevice(device_number); layer_info.init(device_number,D); dType *h_temp; full_matrix_setup(&h_temp,&d_W_a,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p,1,LSTM_size); full_matrix_setup(&h_temp,&d_output_bias,LSTM_size,1); full_matrix_setup(&h_temp,&d_W_c_p1,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_temp_1,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_h_t_Wa_factor,2*D+1,minibatch_size); full_vector_setup_ones(&h_temp,&d_ones_minibatch,minibatch_size); if(multi_attention_v2) { full_matrix_setup(&h_temp,&d_W_a_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_W_p_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_v_p_v2,1,LSTM_size); full_matrix_setup(&h_temp,&d_W_c_p3_v2,LSTM_size,LSTM_size); full_matrix_setup(&h_temp,&d_temp_1_v2,LSTM_size,minibatch_size); full_matrix_setup(&h_temp,&d_h_t_Wa_factor_v2,2*D+1,minibatch_size); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_t_sum_v2, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_s_sum_v2, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); } CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_t_sum, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_h_s_sum, LSTM_size*minibatch_size*sizeof(dType)),"GPU memory allocation failed\n"); for(int i=0; i<1; i++) { nodes.push_back( attention_node<dType>(LSTM_size,minibatch_size,device_number,D,false,this,i,false,1,false,multi_attention_v2) ); } //now construct d_total_hs_mat dType **h_total_hs_mat = (dType **)malloc(longest_sent*sizeof(dType*)); for(int i=0; i<longest_sent; i++) { h_total_hs_mat[i] = top_source_states[i]; //cudaMemset(top_source_states[i],0,LSTM_size*minibatch_size*sizeof(dType)); } dType **h_total_hs_mat_v2; if(multi_attention_v2) { h_total_hs_mat_v2 = (dType **)malloc(longest_sent*sizeof(dType*)); for(int i=0; i<longest_sent; i++) { h_total_hs_mat_v2[i] = top_source_states_v2[i]; } } CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_ones_minibatch_int,minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); thrust::device_ptr<int> ones_ptr = thrust::device_pointer_cast(d_ones_minibatch_int); for(int i=0; i<minibatch_size; i++) { ones_ptr[i] = 1; } nodes[0].d_indicies_mask = &d_ones_minibatch_int; //std::cout << "MINIBATCH SIZE IN INITIALIZATION: " << minibatch_size << "\n"; CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_mat, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_batch_info, 2*minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); cudaMemcpy(d_total_hs_mat,h_total_hs_mat,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); if(multi_attention_v2) { CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_total_hs_mat_v2, longest_sent*sizeof(dType*)),"GPU memory allocation failed\n"); CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_batch_info_v2, 2*minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); cudaMemcpy(d_total_hs_mat_v2,h_total_hs_mat_v2,longest_sent*sizeof(dType*),cudaMemcpyHostToDevice); free(h_total_hs_mat_v2); } if(BZ_CUDA::unk_replacement) { //std::cout << "UNK REPLACEMENT SET TO TRUE\n"; CUDA_ERROR_WRAPPER(cudaMalloc((void**)&d_viterbi_alignments, minibatch_size*sizeof(int)),"GPU memory allocation failed\n"); } free(h_total_hs_mat); } template<typename dType> void attention_layer<dType>::clear_gradients() { cudaSetDevice(device_number); cudaMemsetAsync(d_W_a_grad,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_W_p_grad,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_v_p_grad,0,LSTM_size*1*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_output_bias_grad,0,LSTM_size*1*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_W_c_p1_grad,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_W_c_p2_grad,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); if(multi_attention_v2) { cudaMemsetAsync(d_W_a_grad_v2,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_W_p_grad_v2,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_v_p_grad_v2,0,LSTM_size*1*sizeof(dType),layer_info.s0); cudaMemsetAsync(d_W_c_p3_grad_v2,0,LSTM_size*LSTM_size*sizeof(dType),layer_info.s0); } devSynchAll(); } template<typename dType> void attention_layer<dType>::clip_gradients_func() { norm_clip_GPU_v2(thrust_d_W_a_grad,d_W_a_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_W_p_grad,d_W_p_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_v_p_grad,d_v_p_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_output_bias_grad,d_output_bias_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_W_c_p1_grad,d_W_c_p1_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_W_c_p2_grad,d_W_c_p2_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); if(multi_attention_v2) { norm_clip_GPU_v2(thrust_d_W_a_grad_v2,d_W_a_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_W_p_grad_v2,d_W_p_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_v_p_grad_v2,d_v_p_grad_v2,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2(thrust_d_W_c_p3_grad_v2,d_W_c_p3_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); } } template<typename dType> void attention_layer<dType>::scale_gradients() { scale_functor unary_op(minibatch_size); thrust::for_each(thrust_d_W_a_grad,thrust_d_W_a_grad + LSTM_size*LSTM_size,unary_op); thrust::for_each(thrust_d_W_p_grad,thrust_d_W_p_grad + LSTM_size*LSTM_size,unary_op); thrust::for_each(thrust_d_v_p_grad,thrust_d_v_p_grad + LSTM_size*1,unary_op); thrust::for_each(thrust_d_output_bias_grad,thrust_d_output_bias_grad + LSTM_size*1,unary_op); thrust::for_each(thrust_d_W_c_p1_grad,thrust_d_W_c_p1_grad + LSTM_size*LSTM_size,unary_op); thrust::for_each(thrust_d_W_c_p2_grad,thrust_d_W_c_p2_grad + LSTM_size*LSTM_size,unary_op); if(multi_attention_v2) { thrust::for_each(thrust_d_W_a_grad_v2,thrust_d_W_a_grad_v2 + LSTM_size*LSTM_size,unary_op); thrust::for_each(thrust_d_W_p_grad_v2,thrust_d_W_p_grad_v2 + LSTM_size*LSTM_size,unary_op); thrust::for_each(thrust_d_v_p_grad_v2,thrust_d_v_p_grad_v2 + LSTM_size*1,unary_op); thrust::for_each(thrust_d_W_c_p3_grad_v2,thrust_d_W_c_p3_grad_v2 + LSTM_size*LSTM_size,unary_op); } } template<typename dType> void attention_layer<dType>::update_params() { gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_a,d_W_a_grad,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_p,d_W_p_grad,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); gradient_update_mats<<<std::min(256,(LSTM_size*1 + 256 - 1)/256),256,0,layer_info.s0>>>(d_v_p,d_v_p_grad,model->input_layer_target.learning_rate,LSTM_size*1); gradient_update_mats<<<std::min(256,(LSTM_size*1 + 256 - 1)/256),256,0,layer_info.s0>>>(d_output_bias,d_output_bias_grad,model->input_layer_target.learning_rate,LSTM_size*1); gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p1,d_W_c_p1_grad,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p2,d_W_c_p2_grad,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); if(multi_attention_v2) { gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_a_v2,d_W_a_grad_v2,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_p_v2,d_W_p_grad_v2,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); gradient_update_mats<<<std::min(256,(LSTM_size*1 + 256 - 1)/256),256,0,layer_info.s0>>>(d_v_p_v2,d_v_p_grad_v2,model->input_layer_target.learning_rate,LSTM_size*1); gradient_update_mats<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p3_v2,d_W_c_p3_grad_v2,model->input_layer_target.learning_rate,LSTM_size*LSTM_size); } } template<typename dType> void attention_layer<dType>::norm_p1() { // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING ATTENTION GRADIENTS -----------------------\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_a_grad,d_W_a_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_a_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_p_grad,d_W_p_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_p_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_v_p_grad,d_v_p_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_v_p_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_output_bias_grad,d_output_bias_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_output_bias_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_c_p1_grad,d_W_c_p1_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_c_p1_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_c_p2_grad,d_W_c_p2_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_c_p2_grad -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } if(multi_attention_v2) { norm_clip_GPU_v2_p1(thrust_d_W_a_grad_v2,d_W_a_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_a_grad_v2 -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_p_grad_v2,d_W_p_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_p_grad_v2 -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_v_p_grad_v2,d_v_p_grad_v2,norm_clip,LSTM_size*1,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_v_p_grad_v2 -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } norm_clip_GPU_v2_p1(thrust_d_W_c_p3_grad_v2,d_W_c_p3_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); // if(BZ_CUDA::print_norms) { // HPC_output << "----------------------- PRINTING GRAD NORM FOR d_W_c_p3_grad_v2 -----------------------\n"; // HPC_output << BZ_CUDA::recent_sum << "\n"; // } } } template<typename dType> void attention_layer<dType>::norm_p2() { norm_clip_GPU_v2_p2(thrust_d_W_a_grad,d_W_a_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_W_p_grad,d_W_p_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_v_p_grad,d_v_p_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_output_bias_grad,d_output_bias_grad,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_W_c_p1_grad,d_W_c_p1_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_W_c_p2_grad,d_W_c_p2_grad,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); if(multi_attention_v2) { norm_clip_GPU_v2_p2(thrust_d_W_a_grad_v2,d_W_a_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_W_p_grad_v2,d_W_p_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_v_p_grad_v2,d_v_p_grad_v2,norm_clip,LSTM_size*1,d_temp_result,d_result); norm_clip_GPU_v2_p2(thrust_d_W_c_p3_grad_v2,d_W_c_p3_grad_v2,norm_clip,LSTM_size*LSTM_size,d_temp_result,d_result); } } template<typename dType> void attention_layer<dType>::clip_indiv() { clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_a_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_p_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); clip_mat_kernel<<<std::min(256,(LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_v_p_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*1); clip_mat_kernel<<<std::min(256,(LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_output_bias_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*1); clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p1_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p2_grad,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); if(multi_attention_v2) { clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_a_grad_v2,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_p_grad_v2,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); clip_mat_kernel<<<std::min(256,(LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_v_p_grad_v2,BZ_CUDA::ind_norm_clip_thres,LSTM_size*1); clip_mat_kernel<<<std::min(256,(LSTM_size*LSTM_size + 256 - 1)/256),256,0,layer_info.s0>>>(d_W_c_p3_grad_v2,BZ_CUDA::ind_norm_clip_thres,LSTM_size*LSTM_size); } devSynchAll(); } template<typename dType> void attention_layer<dType>::dump_weights(std::ofstream &output) { write_matrix_GPU(d_W_a,LSTM_size,LSTM_size,output); write_matrix_GPU(d_W_p,LSTM_size,LSTM_size,output); write_matrix_GPU(d_v_p,LSTM_size,1,output); write_matrix_GPU(d_output_bias,LSTM_size,1,output); write_matrix_GPU(d_W_c_p1,LSTM_size,LSTM_size,output); write_matrix_GPU(d_W_c_p2,LSTM_size,LSTM_size,output); if(multi_attention_v2) { write_matrix_GPU(d_W_a_v2,LSTM_size,LSTM_size,output); write_matrix_GPU(d_W_p_v2,LSTM_size,LSTM_size,output); write_matrix_GPU(d_v_p_v2,LSTM_size,1,output); write_matrix_GPU(d_W_c_p3_v2,LSTM_size,LSTM_size,output); } } template<typename dType> void attention_layer<dType>::load_weights(std::ifstream &input) { read_matrix_GPU(d_W_a,LSTM_size,LSTM_size,input); read_matrix_GPU(d_W_p,LSTM_size,LSTM_size,input); read_matrix_GPU(d_v_p,LSTM_size,1,input); read_matrix_GPU(d_output_bias,LSTM_size,1,input); read_matrix_GPU(d_W_c_p1,LSTM_size,LSTM_size,input); read_matrix_GPU(d_W_c_p2,LSTM_size,LSTM_size,input); if(multi_attention_v2) { read_matrix_GPU(d_W_a_v2,LSTM_size,LSTM_size,input); read_matrix_GPU(d_W_p_v2,LSTM_size,LSTM_size,input); read_matrix_GPU(d_v_p_v2,LSTM_size,1,input); read_matrix_GPU(d_W_c_p3_v2,LSTM_size,LSTM_size,input); } } template<typename dType> void attention_layer<dType>::check_gradients(dType epsilon) { std::cout << "--------------------GRADIENT CHECKING FOR ATTENTION LAYER GPU-------------------------\n"; std::cout << "GRADIENT CHECKING FOR W_c_p1\n"; check_gradient_GPU(epsilon,d_W_c_p1,d_W_c_p1_grad,LSTM_size,LSTM_size); std::cout << "GRADIENT CHECKING FOR W_c_p2\n"; check_gradient_GPU(epsilon,d_W_c_p2,d_W_c_p2_grad,LSTM_size,LSTM_size); std::cout << "GRADIENT CHECKING FOR OUTPUT BIAS\n"; check_gradient_GPU(epsilon,d_output_bias,d_output_bias_grad,LSTM_size,1); std::cout << "GRADIENT CHECKING FOR v_p\n"; check_gradient_GPU(epsilon,d_v_p,d_v_p_grad,LSTM_size,1); std::cout << "GRADIENT CHECKING FOR W_p\n"; check_gradient_GPU(epsilon,d_W_p,d_W_p_grad,LSTM_size,LSTM_size); std::cout << "GRADIENT CHECKING FOR W_a\n"; check_gradient_GPU(epsilon,d_W_a,d_W_a_grad,LSTM_size,LSTM_size); if(multi_attention_v2) { std::cout << "GRADIENT CHECKING FOR v_p_v2\n"; check_gradient_GPU(epsilon,d_v_p_v2,d_v_p_grad_v2,LSTM_size,1); std::cout << "GRADIENT CHECKING FOR W_p_v2\n"; check_gradient_GPU(epsilon,d_W_p_v2,d_W_p_grad_v2,LSTM_size,LSTM_size); std::cout << "GRADIENT CHECKING FOR W_a_v2\n"; check_gradient_GPU(epsilon,d_W_a_v2,d_W_a_grad_v2,LSTM_size,LSTM_size); std::cout << "GRADIENT CHECKING FOR W_c_p3_v2\n"; check_gradient_GPU(epsilon,d_W_c_p3_v2,d_W_c_p3_grad_v2,LSTM_size,LSTM_size); } } template<typename dType> void attention_layer<dType>::check_gradient_GPU(dType epsilon,dType *d_mat,dType *d_grad,int rows,int cols) { cudaSetDevice(device_number); thrust::device_ptr<dType> d_thrust_mat = thrust::device_pointer_cast(d_mat); thrust::device_ptr<dType> d_thrust_grad = thrust::device_pointer_cast(d_grad); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { dType loss =0; d_thrust_mat[IDX2C(i,j,rows)]+= epsilon; loss = model->getError(true); cudaSetDevice(device_number); cudaDeviceSynchronize(); d_thrust_mat[IDX2C(i,j,rows)]+= -2*epsilon; loss -=model->getError(true); cudaSetDevice(device_number); cudaDeviceSynchronize(); d_thrust_mat[IDX2C(i,j,rows)]+= epsilon; //std::cout << "My gradient: " << d_thrust_grad[IDX2C(i,j,rows)] << "\n"; std::cout << "Gradient difference: " << std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon)) << " my gradient: " << d_thrust_grad[IDX2C(i,j,rows)] <<"\n"; if( (std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon))) > 1/(dType)1000.0 || (std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon))/(std::abs(d_thrust_grad[IDX2C(i,j,rows)]) + std::abs(loss/(2*epsilon)))) > 1/1000.0 ) { std::cout << "Gradient for gradient check: " << loss/(2*epsilon) << "\n"; std::cout << "My gradient: " << d_thrust_grad[IDX2C(i,j,rows)] << "\n"; std::cout << "Gradient difference: " << std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon)) << "\n"; std::cout << "Gradient difference (Equation 2): " << std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon))/(std::abs(d_thrust_grad[IDX2C(i,j,rows)]) + std::abs(loss/(2*epsilon)) ) << "\n\n"; } else if(d_thrust_grad[IDX2C(i,j,rows)]==0 ||loss/(2*epsilon) ==0) { std::cout << "ZERO GRADIENTS\n"; std::cout << "Gradient for gradient check: " << loss/(2*epsilon) << "\n"; std::cout << "My gradient: " << d_thrust_grad[IDX2C(i,j,rows)] << "\n"; std::cout << "Gradient difference: " << std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon)) << "\n"; std::cout << "Gradient difference (Equation 2): " << std::abs(d_thrust_grad[IDX2C(i,j,rows)] - loss/(2*epsilon))/(std::abs(d_thrust_grad[IDX2C(i,j,rows)]) + std::abs(loss/(2*epsilon)) ) << "\n\n"; } } } } template<typename dType> void attention_layer<dType>::prep_minibatch_info(int *h_batch_info) { cudaSetDevice(device_number); cudaMemcpy(d_batch_info,h_batch_info,2*minibatch_size*sizeof(int),cudaMemcpyHostToDevice); } template<typename dType> void attention_layer<dType>::prep_minibatch_info_v2(int *h_batch_info_v2) { cudaSetDevice(device_number); cudaMemcpy(d_batch_info_v2,h_batch_info_v2,2*minibatch_size*sizeof(int),cudaMemcpyHostToDevice); }
48.856419
240
0.763959
3492168940e6c054403efb893ccd2ae5e67eee86
271
cpp
C++
Olamundo/02/freq03/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
Olamundo/02/freq03/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
Olamundo/02/freq03/main.cpp
tosantos1/LIP
7dbc045afa02729f4e2f2f1d3b29baebf5be72ad
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int opa(int a); int main() { int n; cin >> n; cout << opa(n); return 0; } int opa(int n){ if(n == 1 || n == 0){ return n; }else{ return opa(n - 1) + opa (n-2); } return 0; }
10.037037
38
0.450185
34925620a1745cc31dfa47a1a0ebdb4a7abec0c6
2,306
hpp
C++
mln.hpp
pisa-engine/mln
9c03f78de5539c245a991b209a8a406f9fc64892
[ "Apache-2.0" ]
null
null
null
mln.hpp
pisa-engine/mln
9c03f78de5539c245a991b209a8a406f9fc64892
[ "Apache-2.0" ]
null
null
null
mln.hpp
pisa-engine/mln
9c03f78de5539c245a991b209a8a406f9fc64892
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <array> #include <cstddef> #include <cstdint> #include <iostream> #include <numeric> template <size_t Q> class mln { using Table = std::array<std::array<uint8_t, Q>, Q>; static Table generate_compression_table(const uint32_t *in, const size_t n) { std::array<std::array<uint32_t, Q>, Q> freq_table{}; for (int i = 0; i < n - 1; ++i) { uint32_t current = in[i]; uint32_t next = in[i + 1]; if (current <= Q and next <= Q) { freq_table[current - 1][next - 1] += 1; } } Table t{}; for (int i = 0; i < freq_table.size(); ++i) { auto freq_row = freq_table[i]; std::array<uint8_t, Q> idx; std::iota(idx.begin(), idx.end(), 0); std::stable_sort(idx.begin(), idx.end(), [&](size_t i1, size_t i2) { return freq_row[i1] > freq_row[i2]; }); for (int j = 0; j < freq_row.size(); ++j) { t[i][idx[j]] = j + 1; } } return t; } static Table generate_decompression_table(Table &t) { Table dt{}; for (int i = 0; i < t.size(); ++i) { for (int j = 0; j < t[0].size(); ++j) { dt[i][t[i][j]-1] = j+1; } } return dt; } public: static Table encode(const uint32_t *in, const size_t n, uint32_t *out) { auto t = generate_compression_table(in, n); out[0] = in[0]; for (int i = 1; i < n; ++i) { auto prev = in[i - 1]; auto current = in[i]; if (prev <= Q and current <= Q) { out[i] = t[prev - 1][current - 1]; } else { out[i] = in[i]; } } return generate_decompression_table(t); } static void decode(const uint32_t *in, uint32_t *out, size_t n, Table &t) { out[0] = in[0]; auto prev = out[0]; for (int i = 1; i < n; ++i) { auto current = in[i]; if (prev <= Q and current <= Q) { out[i] = t[prev - 1][current - 1]; } else { out[i] = in[i]; } prev = out[i]; } } };
28.469136
80
0.436687
349327048909567c2b1b78effa6490a6774928e0
334
cpp
C++
modules/cpp-alignlib-wrapper/src/wrapalignlib.cpp
wwPDB/py-wwpdb_utils_align
424a285b455ee894b728526166ac244aaef6bd5c
[ "Apache-2.0" ]
null
null
null
modules/cpp-alignlib-wrapper/src/wrapalignlib.cpp
wwPDB/py-wwpdb_utils_align
424a285b455ee894b728526166ac244aaef6bd5c
[ "Apache-2.0" ]
null
null
null
modules/cpp-alignlib-wrapper/src/wrapalignlib.cpp
wwPDB/py-wwpdb_utils_align
424a285b455ee894b728526166ac244aaef6bd5c
[ "Apache-2.0" ]
1
2020-09-12T17:12:32.000Z
2020-09-12T17:12:32.000Z
// File: ./src/wrapalignlib.cpp // Date: 2018-10-15 // #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; using namespace pybind11::literals; void wrapPairwiseAlign(py::module &); void wrapPseudoMultiAlign(py::module &); PYBIND11_MODULE(alignlib, m) { wrapPairwiseAlign(m); wrapPseudoMultiAlign(m); }
20.875
40
0.748503
34946d44745756e2ec3f3c918ad22612c3b6c769
1,568
cpp
C++
training/Codeforces/765E.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/Codeforces/765E.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/Codeforces/765E.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 10:47 on 15 Feb 2017 #include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_N = 2e5 + 10; int N, u, v, ans; vector<int> G[MAX_N]; int dfs(int v, int p) { set<int> h; for (auto u : G[v]) if (u != p) { int res = dfs(u, v); if (res == -1) return -1; else h.insert(res + 1); } if (!h.size()) return 0; if (h.size() == 1) return *h.begin(); if (!p && h.size() == 2) return *h.begin() + *h.rbegin(); u = v; return -1; } int main(int argc, char const *argv[]) { scanf("%d", &N); rep(i, 1, N) scanf("%d%d", &u, &v), G[v].push_back(u), G[u].push_back(v); u = 0; ans = dfs(1, 0); if (u) ans = dfs(u, 0); while (~ans && !(ans & 1)) ans /= 2; printf("%d\n", ans); return 0; }
27.034483
118
0.568878
34980dd4ee5102d7f277e8da22a98350b5762241
4,210
cpp
C++
samples/widgets/app/app.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
5
2019-10-04T05:10:06.000Z
2021-02-03T23:29:10.000Z
samples/widgets/app/app.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
null
null
null
samples/widgets/app/app.cpp
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
2
2019-09-27T00:34:36.000Z
2020-10-27T09:44:26.000Z
// // Copyright © 2020 Sandcastle Software Ltd. All rights reserved. // // This file is part of 'Oaknut' which is released under the MIT License. // See the LICENSE file in the root of this installation for details. // #include <oaknut.h> class Drawer : public LinearLayout { public: Drawer() : LinearLayout() { _orientation = Vertical; } bool applySingleStyle(const string& name, const style& value) override { return LinearLayout::applySingleStyle(name, value); } void setSelectedSubview(View* subview) override { View::setSelectedSubview(subview); if (subview != _selectedSubview) { if (_onSelectedSubviewChanged) { _onSelectedSubviewChanged(subview); } _selectedSubview = subview; } } std::function<void(View*)> _onSelectedSubviewChanged; View* _selectedSubview; }; DECLARE_DYNCREATE(Drawer); class Tabs : public LinearLayout { protected: sp<RectRenderOp> _selectedOp; float _barHeight; public: Tabs() : LinearLayout() { _selectedOp = new RectRenderOp(); _hideScrollbars = true; addDecorOp(_selectedOp); } bool applySingleStyle(const string& name, const style& value) override { if (name == "bar-color") { _selectedOp->setFillColor(value.colorVal()); return true; } if (name == "bar-height") { _barHeight = value.floatVal(); setNeedsLayout(); return true; } if (name == "tabs") { auto tabs = value.arrayVal(); for (auto& vtab : tabs) { auto title = vtab.stringVal(); Button* button = new Button(); button->setSelectable(true); button->applyStyle("material_design.Tabs.Button"); button->setText(title); button->setImage("star.png"); addSubview(button); } return true; } return LinearLayout::applySingleStyle(name, value); } void setSelectedSubview(View* subview) override { for (auto& it : _subviews) { if (!it->isSelectable()) { continue; } bool selected = subview == it._obj; it->setSelected(selected); if (selected) { RECT oldRect = _selectedOp->_rect; RECT rectTarget = it->getRect(); rectTarget.origin.y = rectTarget.bottom() - _barHeight; rectTarget.size.height = _barHeight; if (oldRect.size.width <=0) { _selectedOp->setRect(rectTarget); } else { Animation::start(this, 300, [=](float val) { RECT rect = rectTarget; rect.origin.x = oldRect.origin.x + (rectTarget.origin.x-oldRect.origin.x) * val; rect.size.width = oldRect.size.width + (rectTarget.size.width-oldRect.size.width) * val; _selectedOp->setRect(rect); }, Animation::strongEaseOut); } } } } }; DECLARE_DYNCREATE(Tabs); class MainViewController : public ViewController { public: MainViewController() { inflate("layout/main.res"); bind(_drawer, "drawer"); bind(_content, "content"); _drawer->_onSelectedSubviewChanged = [=](View* selectedSubview) { int index = _drawer->indexOfSubview(selectedSubview); if (index == 1) { _content->setCurrentSubview(0); } else { _content->setCurrentSubview(1); } }; /*ShadowRenderOp* shadow = new ShadowRenderOp(); shadow->setSigma(0); shadow->setRect(RECT(50,50,200,200)); view->addRenderOp(shadow);*/ } Drawer* _drawer; ViewSwitcher* _content; }; class WidgetsApp : public App { public: void main() override { MainViewController* mainVC = new MainViewController(); _window->setRootViewController(mainVC); }; }; static WidgetsApp the_app;
27.337662
108
0.553682
349ba7372ae75faf9748c31dd57c25d3c5bad952
11,795
hh
C++
BdbTime/BdbTime.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
BdbTime/BdbTime.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
BdbTime/BdbTime.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
#ifndef BDBTIME_HH #define BDBTIME_HH //----------------------------------------------------------------------------- // // File and Version Information: // $Id: BdbTime.hh 496 2010-01-13 17:10:44Z stroili $ // // Description: // Class BdbTime. // This is a persistent time class. // // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Author List: // J. Ohnemus Original Author // Gregory Dubois-Felsmann Rogue Wave migration, 2002/2003 // // Copyright Information: // Copyright (C) 1994, 1995 Lawrence Berkeley Laboratory // Copyright (c) 2002, 2003 California Institute of Technology // //----------------------------------------------------------------------------- //----------------- // BaBar Headers -- //----------------- #include "BaBar/BaBarODMGTypes.h" //----------------- // C/C++ Headers -- //----------------- #include <time.h> #include <iostream> #include <string> //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "BdbTime/BdbDuration.hh" #include "BdbTime/BdbTimeConst.hh" //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ // --------------------- // -- Class Interface -- // --------------------- class BdbTime { public: enum Zone { Local, UTC }; // Constructors /** * (Deprecated) * Constructs with the current time, to the nearest second. This * constructor is deprecated and may be removed in a future release. * The static function BdbTime::now() should be used in preference * to this in all new code, if the current time is really required. * * For some reason, the original implementation did not set the _gmtNsec * member, perhaps because it was not easy to get it synchronized with * the Rogue Wave "now()" function's return value. Now that we use * clock_gettime() directly, this could be fixed. * * However, we have decided not to do this at this time, in order not * to change the behavior of existing programs. * * BdbTime::now() preserves the full significance available from * clock_gettime(). * * Please note that this constructor involves a system call and is * expensive! Do not default-construct BdbTimes unless you really need * the current time value. If you are just declaring a time variable * to fill in later, BdbTime(0) is a more performant choice. */ BdbTime( ); /** Copy constructor. */ BdbTime( const BdbTime& t ); /** * Constructs a time from an unsigned number of seconds since the * BdbTime epoch of 1901. NB: this is not the Unix epoch of 1970! */ explicit BdbTime( d_ULong sec_since_1901, d_ULong nsec = 0 ); /** * Constructs a time from a broken-down list of components of a date * and time. * * This uses definitions inherited from the old RogueWave implementation * of BdbTime. Thus "year" is the calendar year C.E. (e.g., 2003), and * "month" is the month in the range {1..12}. Note that these differ * from the POSIX broken-down time (struct tm) definitions, where * 2003 C.E. is represented as 103, and the month is in the range {0..11}. */ BdbTime( d_ULong year, d_ULong month, d_ULong day, d_ULong hour, d_ULong minute, d_ULong second, d_ULong nanosecond = 0, Zone zone = UTC ); /** * (Deprecated - use parseTime()) * Constructs a BdbTime from a string date and a string time. * * The use of this constructor is strongly discouraged, as it does not * have a means of reliably reporting parsing errors (BaBar does not * use C++ exceptions). Use BdbTime::parseTime() instead (which this * is implemented over). */ BdbTime( const std::string& date, const std::string& time, Zone zone = UTC ); /** * (Deprecated - use parseTime()) * Constructs a BdbTime from a single date-time string, in which the * date and time must be given separated by whitespace. Otherwise * identical to the above constructor. * * The use of this constructor is strongly discouraged, as it does not * have a means of reliably reporting parsing errors (BaBar does not * use C++ exceptions). Use BdbTime::parseTime() instead (which this * is implemented over). */ explicit BdbTime( const std::string&, Zone zone = UTC ); /** * Constructs from POSIX high-resolution time, as might be * obtained from clock_gettime. */ BdbTime( const struct timespec& ts ); /** * Constructs from POSIX "broken-down time". * @param stm Cannot be const because it is internally provided to * POSIX mktime(), which normalizes it -- see man mktime. */ BdbTime( struct tm& stm, Zone zone = UTC ); /** * The destructor is non-virtual in order to keep this representational * class small and suitable for processing with value semantics. * Classes with non-empty destructors should not be constructed with * non-private inheritance from BdbTime. */ ~BdbTime( ) { } // Assignment operator BdbTime& operator=( const BdbTime& t ); // Calculational operators /** * Calculates the absolute value of the difference between two times. * NB: BdbDuration is an inherently unsigned quantity! This is * in essence because reasonably foreseeable time differences are * larger in seconds than 2^31 and so can't be represented as a * signed 32 bit integer. */ BdbDuration operator-( const BdbTime& t ) const; BdbTime& operator+=( const BdbDuration& d ); BdbTime operator+( const BdbDuration& d ) const; BdbTime& operator-=( const BdbDuration& d ); BdbTime operator-( const BdbDuration& d ) const; // Comparison operators bool operator==( const BdbTime& t ) const { return ( _gmtSec == t._gmtSec && _gmtNsec == t._gmtNsec ); } bool operator!=( const BdbTime& t ) const { return !( *this == t ); } bool operator<( const BdbTime& t ) const { return ( _gmtSec < t._gmtSec ) || ( _gmtSec == t._gmtSec && _gmtNsec < t._gmtNsec ); } bool operator<=( const BdbTime& t ) const { return ( _gmtSec < t._gmtSec ) || ( _gmtSec == t._gmtSec && _gmtNsec <= t._gmtNsec ); } bool operator>( const BdbTime& t ) const { return !( *this <= t ); } bool operator>=( const BdbTime& t ) const { return !( *this < t ); } // Selectors d_ULong getGmtSec( ) const { return _gmtSec; } d_ULong getGmtNsec( ) const { return _gmtNsec; } /** * Extracts the value of the BdbTime as a POSIX.1b "struct timespec". * Returns 0 on success in analogy with POSIX.1b clock_gettime(). * WARNING: Must and will fail for valid BdbTime values that are more * than 2^31-1 seconds before the beginning of the POSIX 1970 epoch, * i.e., before around 1901.12.13 20:45:53 UTC. * * There are such times in the conditions database from early * SP production, before all times were renormalized into 1997+ space. */ int timeSpec( struct timespec* ts ) const; /** * Extracts the value of the BdbTime as a POSIX "struct tm" broken-down * time. This requires the use of a time zone. In analogy with the * POSIX.1b gmtime_r() function, a pointer to a "struct tm" to receive * the data must be supplied -- so this function is thread-safe(*). * Following this analogy, the function returns the supplied pointer * on success, and 0 on failure. * * This function should work for all times in the BdbTime range. */ struct tm* tm( struct tm* stm, Zone zone ) const; /** * Creates a string from the value of the BdbTime, based on a * specified format specification, as for POSIX strftime(), and on * a time zone. Note that this function does not provide a way * to embed the "nanoseconds" part of the BdbTime, since this is * not possible to express in a form recognized by strftime. * * The "%N" format specified does not appear to be used in the POSIX * definition of strftime. It's possible it could be hijacked in a * future upgrade. FIXME * * This function should work for all times in the BdbTime range. */ std::string asString( const char* fmt, Zone zone ) const; // Friends friend BdbTime operator+( const BdbDuration& d, const BdbTime& t ); friend std::ostream& operator<<( std::ostream& os, const BdbTime& t ); private: void renormalizeNanoseconds( ); // Data members d_ULong _gmtSec; // number of seconds since 00:00:00 Jan. 1, 1901 UTC d_ULong _gmtNsec; // number of nanoseconds public: // static interfaces: /** * Constructs and returns a BdbTime representing the current time. * This interface, unlike the deprecated default constructor, returns * a BdbTime set to the full resolution available from clock_gettime(). * Note that this may vary between platforms and even operating * system versions. */ static BdbTime now(); /** * Determines whether a string representing a date and a string * representing a time can be converted successfully to a date/time * in BdbTime format, i.e., in the unsigned 1901 epoch. * * Note that 1901.01.01 00:00:00 UTC is not a valid time; 00:00:01 * is the first valid time. * * Date is parsed using strptime formats "%D" and "%d%b%Y", controlled * by BdbTimeInput, with the first one that succeeds taking precedence. * Time is parsed with formats "%T" and "%R". These are quite a * restricted set compared to those originally accepted by the * Rogue Wave implementation first used here. * * By default times are interpreted as UTC (a logical alternative might * be the local time zone. If an invalid date or time string is supplied, * the BdbTime time will be set to -Infinity. If the date string is set to * "+Infinity" or "-Infinity", the time string will be ignored and the * BdbTime will be set to the corresponding value. * * @param time Returned time value; modified only if parsing is successful. * @return Flag indicating whether parsing was successful. */ static bool parseTime( const std::string& sdate, const std::string& stime, Zone zone, BdbTime& time ); /** * Determines whether a string representing a date and time can be * converted successfully to a date/time in BdbTime format, i.e., in * the unsigned 1901 epoch. * * Equivalent to a call to parseTime( const std::string& sdate, * const std::string& stime, Zone zone, BdbTime& time ) * with the date and time set from the first and second whitespace- * delimited tokens in the sdatetime string and subsequent text ignored. * * This is a less precise parsing method than the above. * * @param time Returned time value; modified only if parsing is successful. * @return Flag indicating whether parsing was successful. */ static bool parseTime( const std::string& sdatetime, Zone zone, BdbTime& time ); // Static members static const BdbTime minusInfinity; static const BdbTime plusInfinity; }; inline void BdbTime::renormalizeNanoseconds( ) { if ( _gmtNsec >= BdbTimeConst::nsecInASec ) { // carry nanoseconds over into seconds d_ULong extraSec = _gmtNsec / BdbTimeConst::nsecInASec; d_ULong remainNsec = _gmtNsec % BdbTimeConst::nsecInASec; _gmtSec += extraSec; _gmtNsec = remainNsec; } } #endif
34.188406
79
0.635693
34a130d2f192dabab62ccfa996c7233cbfd19e29
434
cc
C++
exercises/ESEMPI_BASE/operatori_aritmetici.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
3
2021-11-05T16:25:50.000Z
2022-02-10T14:06:00.000Z
exercises/ESEMPI_BASE/operatori_aritmetici.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
null
null
null
exercises/ESEMPI_BASE/operatori_aritmetici.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
2
2018-10-31T14:53:40.000Z
2020-01-09T22:34:37.000Z
using namespace std; #include <iostream> int main () { int n = 7; int m = 3; cout << "n = " << n << endl; cout << "m = " << m << endl; cout << "n+m = " << n+m << endl; cout << "n-m = " << n-m << endl; cout << "n*m = " << n*m << endl; cout << "n/m = " << n/m << endl; cout << "n%m = " << n%m << endl; cout << "-(n-m) = " << -(n-m) << endl; cout << "-n-m = " << -n-m << endl; return 0; }
17.36
40
0.368664
34af9fbebdb458197455883fd2889c4ad5b4a65f
1,788
cpp
C++
src/main/utils.cpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
src/main/utils.cpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
src/main/utils.cpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
#include <SDL/SDL.h> #include <SDL/SDL_ttf.h> #include "graphicsEditor.hpp" #include "utils.hpp" SDL_Color translate_color(Uint32 int_color) { #if SDL_BYTEORDER != SDL_BIG_ENDIAN SDL_Color color={ (Uint8) ((int_color & 0x00ff0000)/0x10000), (Uint8) ((int_color & 0x0000ff00)/0x100), (Uint8) (int_color & 0x000000ff), 0}; #else SDL_Color color={ (Uint8) (int_color & 0x000000ff), (Uint8) ((int_color & 0x0000ff00)/0x100), (Uint8) ((int_color & 0x00ff0000)/0x10000), 0}; #endif return color; } void renderText(SDL_Surface* screen, SDL_Rect dst, const char* message, int fontSize, Uint32 color) { SDL_Surface* textSurface; TTF_Font* fnt; if (!(fnt = TTF_OpenFont("../public/Ubuntu.ttf", fontSize))) { return; } if ((textSurface = TTF_RenderUTF8_Blended(fnt, message, translate_color(color)))) { SDL_BlitSurface(textSurface, NULL, screen, &dst); SDL_FreeSurface(textSurface); textSurface = NULL; } TTF_CloseFont(fnt); } char* IntToHexChars(int value) { char* result = new char[7]; sprintf(result, "#%06X", value); return result; } char* IntToChars(int value) { char* result = new char[3]; sprintf(result, "%d", value); return result; } Uint32 createRGB(int r, int g, int b) { return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff); } Uint32 getpixel(SDL_Surface * surface, int x, int y) { int bpp = surface->format->BytesPerPixel; Uint8 * p = (Uint8 *) surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: return *p; case 2: return *(Uint16 *) p; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; case 4: return *(Uint32 *) p; default: return 0; } }
24.833333
101
0.630313
34b072586a0bd73e7f7ce8ab30fc9e1f3d7410ee
7,245
cpp
C++
Tests/GuiTests/DFNs/DisparityImage/DisparityImageEdres.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
Tests/GuiTests/DFNs/DisparityImage/DisparityImageEdres.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
Tests/GuiTests/DFNs/DisparityImage/DisparityImageEdres.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @author Clément Bazerque */ /** * Test application for the DFN DisparityImageEdres */ /** * @addtogroup DFNsTest * @{ */ #include <DisparityImage/DisparityImageEdres.hpp> #include <GuiTests/ParametersInterface.hpp> #include <GuiTests/MainInterface.hpp> #include <GuiTests/DFNs/DFNTestInterface.hpp> #include <Visualizers/OpenCVVisualizer.hpp> #include <Errors/Assert.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs/imgcodecs.hpp> #include <opencv2/highgui/highgui.hpp> using namespace CDFF::DFN::DisparityImage; using namespace FrameWrapper; class DisparityImageEdresTestInterface : public DFNTestInterface { public: DisparityImageEdresTestInterface(const std::string& dfnName, int buttonWidth, int buttonHeight); ~DisparityImageEdresTestInterface(); private: DisparityImageEdres disparityImageEdres; cv::Mat cvLeftImage; cv::Mat cvRightImage; std::string outputWindowName; void SetupParameters() override; void DisplayResult() override; }; DisparityImageEdresTestInterface::DisparityImageEdresTestInterface(const std::string& dfnName, int buttonWidth, int buttonHeight) : DFNTestInterface(dfnName, buttonWidth, buttonHeight), disparityImageEdres() { SetDFN(&disparityImageEdres); // Loads two grayscaled rectified images cvLeftImage = cv::imread("../../tests/Data/Images/MinnieStereo/MinnieRectDeg3Left.png", cv::IMREAD_GRAYSCALE); cvRightImage = cv::imread("../../tests/Data/Images/MinnieStereo/MinnieRectDeg3Right.png", cv::IMREAD_GRAYSCALE); // Initialise a frame pair and set its metadata asn1SccFramePair *framePair = new asn1SccFramePair(); asn1SccFramePair_Initialize(framePair); framePair->msgVersion = frame_Version; framePair->baseline = 0.270268442641143; // Fill the left image data { framePair->left.msgVersion = frame_Version; framePair->left.metadata.msgVersion = frame_Version; framePair->left.metadata.status = asn1Sccstatus_VALID; framePair->left.metadata.pixelModel = asn1Sccpix_UNDEF; framePair->left.metadata.mode = asn1Sccmode_GRAY; framePair->left.intrinsic.msgVersion = frame_Version; framePair->left.intrinsic.cameraModel = asn1Scccam_PINHOLE; framePair->left.intrinsic.cameraMatrix.arr[0].arr[0] = 1069.23438117834; framePair->left.intrinsic.cameraMatrix.arr[0].arr[1] = 0; framePair->left.intrinsic.cameraMatrix.arr[0].arr[2] = 956.907250034732; framePair->left.intrinsic.cameraMatrix.arr[1].arr[0] = 0; framePair->left.intrinsic.cameraMatrix.arr[1].arr[1] = 1071.73940921359; framePair->left.intrinsic.cameraMatrix.arr[1].arr[2] = 621.662860111553; framePair->left.intrinsic.cameraMatrix.arr[2].arr[0] = 0; framePair->left.intrinsic.cameraMatrix.arr[2].arr[1] = 0; framePair->left.intrinsic.cameraMatrix.arr[2].arr[2] = 1; asn1SccArray3D &imageOnly = framePair->left.data; imageOnly.msgVersion = array3D_Version; imageOnly.rows = static_cast<asn1SccT_UInt32>(cvLeftImage.rows); imageOnly.cols = static_cast<asn1SccT_UInt32>(cvLeftImage.cols); imageOnly.channels = static_cast<asn1SccT_UInt32>(cvLeftImage.channels()); imageOnly.depth = static_cast<asn1SccArray3D_depth_t>(cvLeftImage.depth()); imageOnly.rowSize = cvLeftImage.step[0]; imageOnly.data.nCount = static_cast<int>(imageOnly.rows * imageOnly.rowSize); memcpy(imageOnly.data.arr, cvLeftImage.data, static_cast<size_t>(imageOnly.data.nCount)); } // Fill the right image data { framePair->right.msgVersion = frame_Version; framePair->right.metadata.msgVersion = frame_Version; framePair->right.metadata.status = asn1Sccstatus_VALID; framePair->right.metadata.pixelModel = asn1Sccpix_UNDEF; framePair->right.metadata.mode = asn1Sccmode_GRAY; framePair->right.intrinsic.msgVersion = frame_Version; framePair->right.intrinsic.cameraModel = asn1Scccam_PINHOLE; framePair->right.intrinsic.cameraMatrix.arr[0].arr[0] = 1066.44771376037; framePair->right.intrinsic.cameraMatrix.arr[0].arr[1] = 0; framePair->right.intrinsic.cameraMatrix.arr[0].arr[2] = 943.937535155249; framePair->right.intrinsic.cameraMatrix.arr[1].arr[0] = 0; framePair->right.intrinsic.cameraMatrix.arr[1].arr[1] = 1069.28469804725; framePair->right.intrinsic.cameraMatrix.arr[1].arr[2] = 617.141031157546; framePair->right.intrinsic.cameraMatrix.arr[2].arr[0] = 0; framePair->right.intrinsic.cameraMatrix.arr[2].arr[1] = 0; framePair->right.intrinsic.cameraMatrix.arr[2].arr[2] = 1; asn1SccArray3D &imageOnly = framePair->right.data; imageOnly.msgVersion = array3D_Version; imageOnly.rows = static_cast<asn1SccT_UInt32>(cvRightImage.rows); imageOnly.cols = static_cast<asn1SccT_UInt32>(cvRightImage.cols); imageOnly.channels = static_cast<asn1SccT_UInt32>(cvRightImage.channels()); imageOnly.depth = static_cast<asn1SccArray3D_depth_t>(cvRightImage.depth()); imageOnly.rowSize = cvRightImage.step[0]; imageOnly.data.nCount = static_cast<int>(imageOnly.rows * imageOnly.rowSize); memcpy(imageOnly.data.arr, cvRightImage.data, static_cast<size_t>(imageOnly.data.nCount)); } // Set the DFN input with this image pair disparityImageEdres.framePairInput(*framePair); outputWindowName = "Disparity Image Result"; delete(framePair); } DisparityImageEdresTestInterface::~DisparityImageEdresTestInterface() { } void DisparityImageEdresTestInterface::SetupParameters() { AddParameter("DisparityParams", "minDistance", 1.0, 100.0); AddParameter("DisparityParams", "maxDistance", 40.0, 100.0); AddParameter("DisparityParams", "method", 1, 4); AddParameter("DisparityParams", "grad", 2, 5); AddParameter("DisparityParams", "gradType", 5, 8); AddParameter("DisparityParams", "dispType", 8, 8); AddParameter("FilterParams", "filter", 1, 1); AddParameter("FilterParams", "trimWidth", 3, 100, 1); AddParameter("FilterParams", "connexityThresh", 2, 10, 0.1); AddParameter("FilterParams", "surfMin", 20, 1000, 10); AddParameter("FilterParams", "surfMax", 1000, 5000, 10); } void DisparityImageEdresTestInterface::DisplayResult() { // Fetch the resulting disparity image asn1SccFrame* res = new asn1SccFrame(); *res = disparityImageEdres.disparityOutput(); PRINT_TO_LOG("Processing time (seconds): ", GetLastProcessingTimeSeconds()); PRINT_TO_LOG("Virtual memory used (kB): ", GetTotalVirtualMemoryUsedKB()); // Convert the disparity image as a cv::Mat for display cv::Mat disparity = cv::Mat(res->data.rows, res->data.cols, CV_MAKETYPE((int)(res->data.depth), res->data.channels), res->data.data.arr, res->data.rowSize); // Apply a colormap cv::Mat dispColor; double min, max; cv::minMaxLoc(disparity, &min, &max); disparity.convertTo(disparity, CV_8U, 255 / (max - min), -255.0 * min / (max - min)); cv::Mat mask = disparity > 0; cv::applyColorMap(disparity, disparity, 2); disparity.copyTo(dispColor, mask); // Display the disparity cv::namedWindow(outputWindowName, CV_WINDOW_NORMAL); cv::imshow(outputWindowName, dispColor); cv::resizeWindow(outputWindowName, dispColor.cols, dispColor.rows); cv::waitKey(500); delete(res); } int main(int argc, char** argv) { DisparityImageEdresTestInterface* interface = new DisparityImageEdresTestInterface("DisparityImageEdres", 100, 40); interface->Run(); delete(interface); }; /** @} */
38.333333
157
0.757902
34b0b7cb584507f7860dc717ae0d4d5746ee8dc8
3,093
cpp
C++
src/Solver/NumericalJacobian.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Solver/NumericalJacobian.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Solver/NumericalJacobian.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Routines for numerically evaluating the jacobian numerically * in the non-linear solver. */ #include <iostream> #include "DREAM/Solver/SolverNonLinear.hpp" #include "FVM/BlockMatrix.hpp" #include "FVM/UnknownQuantity.hpp" using namespace DREAM; /** * Evaluate jacobian numerically using finite difference * of the residual function. * * jac: Jacobian matrix. */ void SolverNonLinear::_EvaluateJacobianNumerically( FVM::BlockMatrix *jac ) { printf("Evaluating Jacobian numerically... 0.00%%"); len_t nSize = this->unknowns->GetLongVectorSize(this->nontrivial_unknowns); const real_t *iniVec = this->unknowns->GetLongVector(this->nontrivial_unknowns); real_t *dFVec = new real_t[nSize]; real_t *FVec = new real_t[nSize]; real_t *iniFVec = new real_t[nSize]; real_t *xhVec = new real_t[nSize]; // Copy initial vector to shifted solution vector for (len_t i = 0; i < nSize; i++) xhVec[i] = iniVec[i]; jac->SetOffset(0, 0); jac->Zero(); this->_EvaluateF(iniVec, iniFVec, jac); const real_t h = 1e-6, hDefault = 10; len_t index = 0; for (auto uid : this->nontrivial_unknowns) { FVM::UnknownQuantity *uqn = this->unknowns->GetUnknown(uid); const len_t N = uqn->NumberOfElements(); // Differentiate w.r.t. index... for (len_t _i = 0; _i < N; _i++, index++) { // Restore previous element if (index > 0) xhVec[index-1] = iniVec[index-1]; // Determine derivative step length real_t hStep; if (iniVec[index] == 0) hStep = hDefault; else hStep = h*iniVec[index]; xhVec[index] += hStep; // Evaluate F(x+h) this->_EvaluateF(xhVec, FVec, jac); // Evaluate dF/dx_index for (len_t j = 0; j < nSize; j++) dFVec[j] = (FVec[j]-iniFVec[j]) / hStep; // Set Jacobian column for (len_t j = 0; j < nSize; j++) { if (dFVec[j] != 0) jac->SetElement(j, index, dFVec[j], INSERT_VALUES); } printf("\b\b\b\b\b\b\b%6.2f%%", double(index)/double(nSize-1)*100); std::cout << std::flush; } } printf("\n"); jac->Assemble(); delete [] xhVec; delete [] iniFVec; delete [] FVec; delete [] dFVec; } /** * Evaluate the non-linear function 'F'. * * xVec: Point in which to evaluate the function. * FVec: Contains function value on return. * jac: Associated jacobian (for obtaining vector/matrix structure). */ void SolverNonLinear::_EvaluateF(const real_t *xVec, real_t *FVec, FVM::BlockMatrix *jac) { len_t offset = 0; for (auto uqnid : this->nontrivial_unknowns) { unknowns->Store(uqnid, xVec, offset); offset += unknowns->GetUnknown(uqnid)->NumberOfElements(); } this->RebuildTerms(this->CurrentTime(), this->CurrentTimeStep()); this->BuildVector(this->CurrentTime(), this->CurrentTimeStep(), FVec, jac); }
28.118182
91
0.589395
34b7758ac1a85618e9b620de9522e93938a1edfa
2,223
cpp
C++
App/src/UI/Windows/UIMatrixWindow.cpp
Shorakie/GraphDelta
f930ccd7c3bffc7a12fa864d6dca72375623cbcf
[ "MIT" ]
1
2021-07-08T22:51:59.000Z
2021-07-08T22:51:59.000Z
App/src/UI/Windows/UIMatrixWindow.cpp
Shorakie/GraphDelta
f930ccd7c3bffc7a12fa864d6dca72375623cbcf
[ "MIT" ]
null
null
null
App/src/UI/Windows/UIMatrixWindow.cpp
Shorakie/GraphDelta
f930ccd7c3bffc7a12fa864d6dca72375623cbcf
[ "MIT" ]
null
null
null
#include "UIMatrixWindow.h" #include <IconsFontAwesome5.h> #include <spdlog/fmt/fmt.h> #include <Core/Application.h> #include <Core/Utils.h> #include "Components/Components.h" using namespace entt::literals; namespace Project { UIMatrixWindow::UIMatrixWindow(GraphSystem& graphSystem, std::string name) : Engine::UIWindow(name), graphSystem(graphSystem), mode(MatrixMode::ADJ) {} void UIMatrixWindow::init() { show = true; } void UIMatrixWindow::deinit() {} void UIMatrixWindow::render() { if (show) { if (ImGui::Begin(getName(), &show, ImGuiWindowFlags_NoFocusOnAppearing)) renderImGui(); ImGui::End(); } } void UIMatrixWindow::update() {} void UIMatrixWindow::renderImGui() { auto& reg = Engine::Application::get().reg; ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); if (ImGui::Button(ICON_FA_HOME, {28, 28})) mode = MatrixMode::ADJ; ImGui::PopFont(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Adjacency matrix"); ImGui::SameLine(); ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); if (ImGui::Button(ICON_FA_DOLLAR_SIGN, {28, 28})) mode = MatrixMode::COST; ImGui::PopFont(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Cost matrix"); ImGui::Separator(); auto nodes = reg.view<Component::Node>(entt::exclude<entt::tag<"PREVIEW"_hs>>); Engine::Util::NMatrix<double_t> matrix; if (mode == MatrixMode::ADJ) matrix = graphSystem.getAdjacencyMatrix(); else if (mode == MatrixMode::COST) matrix = graphSystem.getCostMatrix(); if (ImGui::BeginTable("Matrix", matrix.size() + 1, ImGuiTableFlags_NoHostExtendY | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX)) { ImGui::TableSetupScrollFreeze(1, 1); ImGui::TableSetupColumn("##Nodes"); for (auto& [nodeId, node] : nodes.each()) ImGui::TableSetupColumn(node.name.c_str()); ImGui::TableHeadersRow(); for (auto& [startId, startNode] : nodes.each()) { ImGui::TableNextColumn(); ImGui::Text(startNode.name.c_str()); for (auto& [endId, endNode] : nodes.each()) { ImGui::TableNextColumn(); ImGui::Text(fmt::to_string(matrix[startId][endId]).c_str()); } } ImGui::EndTable(); } } } // namespace Project
29.64
92
0.682861
34c3762ad4e9b277af235f077a414c405f58eda2
1,061
cpp
C++
src/database/library/artist.cpp
jeanyvesb9/PROJECTu
9534ce3e067425a75a194e56ec53344c5346c151
[ "Apache-2.0" ]
null
null
null
src/database/library/artist.cpp
jeanyvesb9/PROJECTu
9534ce3e067425a75a194e56ec53344c5346c151
[ "Apache-2.0" ]
null
null
null
src/database/library/artist.cpp
jeanyvesb9/PROJECTu
9534ce3e067425a75a194e56ec53344c5346c151
[ "Apache-2.0" ]
null
null
null
#include "artist.h" using namespace DB; Artist::Artist(QObject *parent) :QObject(parent) { } Artist::Artist(quint64 id, QByteArray name, bool albumArtist, QObject *parent) : QObject(parent), id{id}, albumArtist{albumArtist}, name{name} { } Artist::~Artist() { emit artistDeleted(this); } void Artist::setId(quint64 id) { this->id = id; } void Artist::setName(QString name) { this->name = name.toUtf8(); } void Artist::setName(QByteArray name) { this->name = name; } void Artist::setAlbumArtist(bool albumArtist) { this->albumArtist = albumArtist; } void Artist::setAlbumList(QList<quint64> albums) { this->albumList = albums; } void Artist::addAlbum(quint16 possition, quint64 albumNumber) { this->albumList.insert(possition, albumNumber); } void Artist::appendAlbum(quint64 albumNumber) { this->albumList.append(albumNumber); } void Artist::removeAlbum(quint16 possition) { this->albumList.removeAt(possition); } void Artist::moveAlbum(quint16 from, quint16 to) { this->albumList.move(from, to); }
16.323077
78
0.702168
34c3c0adf0797ceeb3c51c7caa3a1ab2eecde196
213
cc
C++
build/ARM/python/m5/internal/param_RubyPort.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_RubyPort.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_RubyPort.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_param_RubyPort(); } EmbeddedSwig embed_swig_param_RubyPort(init_param_RubyPort, "m5.internal._param_RubyPort");
23.666667
99
0.596244
34c3fc0f23e5ac1ba2efe95219cd74ae93d99036
1,816
cpp
C++
evias/network/connection.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
1
2015-10-31T03:18:02.000Z
2015-10-31T03:18:02.000Z
evias/network/connection.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
evias/network/connection.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
#include "connection.hpp" using namespace evias::network; /** * searchQueue * * pop the queue's first element or the first with identification reqId. * * \note returned object has to be free'd * \return netPacket* */ netPacket *evias::network::netConnection::searchQueue(__netRequest_t reqId) { // execute this algorithm safely in creating a specific thread and locking // the mutex Lock l(_mutex); if (_queue.empty()) { return NULL; } netPacket *p = NULL; // either get the first message available // or get a specific packet by its message ID if (reqId == EVIAS_MSG_NONE) { p = _queue.front(); _queue.pop_front(); } else { for (std::list<netPacket*>::iterator i = _queue.begin() ; i != _queue.end() ; i++) { // packet is current iterator's value p = *i; if ( ((__packetHeader_t *) p->m_dataPointer)->requestId == reqId ) { _queue.erase(i); break; } p = NULL; } if (p == NULL) { return NULL; } } return p; } /** * addPacketToQueue * * adds the specified packet to the current queue. If the queue's length * is greater than allowed, pop the first element. * * \return void **/ void evias::network::netConnection::pushQueue(netPacket* packetAdded) { if (! packetAdded) return ; Lock l(_mutex); // add the specified packet _queue.push_back(packetAdded); while (_queue.size() > QUEUE_MAX) { // get the instance for free-ing memory netPacket* frontPacket = _queue.front(); _queue.pop_front(); releaseMemory(frontPacket); } }
21.364706
93
0.556718
34c7dc7488185dc25907f14567154347348f23d1
1,048
cpp
C++
apr.2020after/20200507/20200507/n_11328/n_11328.cpp
lis0517/BOJ_
8aafb2db9c3c08afd145db911144c28a7cec3279
[ "MIT" ]
null
null
null
apr.2020after/20200507/20200507/n_11328/n_11328.cpp
lis0517/BOJ_
8aafb2db9c3c08afd145db911144c28a7cec3279
[ "MIT" ]
null
null
null
apr.2020after/20200507/20200507/n_11328/n_11328.cpp
lis0517/BOJ_
8aafb2db9c3c08afd145db911144c28a7cec3279
[ "MIT" ]
null
null
null
// n_11328.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #include <iostream> #include <string> using namespace std; int arr1[26]; int arr2[26]; int main() { int lp = 0; cin >> lp; for (int i = 0; i < lp; ++i) { fill(arr1 + 0, arr1 + 26, 0); fill(arr2 + 0, arr2 + 26, 0); string s1, s2; cin >> s1 >> s2; for (auto c : s1) { arr1[c - 'a']++; } for (auto c : s2) { arr2[c - 'a']++; } bool flag = true; for (int i = 0; i < 26; ++i) { if (arr1[i] != arr2[i]) { flag = false; break; } } cout << ((flag) ? "Possible" : "Impossible") << "\n"; } } // 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴 // 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴 // 시작을 위한 팁: // 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다. // 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다. // 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다. // 4. [오류 목록] 창을 사용하여 오류를 봅니다. // 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다. // 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
19.407407
96
0.510496
34cddbfed49e6957150bde6c006b2a22752bfed9
1,241
hpp
C++
core/include/storm/core/Singleton.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
core/include/storm/core/Singleton.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
core/include/storm/core/Singleton.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #pragma once #include <functional> #include <memory> #include <mutex> #include <storm/core/Memory.hpp> #include <storm/core/NonCopyable.hpp> #include <storm/core/NonMovable.hpp> #include <utility> namespace storm::core { template<class T> class Singleton: public NonMovable, public NonCopyable { public: template<typename... Args> static T &instance(Args &&...args) { auto lambdas = [](Args &&...args) mutable { m_instance = std::make_unique<T>(std::forward<Args>(args)...); }; std::call_once(onceFlag(), lambdas, std::forward<Args>(args)...); return *m_instance; } protected: explicit Singleton() = default; ~Singleton() = default; private: static std::once_flag &onceFlag() { static auto once_flag = std::once_flag {}; return once_flag; } static inline std::unique_ptr<T> m_instance = nullptr; }; } // namespace storm::core
29.547619
79
0.589847
34d0bb63038a190ded7209dd6ecf81a9cc83c18d
2,177
cpp
C++
DataProcessingList.cpp
AlanRace/imzMLParser
1b9bc7f0b09bdeca9c8427448baed53483ce64e7
[ "Apache-2.0" ]
1
2021-03-18T09:51:10.000Z
2021-03-18T09:51:10.000Z
DataProcessingList.cpp
AlanRace/imzMLParser
1b9bc7f0b09bdeca9c8427448baed53483ce64e7
[ "Apache-2.0" ]
null
null
null
DataProcessingList.cpp
AlanRace/imzMLParser
1b9bc7f0b09bdeca9c8427448baed53483ce64e7
[ "Apache-2.0" ]
1
2018-06-08T09:11:55.000Z
2018-06-08T09:11:55.000Z
/* * * Copyright 2013 Alan Race * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ /* * DataProcessingList.cpp * * Created on: 18 May 2012 * Author: alan */ #include "DataProcessingList.h" namespace ImzML { DataProcessingList::DataProcessingList(int count) { dataProcessingList.reserve(count); } DataProcessingList::~DataProcessingList() { // TODO Auto-generated destructor stub } void DataProcessingList::addDataProcessing(boost::shared_ptr<ImzML::DataProcessing> dataProcessing) { dataProcessingList.push_back(dataProcessing); } boost::shared_ptr<ImzML::DataProcessing> DataProcessingList::getDataProcessing(int index) { return dataProcessingList[index]; } boost::shared_ptr<ImzML::DataProcessing> DataProcessingList::getDataProcessing(std::string id) { for(std::vector< boost::shared_ptr<ImzML::DataProcessing> >::iterator iter = dataProcessingList.begin(); iter < dataProcessingList.end(); iter++) if(id.compare((*iter)->getID()) == 0) return *iter; return boost::shared_ptr<ImzML::DataProcessing>(); } std::ostream& operator<<(std::ostream& os, const ImzML::DataProcessingList& dpl) { for(int i = 0; i < dpl.indent; i++) os << dpl.indentString; os << "<dataProcessingList count=\"" << dpl.dataProcessingList.size() << "\">" << std::endl; dpl.indent++; for(ImzML::DataProcessingList::dataProcessingList_type::size_type i = 0; i < dpl.dataProcessingList.size(); i++) os << *dpl.dataProcessingList[i] << std::endl; dpl.indent--; for(int i = 0; i < dpl.indent; i++) os << dpl.indentString; os << "</dataProcessingList>"; return os; } } /* namespace ImzML */
29.418919
147
0.702802
34daa666825c85dcb0228a49cf58f7b01a528b56
4,104
cpp
C++
third-year/GeometricModelling/Aufgabe01/Aufgabe01/AffineMap.cpp
JulianGR/university
2f643825b238892d602baf0c8e71e4c1b0fdefc2
[ "MIT" ]
null
null
null
third-year/GeometricModelling/Aufgabe01/Aufgabe01/AffineMap.cpp
JulianGR/university
2f643825b238892d602baf0c8e71e4c1b0fdefc2
[ "MIT" ]
null
null
null
third-year/GeometricModelling/Aufgabe01/Aufgabe01/AffineMap.cpp
JulianGR/university
2f643825b238892d602baf0c8e71e4c1b0fdefc2
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////// // // Georg Umlauf, (c) 2020 // //////////////////////////////////////////////////////////////////// #include "AffineMap.h" // constructors AffineMap::AffineMap (double t) { for (int j=0; j<4; j++) for (int i=0; i<4; i++) m_aatData[i][j] = (i==j)? t: 0.0; } AffineMap::AffineMap (const double aatData[4][4]) { for (int j=0; j<4; j++) for (int i=0; i<4; i++) m_aatData[i][j] = aatData[i][j]; } AffineMap::AffineMap (const AffineMap &mat) { for (int j=0; j<4; j++) for (int i=0; i<4; i++) m_aatData[i][j] = mat(i,j); } // destructor AffineMap::~AffineMap () { // nothing to do here ... } // index operations and related methods double &AffineMap::operator () (unsigned i, unsigned j) { return m_aatData[i%4][j%4]; } double AffineMap::operator () (unsigned i, unsigned j) const { return m_aatData[i%4][j%4]; } void AffineMap::swap (unsigned i, unsigned j) { i %= 4; j %= 4; double tmp = m_aatData[i][j]; m_aatData[i][j] = m_aatData[j][i]; m_aatData[j][i] = tmp; } // arithmetic operations AffineMap AffineMap::operator + (const AffineMap &mat) { AffineMap buf(0.0); for (int i=0; i<4; i++) for (int j=0; j<4; j++) buf(i,j) = m_aatData[i][j] + mat.m_aatData[i][j]; return buf; } AffineMap AffineMap::operator - (const AffineMap &mat) { AffineMap buf(0.0); for (int i=0; i<4; i++) for (int j=0; j<4; j++) buf(i,j) = m_aatData[i][j] - mat.m_aatData[i][j]; return buf; } AffineMap AffineMap::operator * (const AffineMap &mat) { AffineMap buf(0.0); for (int i=0; i<4; i++) // row i for (int j=0; j<4; j++) // column j for (int k=0; k<4; k++) // k buf(i,j) += m_aatData[i][k] * mat.m_aatData[k][j]; return buf; } Vector AffineMap::operator * (const Vector &vec) { Vector buf(0,0,0,0); for (int j=0; j<4; j++) // column j for (int i=0; i<4; i++) // row i buf[i] += m_aatData[i][j] * vec[j]; return buf; } Point AffineMap::operator * (const Point &pnt) { Point buf(0,0,0,1); for (int j=0; j<4; j++) // column j for (int i=0; i<4; i++) // row i buf[i] += m_aatData[i][j] * pnt[j]; return buf; } // matrix operations void AffineMap::transpose() { // transpose submatrix (a_ij) for i,j = r,...,l. for( int i=0; i<4; i++) // row i for (int j=i+1; j<4; j++) // column j swap(i,j); } void AffineMap::inverse() // Computes the inverse of a 4x4 matrix M of the form // ⎡ R P ⎤ // M = ⎢ ⎥, // ⎣ 0 1 ⎦ // with an orthonormal 3x3 matrix R, a 3d-column vector P and a 3d-row vector 0=(0,0,0). // // The inverse if computed as // ⎡ Rᵗ -Rᵗ·P ⎤ // M⁻¹ = ⎢ ⎥ . // ⎣ 0 1 ⎦ // // The steps in the computation are // ⎡ R P ⎤ ⎡ R 0 ⎤ ⎡ Rᵗ 0 ⎤ ⎡ Rᵗ -Rᵗ·P ⎤ // M = ⎢ ⎥ ⇒¹ ⎢ ⎥ ⇒² ⎢ ⎥ ⇒³ ⎢ ⎥ = M⁻¹ . // ⎣ 0 1 ⎦ ⎣ 0 1 ⎦ ⎣ 0 1 ⎦ ⎣ 0 1 ⎦ // { AffineMap& M = *this; CoordTuple4d P = M.getCol(3); // copy P from M CoordTuple4d b(0,0,0,1); M.setCol ( b, 3); // step ⇒¹: remove P from M -> the upper left 3x3 block of M is R M.transpose( ); // step ⇒²: transpose M -> the upper left 3x3 block of M is Rᵗ M.setCol (-(M*P), 3); // step ⇒³: insert -Rᵗ·P into M -> M⁻¹ } // row/column operations void AffineMap::setRow(const CoordTuple4d& r, int i) { for (int j=0; j<4; j++) m_aatData[i%4][j] = r[j]; // column j } void AffineMap::setCol(const CoordTuple4d& c, int j) { for (int i=0; i<4; i++) m_aatData[i][j%4] = c[i];// row i } CoordTuple4d AffineMap::getCol(int j) const { Vector vec; for (int i=0; i<4; i++) vec[i] = m_aatData[i][j%4]; // row i return vec; } CoordTuple4d AffineMap::getRow(int i) const { Vector vec; for (int j=0; j<4; j++) vec[j] = m_aatData[i%4][j]; // column j return vec; } // output std::ostream &operator<< (std::ostream &ostr, const AffineMap &u) { ostr << "Affine Map:\n"; for (int i = 0; i < 4; i++) { ostr << "["; for (int j = 0; j < 4; j++) { ostr << u(i, j); if (j != 3) ostr << ", "; } ostr << "]\n"; } return ostr; }
23.318182
93
0.522661
34dd8c2f033593082df54b2853bba8225c0295d4
4,986
cpp
C++
src/lockrace/modtrack.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
2
2015-02-19T13:15:08.000Z
2018-05-30T05:34:15.000Z
src/lockrace/modtrack.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
null
null
null
src/lockrace/modtrack.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
null
null
null
#include "modtrack.h" ModifiedRaceTracker::ModifiedRaceTracker() : HybridRaceTracker() { initializationHelper(); } ModifiedRaceTracker::ModifiedRaceTracker(unsigned int wr, unsigned int rd) : HybridRaceTracker(wr, rd) { initializationHelper(); } ModifiedRaceTracker::~ModifiedRaceTracker() { } void ModifiedRaceTracker::initializationHelper() { printf("Using modified hybrid tracker\n"); outfilename = "thrille-randomactive"; eventcount = 0; lockprofiling = 20; } void ModifiedRaceTracker::beforeSignal(thrID me, pthread_cond_t * cond) {} void ModifiedRaceTracker::afterWait(thrID me, pthread_cond_t * cond) {} void ModifiedRaceTracker::addLockEvent(lockRaceEvent e) { int count = lock_profile_map[e.addr]; if (count > lockprofiling) { return; } count++; lock_profile_map[e.addr] = count; vector<lockRaceEvent> eset = lockeventset[e.addr]; eset.push_back(e); lockeventset[e.addr] = eset; } void ModifiedRaceTracker::outputRaces() { printf("Races:\n"); map<void *, vector<dataRaceEvent> >::iterator mitr; vector<dataRaceEvent>::iterator vitr; for (mitr = eventset.begin(); mitr != eventset.end(); mitr++) { vector<dataRaceEvent> tmpv = mitr->second; for (vitr = tmpv.begin(); vitr != tmpv.end(); vitr++) { eventcount++; if (eventcount % 1000 == 0) { printf("Events Processed: %d\n", eventcount); } checkRace((*vitr)); } } map<void *, vector<lockRaceEvent> >::iterator mliter; vector<lockRaceEvent>::iterator vliter; for (mliter = lockeventset.begin(); mliter != lockeventset.end(); mliter++) { vector<lockRaceEvent> tmplv = mliter->second; for (vliter = tmplv.begin(); vliter != tmplv.end(); vliter++) { eventcount++; if (eventcount % 1000 == 0) { printf("Events Processed: %d\n", eventcount); } checkLockRace((*vliter)); } } ofstream * fout = new ofstream; fout->open(outfilename.c_str()); dumpRaces(fout); fout->close(); delete fout; } void ModifiedRaceTracker::checkLockRace(lockRaceEvent e) { vector<lockRaceEvent> addrevents = lockeventset[e.addr]; vector<lockRaceEvent>::iterator itr; for (itr = addrevents.begin(); itr != addrevents.end(); itr++) { if (isRacing((*itr), e)) { lockRaceRecord tmprec((*itr).lock, e.lock); vector<lockRaceRecord>::iterator litr; bool addrace = true; for (litr = foundlockraces.begin(); litr != foundlockraces.end(); litr++) { if ((*litr) == tmprec) { addrace = false; } } if (addrace) { foundlockraces.push_back(tmprec); } } } } void ModifiedRaceTracker::dumpRaces(ofstream * fout) { vector<dataRaceRecord>::iterator itr; if (((int) foundraces.size()) == 0 && ((int) foundlockraces.size()) == 0) { printf("No races discovered\n"); } for (itr = foundraces.begin(); itr != foundraces.end(); itr++) { printf("Race: DataRaceRecord(%p, %p)\n", ((dataRaceRecord)(*itr)).getLeft(), ((dataRaceRecord)(*itr)).getRight()); (*fout) << "DATA" << endl << ((dataRaceRecord)(*itr)).getLeft() << endl << ((dataRaceRecord) (*itr)).getRight() << endl << flush; } vector<lockRaceRecord>::iterator litr; for (litr = foundlockraces.begin(); litr != foundlockraces.end(); litr++) { printf("Race: LockRaceRecord(%p, %p)\n", ((lockRaceRecord)(*litr)).getLeft(), ((lockRaceRecord)(*litr)).getRight()); (*fout) << "LOCK" << endl << ((lockRaceRecord)(*litr)).getLeft() << endl << ((lockRaceRecord) (*litr)).getRight() << endl << flush; } int racecount = 0; map<void *, vector<dataRaceEvent> > potraces = eventset; map<void *, vector<dataRaceEvent> >::iterator mitr; vector<dataRaceEvent>::iterator sitr; vector<dataRaceEvent> tmp; for (mitr = potraces.begin(); mitr != potraces.end(); mitr++) { tmp = mitr->second; for (sitr = tmp.begin(); sitr != tmp.end(); sitr++) { racecount++; } } printf("\nData Race Events: %d\n", racecount); int lockracecount = 0; map<void *, vector<lockRaceEvent> > potlockraces = lockeventset; map<void *, vector<lockRaceEvent> >::iterator mlitr; vector<lockRaceEvent>::iterator slitr; vector<lockRaceEvent> ltmp; for (mlitr = potlockraces.begin(); mlitr != potlockraces.end(); mlitr++) { ltmp = mlitr->second; for (slitr = ltmp.begin(); slitr != ltmp.end(); slitr++) { lockracecount++; } } printf("\nLock Race Events: %d\n", lockracecount); }
31.961538
79
0.573606
34e068bf48a74368721b09af4684c7e0457d20c8
769
cpp
C++
plugins/Nephilim/AngelScriptEXT/ASXRuntime.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
19
2015-12-19T11:15:57.000Z
2022-03-09T11:22:11.000Z
plugins/Nephilim/AngelScriptEXT/ASXRuntime.cpp
DevilWithin/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
1
2017-05-17T09:31:10.000Z
2017-05-19T17:01:31.000Z
plugins/Nephilim/AngelScriptEXT/ASXRuntime.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
3
2015-12-14T17:40:26.000Z
2021-02-25T00:42:42.000Z
#include <Nephilim/AngelScriptEXT/ASXRuntime.h> #include <Nephilim/AngelScriptEXT/ASXEngine.h> #include <angelscript.h> NEPHILIM_NS_BEGIN ASXRuntime::ASXRuntime() : m_context(NULL) { } ASXRuntime::ASXRuntime(ASXEngine& engine) { m_context = engine.get()->CreateContext(); } ASXRuntime::~ASXRuntime() { if(m_context) m_context->Release(); } asIScriptContext* ASXRuntime::get() { return m_context; } void ASXRuntime::pushState() { if(m_context) m_context->PushState(); } void ASXRuntime::popState() { if(m_context) m_context->PopState(); } void ASXRuntime::set(ASXEngine& engine) { m_context = engine.get()->CreateContext(); } void ASXRuntime::reset(ASXModule& module) { if(m_context) { module.get()->ResetGlobalVars(m_context); } } NEPHILIM_NS_END
14.788462
47
0.73212
34e4275045040f9b3400d0cdefb85c2055a8dee0
21,640
cpp
C++
Tests/FileMgrTest.cpp
igalink/omniscidb
94e878916991e7cf76bcd85b4091119b1ec66012
[ "Apache-2.0" ]
null
null
null
Tests/FileMgrTest.cpp
igalink/omniscidb
94e878916991e7cf76bcd85b4091119b1ec66012
[ "Apache-2.0" ]
1
2021-02-24T03:22:29.000Z
2021-02-24T03:22:29.000Z
Tests/FileMgrTest.cpp
isabella232/omniscidb
bf83d84833710679debdf7a0484b6fbfc421cc96
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file FileMgrTest.cpp * @brief Unit tests for FileMgr class. */ #include <gtest/gtest.h> #include "DBHandlerTestHelpers.h" #include "DataMgr/FileMgr/FileMgr.h" #include "DataMgr/FileMgr/GlobalFileMgr.h" #include "TestHelpers.h" class FileMgrTest : public DBHandlerTestFixture { protected: std::string table_name; Data_Namespace::DataMgr* dm; ChunkKey chunk_key; std::pair<int, int> file_mgr_key; File_Namespace::GlobalFileMgr* gfm; Catalog_Namespace::Catalog* cat; void SetUp() override { DBHandlerTestFixture::SetUp(); cat = &getCatalog(); dm = &cat->getDataMgr(); gfm = dm->getGlobalFileMgr(); table_name = "test_table"; sql("DROP TABLE IF EXISTS " + table_name + ";"); sql("CREATE TABLE " + table_name + " (col1 INT)"); sql("INSERT INTO " + table_name + " VALUES(1)"); const TableDescriptor* td = cat->getMetadataForTable(table_name); const auto col_descs = cat->getAllColumnMetadataForTable(td->tableId, false, false, false); const ColumnDescriptor* cd = *(col_descs.begin()); int db_id = cat->getCurrentDB().dbId; int tb_id = td->tableId; chunk_key = {db_id, tb_id, cd->columnId, 0}; file_mgr_key = std::make_pair(db_id, tb_id); } void TearDown() override { sql("DROP TABLE " + table_name); DBHandlerTestFixture::TearDown(); } ChunkKey setUpCappedRollbackTable(const int32_t max_rollback_epochs) { Catalog_Namespace::Catalog* cat = &getCatalog(); const std::string capped_table_name("capped_table"); sql("DROP TABLE IF EXISTS " + capped_table_name + ";"); std::stringstream capped_ddl; capped_ddl << "CREATE TABLE " << capped_table_name << " " << "(col1 INT) WITH (max_rollback_epochs=" << max_rollback_epochs << ")"; sql(capped_ddl.str()); sql("INSERT INTO " + capped_table_name + " VALUES(1)"); const TableDescriptor* td = cat->getMetadataForTable(capped_table_name); const auto col_descs = cat->getAllColumnMetadataForTable(td->tableId, false, false, false); const ColumnDescriptor* cd = *(col_descs.begin()); const int db_id = cat->getCurrentDB().dbId; const int tb_id = td->tableId; const ChunkKey capped_chunk_key = {db_id, tb_id, cd->columnId, 0}; return capped_chunk_key; } void compareBuffers(AbstractBuffer* left_buffer, AbstractBuffer* right_buffer, size_t num_bytes) { int8_t left_array[num_bytes]; int8_t right_array[num_bytes]; left_buffer->read(left_array, num_bytes); right_buffer->read(right_array, num_bytes); ASSERT_EQ(std::memcmp(left_array, right_array, num_bytes), 0); ASSERT_EQ(left_buffer->hasEncoder(), right_buffer->hasEncoder()); } void compareMetadata(const std::shared_ptr<ChunkMetadata> lhs_metadata, const std::shared_ptr<ChunkMetadata> rhs_metadata) { SQLTypeInfo lhs_sqltypeinfo = lhs_metadata->sqlType; SQLTypeInfo rhs_sqltypeinfo = rhs_metadata->sqlType; ASSERT_EQ(lhs_sqltypeinfo.get_type(), rhs_sqltypeinfo.get_type()); ASSERT_EQ(lhs_sqltypeinfo.get_subtype(), rhs_sqltypeinfo.get_subtype()); ASSERT_EQ(lhs_sqltypeinfo.get_dimension(), rhs_sqltypeinfo.get_dimension()); ASSERT_EQ(lhs_sqltypeinfo.get_scale(), rhs_sqltypeinfo.get_scale()); ASSERT_EQ(lhs_sqltypeinfo.get_notnull(), rhs_sqltypeinfo.get_notnull()); ASSERT_EQ(lhs_sqltypeinfo.get_comp_param(), rhs_sqltypeinfo.get_comp_param()); ASSERT_EQ(lhs_sqltypeinfo.get_size(), rhs_sqltypeinfo.get_size()); ASSERT_EQ(lhs_metadata->numBytes, rhs_metadata->numBytes); ASSERT_EQ(lhs_metadata->numElements, rhs_metadata->numElements); ChunkStats lhs_chunk_stats = lhs_metadata->chunkStats; ChunkStats rhs_chunk_stats = rhs_metadata->chunkStats; ASSERT_EQ(lhs_chunk_stats.min.intval, rhs_chunk_stats.min.intval); ASSERT_EQ(lhs_chunk_stats.max.intval, rhs_chunk_stats.max.intval); ASSERT_EQ(lhs_chunk_stats.has_nulls, rhs_chunk_stats.has_nulls); } std::shared_ptr<ChunkMetadata> getMetadataForBuffer(AbstractBuffer* buffer) { const std::shared_ptr<ChunkMetadata> metadata = std::make_shared<ChunkMetadata>(); buffer->getEncoder()->getMetadata(metadata); return metadata; } void compareBuffersAndMetadata(AbstractBuffer* left_buffer, AbstractBuffer* right_buffer) { ASSERT_TRUE(left_buffer->hasEncoder()); ASSERT_TRUE(right_buffer->hasEncoder()); ASSERT_TRUE(left_buffer->getEncoder()); ASSERT_TRUE(right_buffer->getEncoder()); ASSERT_EQ(left_buffer->size(), getMetadataForBuffer(left_buffer)->numBytes); ASSERT_EQ(right_buffer->size(), getMetadataForBuffer(right_buffer)->numBytes); compareMetadata(getMetadataForBuffer(left_buffer), getMetadataForBuffer(right_buffer)); compareBuffers(left_buffer, right_buffer, left_buffer->size()); } int8_t* getDataPtr(std::vector<int32_t>& data_vector) { return reinterpret_cast<int8_t*>(data_vector.data()); } void appendData(AbstractBuffer* data_buffer, std::vector<int32_t>& append_data) { CHECK(data_buffer->hasEncoder()); SQLTypeInfo sql_type_info = getMetadataForBuffer(data_buffer)->sqlType; int8_t* append_ptr = getDataPtr(append_data); data_buffer->getEncoder()->appendData(append_ptr, append_data.size(), sql_type_info); } void writeData(AbstractBuffer* data_buffer, std::vector<int32_t>& write_data, const size_t offset) { CHECK(data_buffer->hasEncoder()); SQLTypeInfo sql_type_info = getMetadataForBuffer(data_buffer)->sqlType; int8_t* write_ptr = getDataPtr(write_data); // appendData is a misnomer, with the offset we are overwriting part of the buffer data_buffer->getEncoder()->appendData( write_ptr, write_data.size(), sql_type_info, false /*replicating*/, offset); } }; TEST_F(FileMgrTest, putBuffer_update) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); source_buffer->setUpdated(); auto file_mgr = File_Namespace::FileMgr(0, gfm, file_mgr_key, -1, 0, -1, gfm->getDefaultPageSize()); AbstractBuffer* file_buffer = file_mgr.putBuffer(chunk_key, source_buffer, 4); compareBuffersAndMetadata(source_buffer, file_buffer); ASSERT_FALSE(source_buffer->isAppended()); ASSERT_FALSE(source_buffer->isUpdated()); ASSERT_FALSE(source_buffer->isDirty()); } TEST_F(FileMgrTest, putBuffer_subwrite) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); int8_t temp_array[8] = {1, 2, 3, 4, 5, 6, 7, 8}; source_buffer->write(temp_array, 8); auto file_mgr = File_Namespace::FileMgr(0, gfm, file_mgr_key, -1, 0, -1, gfm->getDefaultPageSize()); AbstractBuffer* file_buffer = file_mgr.putBuffer(chunk_key, source_buffer, 4); compareBuffers(source_buffer, file_buffer, 4); } TEST_F(FileMgrTest, putBuffer_exists) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); int8_t temp_array[4] = {1, 2, 3, 4}; source_buffer->write(temp_array, 4); auto file_mgr = File_Namespace::FileMgr(0, gfm, file_mgr_key, -1, 0, -1, gfm->getDefaultPageSize()); file_mgr.putBuffer(chunk_key, source_buffer, 4); file_mgr.checkpoint(); source_buffer->write(temp_array, 4); AbstractBuffer* file_buffer = file_mgr.putBuffer(chunk_key, source_buffer, 4); compareBuffersAndMetadata(source_buffer, file_buffer); } TEST_F(FileMgrTest, putBuffer_append) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); int8_t temp_array[4] = {1, 2, 3, 4}; source_buffer->append(temp_array, 4); auto file_mgr = File_Namespace::FileMgr(0, gfm, file_mgr_key, -1, 0, -1, gfm->getDefaultPageSize()); AbstractBuffer* file_buffer = file_mgr.putBuffer(chunk_key, source_buffer, 8); compareBuffersAndMetadata(source_buffer, file_buffer); } TEST_F(FileMgrTest, put_checkpoint_get) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); std::vector<int32_t> data_v1 = {1, 2, 3, 5, 7}; appendData(source_buffer, data_v1); File_Namespace::FileMgr* file_mgr = dynamic_cast<File_Namespace::FileMgr*>( dm->getGlobalFileMgr()->getFileMgr(file_mgr_key.first, file_mgr_key.second)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 1); AbstractBuffer* file_buffer_put = file_mgr->putBuffer(chunk_key, source_buffer, 24); ASSERT_TRUE(file_buffer_put->isDirty()); ASSERT_FALSE(file_buffer_put->isUpdated()); ASSERT_TRUE(file_buffer_put->isAppended()); ASSERT_EQ(file_buffer_put->size(), static_cast<size_t>(24)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 1); file_mgr->checkpoint(); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); AbstractBuffer* file_buffer_get = file_mgr->getBuffer(chunk_key, 24); ASSERT_EQ(file_buffer_put, file_buffer_get); CHECK(!(file_buffer_get->isDirty())); CHECK(!(file_buffer_get->isUpdated())); CHECK(!(file_buffer_get->isAppended())); ASSERT_EQ(file_buffer_get->size(), static_cast<size_t>(24)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); compareBuffersAndMetadata(source_buffer, file_buffer_get); } TEST_F(FileMgrTest, put_checkpoint_get_double_write) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); std::vector<int32_t> data_v1 = {1, 2, 3, 5, 7}; std::vector<int32_t> data_v2 = {11, 13, 17, 19}; appendData(source_buffer, data_v1); File_Namespace::FileMgr* file_mgr = dynamic_cast<File_Namespace::FileMgr*>( dm->getGlobalFileMgr()->getFileMgr(file_mgr_key.first, file_mgr_key.second)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 1); file_mgr->putBuffer(chunk_key, source_buffer, 24); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 1); file_mgr->checkpoint(); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); AbstractBuffer* file_buffer = file_mgr->getBuffer(chunk_key, 24); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); ASSERT_FALSE(file_buffer->isDirty()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(24)); compareBuffersAndMetadata(source_buffer, file_buffer); appendData(file_buffer, data_v2); ASSERT_TRUE(file_buffer->isDirty()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(40)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); appendData(file_buffer, data_v2); CHECK(file_buffer->isDirty()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(56)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); file_mgr->checkpoint(); CHECK(!(file_buffer->isDirty())); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(56)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 3); appendData(source_buffer, data_v2); appendData(source_buffer, data_v2); compareBuffersAndMetadata(source_buffer, file_buffer); } TEST_F(FileMgrTest, buffer_append_and_recovery) { AbstractBuffer* source_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); ASSERT_EQ(getMetadataForBuffer(source_buffer)->numElements, static_cast<size_t>(1)); std::vector<int32_t> data_v1 = {1, 2, 3, 5, 7}; std::vector<int32_t> data_v2 = {11, 13, 17, 19}; appendData(source_buffer, data_v1); { File_Namespace::FileMgr* file_mgr = dynamic_cast<File_Namespace::FileMgr*>( dm->getGlobalFileMgr()->getFileMgr(file_mgr_key.first, file_mgr_key.second)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 1); AbstractBuffer* file_buffer = file_mgr->putBuffer(chunk_key, source_buffer, 24); file_mgr->checkpoint(); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); ASSERT_EQ(getMetadataForBuffer(source_buffer)->numElements, static_cast<size_t>(6)); ASSERT_EQ(getMetadataForBuffer(file_buffer)->numElements, static_cast<size_t>(6)); SCOPED_TRACE("Buffer Append and Recovery - Compare #1"); compareBuffersAndMetadata(source_buffer, file_buffer); // Now write data we will not checkpoint appendData(file_buffer, data_v1); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(44)); // Now close filemgr to test recovery cat->removeFragmenterForTable(file_mgr_key.second); dm->getGlobalFileMgr()->closeFileMgr(file_mgr_key.first, file_mgr_key.second); } { File_Namespace::FileMgr* file_mgr = dynamic_cast<File_Namespace::FileMgr*>( dm->getGlobalFileMgr()->getFileMgr(file_mgr_key.first, file_mgr_key.second)); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 2); ChunkMetadataVector chunkMetadataVector; file_mgr->getChunkMetadataVecForKeyPrefix(chunkMetadataVector, chunk_key); ASSERT_EQ(chunkMetadataVector.size(), static_cast<size_t>(1)); ASSERT_EQ(std::memcmp(chunkMetadataVector[0].first.data(), chunk_key.data(), 16), 0); ASSERT_EQ(chunkMetadataVector[0].first, chunk_key); std::shared_ptr<ChunkMetadata> chunk_metadata = chunkMetadataVector[0].second; ASSERT_EQ(chunk_metadata->numBytes, static_cast<size_t>(24)); ASSERT_EQ(chunk_metadata->numElements, static_cast<size_t>(6)); AbstractBuffer* file_buffer = file_mgr->getBuffer(chunk_key, chunk_metadata->numBytes); { SCOPED_TRACE("Buffer Append and Recovery - Compare #2"); compareBuffersAndMetadata(source_buffer, file_buffer); } appendData(source_buffer, data_v2); appendData(file_buffer, data_v2); file_mgr->checkpoint(); ASSERT_EQ(file_mgr->lastCheckpointedEpoch(), 3); { SCOPED_TRACE("Buffer Append and Recovery - Compare #3"); compareBuffersAndMetadata(source_buffer, file_buffer); } } } TEST_F(FileMgrTest, buffer_update_and_recovery) { std::vector<int32_t> data_v1 = { 2, 3, 5, 7, 11}; // Make first element different than 1 stored in col1 at t0 so that we can // ensure updates and rollbacks show a change in col[0] std::vector<int32_t> data_v2 = {13, 17, 19, 23}; { EXPECT_EQ(dm->getTableEpoch(file_mgr_key.first, file_mgr_key.second), std::size_t(1)); AbstractBuffer* cpu_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL); AbstractBuffer* file_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::DISK_LEVEL); ASSERT_FALSE(cpu_buffer->isDirty()); ASSERT_FALSE(cpu_buffer->isUpdated()); ASSERT_FALSE(cpu_buffer->isAppended()); ASSERT_FALSE(file_buffer->isDirty()); ASSERT_FALSE(file_buffer->isUpdated()); ASSERT_FALSE(file_buffer->isAppended()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(4)); { SCOPED_TRACE("Buffer Update and Recovery - Compare #1"); compareBuffersAndMetadata(file_buffer, cpu_buffer); } writeData(file_buffer, data_v1, 0); ASSERT_TRUE(file_buffer->isDirty()); ASSERT_TRUE(file_buffer->isUpdated()); ASSERT_TRUE(file_buffer->isAppended()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(20)); { std::vector<int32_t> file_buffer_data(file_buffer->size() / sizeof(int32_t)); file_buffer->read(reinterpret_cast<int8_t*>(file_buffer_data.data()), file_buffer->size()); ASSERT_EQ(file_buffer_data[0], 2); ASSERT_EQ(file_buffer_data[1], 3); ASSERT_EQ(file_buffer_data[2], 5); ASSERT_EQ(file_buffer_data[3], 7); ASSERT_EQ(file_buffer_data[4], 11); std::shared_ptr<ChunkMetadata> file_chunk_metadata = getMetadataForBuffer(file_buffer); ASSERT_EQ(file_chunk_metadata->numElements, static_cast<size_t>(5)); ASSERT_EQ(file_chunk_metadata->numBytes, static_cast<size_t>(20)); ASSERT_EQ(file_chunk_metadata->chunkStats.min.intval, 1); // We don't currently narrow the metadata on a full rewrite ASSERT_EQ(file_chunk_metadata->chunkStats.max.intval, 11); ASSERT_EQ(file_chunk_metadata->chunkStats.has_nulls, false); } dm->checkpoint(file_mgr_key.first, file_mgr_key.second); EXPECT_EQ(dm->getTableEpoch(file_mgr_key.first, file_mgr_key.second), std::size_t(2)); ASSERT_FALSE(file_buffer->isDirty()); ASSERT_FALSE(file_buffer->isUpdated()); ASSERT_FALSE(file_buffer->isAppended()); cpu_buffer->unPin(); // Neccessary as we just have a raw_ptr, so there is no way to // auto un-pin the pin that getBuffer sets, normally this is // handled by the Chunk class wrapper dm->clearMemory(Data_Namespace::MemoryLevel::CPU_LEVEL); cpu_buffer = dm->getChunkBuffer( chunk_key, Data_Namespace::MemoryLevel::CPU_LEVEL, 0, 20); // Dragons here: if we didn't unpin andy flush the data, the first value // will be 1, and not 2, as we only fetch the portion of data we don't have // from FileMgr (there's no DataMgr versioning currently, so for example, // for updates we just flush the in-memory buffers to get a clean start) ASSERT_FALSE(cpu_buffer->isDirty()); ASSERT_FALSE(cpu_buffer->isUpdated()); ASSERT_FALSE(cpu_buffer->isAppended()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(20)); { std::vector<int32_t> cpu_buffer_data(cpu_buffer->size() / sizeof(int32_t)); cpu_buffer->read(reinterpret_cast<int8_t*>(cpu_buffer_data.data()), cpu_buffer->size()); ASSERT_EQ(cpu_buffer_data[0], 2); ASSERT_EQ(cpu_buffer_data[1], 3); ASSERT_EQ(cpu_buffer_data[2], 5); ASSERT_EQ(cpu_buffer_data[3], 7); ASSERT_EQ(cpu_buffer_data[4], 11); std::shared_ptr<ChunkMetadata> cpu_chunk_metadata = getMetadataForBuffer(cpu_buffer); ASSERT_EQ(cpu_chunk_metadata->numElements, static_cast<size_t>(5)); ASSERT_EQ(cpu_chunk_metadata->numBytes, static_cast<size_t>(20)); ASSERT_EQ(cpu_chunk_metadata->chunkStats.min.intval, 1); // We don't currently narrow the metadata on a full rewrite ASSERT_EQ(cpu_chunk_metadata->chunkStats.max.intval, 11); ASSERT_EQ(cpu_chunk_metadata->chunkStats.has_nulls, false); } { SCOPED_TRACE("Buffer Update and Recovery - Compare #2"); compareBuffersAndMetadata(file_buffer, cpu_buffer); } // Now roll back to epoch 1 cat->setTableEpoch(file_mgr_key.first, file_mgr_key.second, 1); file_buffer = dm->getChunkBuffer(chunk_key, Data_Namespace::MemoryLevel::DISK_LEVEL); ASSERT_FALSE(file_buffer->isDirty()); ASSERT_FALSE(file_buffer->isUpdated()); ASSERT_FALSE(file_buffer->isAppended()); ASSERT_EQ(file_buffer->size(), static_cast<size_t>(4)); { std::vector<int32_t> file_buffer_data(file_buffer->size() / sizeof(int32_t)); file_buffer->read(reinterpret_cast<int8_t*>(file_buffer_data.data()), file_buffer->size()); ASSERT_EQ(file_buffer_data[0], 1); std::shared_ptr<ChunkMetadata> file_chunk_metadata = getMetadataForBuffer(file_buffer); ASSERT_EQ(file_chunk_metadata->numElements, static_cast<size_t>(1)); ASSERT_EQ(file_chunk_metadata->numBytes, static_cast<size_t>(4)); ASSERT_EQ(file_chunk_metadata->chunkStats.min.intval, 1); ASSERT_EQ(file_chunk_metadata->chunkStats.max.intval, 1); ASSERT_EQ(file_chunk_metadata->chunkStats.has_nulls, false); } } } TEST_F(FileMgrTest, capped_metadata) { const int rollback_ceiling = 10; const int num_data_writes = rollback_ceiling * 2; for (int max_rollback_epochs = 0; max_rollback_epochs != rollback_ceiling; ++max_rollback_epochs) { const ChunkKey capped_chunk_key = setUpCappedRollbackTable(max_rollback_epochs); // Have one element already written to key -- epoch should be 2 ASSERT_EQ(dm->getTableEpoch(capped_chunk_key[0], capped_chunk_key[1]), static_cast<size_t>(1)); File_Namespace::FileMgr* file_mgr = dynamic_cast<File_Namespace::FileMgr*>( dm->getGlobalFileMgr()->getFileMgr(capped_chunk_key[0], capped_chunk_key[1])); // buffer inside loop for (int data_write = 1; data_write <= num_data_writes; ++data_write) { std::vector<int32_t> data; data.emplace_back(data_write); AbstractBuffer* file_buffer = dm->getChunkBuffer(capped_chunk_key, Data_Namespace::MemoryLevel::DISK_LEVEL); appendData(file_buffer, data); dm->checkpoint(capped_chunk_key[0], capped_chunk_key[1]); ASSERT_EQ(dm->getTableEpoch(capped_chunk_key[0], capped_chunk_key[1]), static_cast<size_t>(data_write + 1)); const size_t num_metadata_pages_expected = std::min(data_write + 1, max_rollback_epochs + 1); ASSERT_EQ(file_mgr->getNumUsedMetadataPagesForChunkKey(capped_chunk_key), num_metadata_pages_expected); } } } int main(int argc, char** argv) { TestHelpers::init_logger_stderr_only(argc, argv); testing::InitGoogleTest(&argc, argv); int err{0}; try { err = RUN_ALL_TESTS(); } catch (const std::exception& e) { LOG(ERROR) << e.what(); } return err; }
44.989605
90
0.717976
34e5824156bb4489ce6a05a52d37e029521986e1
17,532
cpp
C++
examples/example-rtc.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
1
2018-11-08T13:41:18.000Z
2018-11-08T13:41:18.000Z
examples/example-rtc.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
null
null
null
examples/example-rtc.cpp
kirchnerlab/libpipe
28f08b9399945bd13329937a9dd0691211826886
[ "MIT" ]
null
null
null
/* * example-rtc.cpp * * Copyright (c) 2010 Marc Kirchner * 2011 David Sichau * */ #include <libpipe/config.hpp> #include <stdlib.h> #include <exception> #include <iostream> #include <set> #include <boost/pointer_cast.hpp> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <libpipe/rtc/Algorithm.hpp> #include <libpipe/rtc/Filter.hpp> #include <libpipe/rtc/Manager.hpp> #include <libpipe/rtc/ManagerFactory.hpp> #include <libpipe/rtc/AlgorithmFactory.hpp> #include <libpipe/utilities/Exception.hpp> #include <libpipe/Request.hpp> #include <libpipe/rtc/SharedData.hpp> #include <libpipe/rtc/PipelineLoader.hpp> /** Converts std::string input to uppercase. * Although not exceedingly useful, this is a good example of how to write * an LIBPIPE algorithm. Basically, there are only two requirements (and one * additional option): * \li derive from \c libpipe::Algorithm. * \li implement the \c update() function. * \li optionally, override the \c processRequest() function (if your * implementation does not call the \c update function, you do not * need to implement it). * * Contrary to other approaches to pipelining (most notably probably the VTK * way), LIBPIPE attempts to minimize hard constraints on the implementations. * There is a diverse collection of datatypes and a set of software suites * that are being used to process mass spectrometry data. Minimizing the * structural imprint that LIBPIPE leaves on applications allows easy cross-suite * interfacing and allows for a more rapid algorithmic development cycle. */ class UppercaseAlgorithm : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::string String; typedef libpipe::rtc::SharedData<String> SharedString; static Algorithm* create() { return new UppercaseAlgorithm; } /** Destructor. */ virtual ~UppercaseAlgorithm() { } /** Runs the algorithm and updates the output data. * This is where all the algorithm implementation goes. * @param[in,out] req The request object, forwarded from \c process request. * @return The request */ void update(libpipe::Request& req) { LIBPIPE_PREPARE_READ_ACCESS(input_, dataIn_, String, "StringInput"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, dataOut_, String, "StringOutput"); LIBPIPE_PIPELINE_TRACE("UppercaseAlgorithm::update: start."); dataOut_.clear(); LIBPIPE_PIPELINE_TRACE( "UppercaseAlgorithm::update: transforming to uppercase."); std::transform(dataIn_.begin(), dataIn_.end(), std::back_inserter(dataOut_), toupper); LIBPIPE_PIPELINE_TRACE("UppercaseAlgorithm::update: end."); #ifdef ENABLE_THREADING output_->unlock(); input_->unlock(); #endif } protected: /** Constructor. * Make sure to call the \c libpipe::rtc::Algorithm constructor. */ UppercaseAlgorithm() : libpipe::rtc::Algorithm() { ports_["StringInput"] = boost::make_shared< SharedString>(); ports_["StringOutput"] = boost::make_shared< SharedString >(new std::string); } private: /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "UppercaseAlgorithm"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, UppercaseAlgorithm::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool UppercaseAlgorithm::registered_ = registerLoader(); /** Converts std::string input to lowercase. * Although not exceedingly useful, this is a good example of how to write * an LIBPIPE algorithm. Basically, there are only two requirements (and one * additional option): * \li derive from \c libpipe::Algorithm. * \li implement the \c update() function. * \li optionally, override the \c processRequest() function (if your * implementation does not call the \c update function, you do not * need to implement it). * * Contrary to other approaches to pipelining (most notably probably the VTK * way), LIBPIPE attempts to minimize hard constraints on the implementations. * There is a diverse collection of datatypes and a set of software suites * that are being used to process mass spectrometry data. Minimizing the * structural imprint that LIBPIPE leaves on applications allows easy cross-suite * interfacing and allows for a more rapid algorithmic development cycle. */ class LowercaseAlgorithm : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::string String; typedef libpipe::rtc::SharedData<String> SharedString; static Algorithm* create() { return new LowercaseAlgorithm; } /** Destructor. */ virtual ~LowercaseAlgorithm() { } /** Runs the algorithm and updates the output data. * This is where all the algorithm implementation goes. * @param[in,out] req The request object, forwarded from \c process request. * @return The request */ void update(libpipe::Request& req) { LIBPIPE_PREPARE_READ_ACCESS(input_, dataIn_, String, "StringInput"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, dataOut_, String, "StringOutput"); LIBPIPE_PIPELINE_TRACE("LowercaseAlgorithm::update: start."); dataOut_.clear(); LIBPIPE_PIPELINE_TRACE( "LowercaseAlgorithm::update: transforming to uppercase."); std::transform(dataIn_.begin(), dataIn_.end(), std::back_inserter(dataOut_), tolower); LIBPIPE_PIPELINE_TRACE("LowercaseAlgorithm::update: end."); #ifdef ENABLE_THREADING output_->unlock(); input_->unlock(); #endif } protected: private: /** Constructor. * Make sure to call the \c libpipe::Algorithm constructor. */ LowercaseAlgorithm() : libpipe::rtc::Algorithm() { ports_["StringInput"] = boost::make_shared< SharedString >(); ports_["StringOutput"] = boost::make_shared< SharedString >(new std::string); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "LowercaseAlgorithm"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, LowercaseAlgorithm::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool LowercaseAlgorithm::registered_ = registerLoader(); /** Combines the input strings to one string. * */ class CombineAlgorithm : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::string String; typedef libpipe::rtc::SharedData<String> SharedString; static Algorithm* create() { return new CombineAlgorithm; } /** Destructor. */ virtual ~CombineAlgorithm() { LIBPIPE_PREPARE_READ_ACCESS(input1_, dataIn1_, String, "StringInput1"); LIBPIPE_PREPARE_READ_ACCESS(input2_, dataIn2_, String, "StringInput2"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, dataOut_, String, "StringOutput"); std::cout << "\033[22;32m Combine Algorithm destroyed with input: " << dataIn1_ << " and " << dataIn2_ << "\t and output: " << dataOut_ << "\e[m" << std::endl; #ifdef ENABLE_THREADING output_->unlock(); input1_->unlock(); input2_->unlock(); #endif } /** Runs the algorithm and updates the output data. * This is where all the algorithm implementation goes. * @param[in,out] req The request object, forwarded from \c process request. * @return The request */ void update(libpipe::Request& req) { LIBPIPE_PREPARE_READ_ACCESS(input1_, dataIn1_, String, "StringInput1"); LIBPIPE_PREPARE_READ_ACCESS(input2_, dataIn2_, String, "StringInput2"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, dataOut_, String, "StringOutput"); LIBPIPE_PIPELINE_TRACE("CombineAlgorithm::update: start."); dataOut_.clear(); LIBPIPE_PIPELINE_TRACE( "CombineAlgorithm::update: combining inputs"); combine(dataOut_, dataIn1_, dataIn2_); LIBPIPE_PIPELINE_TRACE("CombineAlgorithm::update: end."); #ifdef ENABLE_THREADING output_->unlock(); input1_->unlock(); input2_->unlock(); #endif } protected: private: /** Combines two inputs * @param result The result */ void combine(String& result, const String& input1_, const String& input2_) { result.append(input1_); result.append(input2_); } /** Constructor. * Make sure to call the \c libpipe::Algorithm constructor. */ CombineAlgorithm() : libpipe::rtc::Algorithm() { ports_["StringInput1"] = boost::make_shared< SharedString >(); ports_["StringInput2"] = boost::make_shared< SharedString >(); ports_["StringOutput"] = boost::make_shared< SharedString >(new std::string); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "CombineAlgorithm"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, CombineAlgorithm::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool CombineAlgorithm::registered_ = registerLoader(); /** cipher the string with ROT13 * */ class ROT13Algorithm : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::string String; typedef libpipe::rtc::SharedData<String> SharedString; static Algorithm* create() { return new ROT13Algorithm; } /** virtual Destructor */ virtual ~ROT13Algorithm() { } /** Runs the algorithm and updates the output data. * If the request type is DELETE the input gets deleted. * This is where all the algorithm implementation goes. * @param[in,out] req The request object, forwarded from \c process request. * @return The request */ void update(libpipe::Request& req) { LIBPIPE_PREPARE_READ_ACCESS(input_, dataIn_, String, "StringInput"); LIBPIPE_PREPARE_WRITE_ACCESS(output_, dataOut_, String, "StringOutput"); if (req.is(libpipe::Request::UPDATE) && this->needUpdate()) { LIBPIPE_PIPELINE_TRACE("ROT13Algorithm::update: start."); dataOut_.clear(); LIBPIPE_PIPELINE_TRACE( "ROT13Algorithm::update: transforming with ROT13."); rot13(dataIn_, dataOut_); LIBPIPE_PIPELINE_TRACE("ROT13Algorithm::update: end."); } else if (req.is(libpipe::Request::DELETE)) { input_.reset(); LIBPIPE_PIPELINE_TRACE( "ROT13Algorithm::update: deleted the input"); } #ifdef ENABLE_THREADING output_->unlock(); input_->unlock(); #endif } protected: private: /** * Function to calculate the ROT13 cipher * @param[in] str A handle to the input string * @param[out] result A handle to the ciphered input */ void rot13(const String& str, String& result) { static std::string const lcalph = "abcdefghijklmnopqrstuvwxyz", ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string::size_type pos; result.reserve(str.length()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if ((pos = lcalph.find(*it)) != std::string::npos) result.push_back(lcalph[(pos + 13) % 26]); else if ((pos = ucalph.find(*it)) != std::string::npos) result.push_back(ucalph[(pos + 13) % 26]); else result.push_back(*it); } } /** Constructor. * Make sure to call the \c libpipe::Algorithm constructor. */ ROT13Algorithm() : libpipe::rtc::Algorithm() { ports_["StringInput"] = boost::make_shared<SharedString>(); ports_["StringOutput"] = boost::make_shared<SharedString>( new std::string); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "ROT13Algorithm"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, ROT13Algorithm::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool ROT13Algorithm::registered_ = registerLoader(); /** Provides a constant string as output. * This is an example of a 'source'. The \c Source algorithm does not require * any input and will always provide a predefined string as its output. */ class Source : public libpipe::rtc::Algorithm { public: // use convenience typedefs to avoid cluttering up the code typedef std::string String; typedef libpipe::rtc::SharedData<String> SharedString; static Algorithm* create() { return new Source; } /** Destructor. */ virtual ~Source() { } /** Updates the output data (i.e. does nothing). * The output is provided as a constant, hence there is nothing to do. * @param[in] req The request object. * @return The request object. */ void update(libpipe::Request& req) { LIBPIPE_PREPARE_WRITE_ACCESS(output_, tempOut, String, "StringOutput"); String temp = parameters_.get<String>("SourceString") + parameters_.get<String>("SourceString2"); tempOut = temp; #ifdef ENABLE_THREADING output_->unlock(); #endif } protected: private: /** Constructor. */ Source() : libpipe::rtc::Algorithm() { ports_["StringOutput"] = boost::make_shared<SharedString>( new std::string("")); } /** registers the Algorithm in the factory * @return true is registration was successful */ static const bool registerLoader() { std::string ids = "Source"; return libpipe::rtc::AlgorithmFactory::instance().registerType(ids, Source::create); } /// true is class is registered in Algorithm Factory static const bool registered_; }; const bool Source::registered_ = registerLoader(); int main(int argc, char *argv[]) { using namespace libpipe::rtc; std::map<std::string, std::string> inputFiles; inputFiles["FilterInput"] = "inputFileFilterJSON.txt"; inputFiles["ConnectionInput"] = "inputFileConnectionJSON.txt"; inputFiles["PipelineInput"] = "inputFilePipelineJSON.txt"; inputFiles["ParameterInput"] = "inputFileParametersJSON.txt"; Pipeline pipeline; try { PipelineLoader loader(inputFiles); pipeline = loader.getPipeline(); } catch (libpipe::utilities::Exception& e) { std::cerr << e.what() << std::endl; } try { pipeline.run(); } catch (libpipe::utilities::Exception& e) { std::cerr << e.what() << std::endl; } std::vector<std::string> trace; trace = pipeline.getTrace(); for (std::vector<std::string>::const_iterator i = trace.begin(); i != trace.end(); ++i) { std::cout << *i << '\n'; } std::cout << "All output after this is due to automatically called destructors." << std::endl; return EXIT_SUCCESS; }
32.346863
84
0.592745
34e5fb3069618dfe4b629d3f544a01ef8e570dde
2,942
cpp
C++
core/CODeMDistribution.cpp
shaulsal/CODeM
8cc85972cbb21ec55f323e6a049429b9ab2e2c74
[ "MIT" ]
null
null
null
core/CODeMDistribution.cpp
shaulsal/CODeM
8cc85972cbb21ec55f323e6a049429b9ab2e2c74
[ "MIT" ]
null
null
null
core/CODeMDistribution.cpp
shaulsal/CODeM
8cc85972cbb21ec55f323e6a049429b9ab2e2c74
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2012-2015 The University of Sheffield (www.sheffield.ac.uk) ** ** This file is part of Liger. ** ** GNU Lesser General Public License Usage ** 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. ** ****************************************************************************/ #include <core/CODeMDistribution.h> #include <core/CODeMOperators.h> #include <core/Distributions/IDistribution.h> #include <tigon/Utils/NormalisationUtils.h> namespace CODeM { CODeMDistribution::CODeMDistribution(IDistribution* d, const vector<double> oVec, double lowerBound, double upperBound, const vector<double> ideal, const vector<double> antiIdeal, double dirPertRad, double dirPertNorm) : m_lb(lowerBound), m_ub(upperBound), m_pNorm(1) { defineDistribution(d); defineIdealAndAntiIdeal(ideal, antiIdeal); defineDirection(oVec); defineDirectionPertRadius(dirPertRad); definePerturbationNorm(dirPertNorm); } CODeMDistribution::~CODeMDistribution() { } vector<double> CODeMDistribution::sampleDistribution() { if(m_distribution.isNull()) { return vector<double>(0); } double sFactor = m_distribution->sample(); // scale to the interval [lb ub] sFactor = m_lb + sFactor*(m_ub-m_lb); // scale the 2-norm direction vector vector<double> samp = m_direction; scale(samp,sFactor); samp = directionPerturbation(samp, m_directionPertRadius, m_pNorm); scaleBackFromUnitBox(samp, m_ideal, m_antiIdeal); return samp; } void CODeMDistribution::defineDirectionPertRadius(double r) { if(r >= 0.0) { m_directionPertRadius = r; } } void CODeMDistribution::definePerturbationNorm(double p) { if(p > 0.0) { m_pNorm = p; } } void CODeMDistribution::defineDirection(const vector<double> oVec) { m_direction = oVec; normaliseToUnitBox(m_direction, m_ideal, m_antiIdeal); toUnitVec(m_direction); } void CODeMDistribution::defineIdealAndAntiIdeal(const vector<double> ideal, const vector<double> antiIdeal) { m_ideal = ideal; m_antiIdeal = antiIdeal; } void CODeMDistribution::defineDistribution(IDistribution* d) { m_distribution = d; } } // namespace CODeM
29.128713
79
0.615228
34ec9e7f840721668c5b529c756e4cf5d515b7b4
753
hpp
C++
test/framework/test_logger.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
test/framework/test_logger.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
test/framework/test_logger.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef TEST_FRAMEWORK_TEST_LOGGER_HPP #define TEST_FRAMEWORK_TEST_LOGGER_HPP #include "logger/logger.hpp" #include "logger/logger_manager_fwd.hpp" /// Allows to log objects, which have toString() method without calling it, e.g. /// log.info("{}", myObject) template <typename StreamType, typename T> auto operator<<(StreamType &os, const T &object) -> decltype(os << object.toString()) { return os << object.toString(); } logger::LoggerManagerTreePtr getTestLoggerManager( const logger::LogLevel &log_level = logger::LogLevel::kDebug); logger::LoggerPtr getTestLogger(const std::string &tag); #endif // TEST_FRAMEWORK_TEST_LOGGER_HPP
28.961538
80
0.746348
34ef50181b03004b1772f96aee5628700062067b
2,797
cpp
C++
CardReaderLibrary/ImageEditHelper.cpp
klanderfri/CardReaderLibrary
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
4
2019-03-18T14:06:59.000Z
2021-07-17T18:36:12.000Z
CardReaderLibrary/ImageEditHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
17
2018-04-12T18:03:16.000Z
2018-05-09T18:33:07.000Z
CardReaderLibrary/ImageEditHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
1
2019-03-25T18:31:17.000Z
2019-03-25T18:31:17.000Z
#include "stdafx.h" #include "ImageEditHelper.h" #include <opencv2\imgproc.hpp> using namespace cv; using namespace std; ImageEditHelper::ImageEditHelper() { this->converter = new ConversionHelper(); this->rectangleMethods = new RectangleHelper(); this->imageInfo = new ImageInformationHelper(); this->transformations = new TransformHelper(); } ImageEditHelper::~ImageEditHelper() { delete converter; delete rectangleMethods; delete imageInfo; delete transformations; } void ImageEditHelper::RotateImage(const Mat rawImage, Mat& outImage, const double angleToRotate, const Point2f centerPoint) { //Implemented as suggested at: //http://opencvexamples.blogspot.com/2014/01/rotate-image.html Mat r = getRotationMatrix2D(centerPoint, angleToRotate, 1.0); //Seems like INTER_LANCZOS4 causes the least blur. //See https://stackoverflow.com/questions/24953935/opencv-image-getting-blurred-when-rotating-with-warpaffine warpAffine(rawImage, outImage, r, Size(rawImage.cols, rawImage.rows), INTER_LANCZOS4); } void ImageEditHelper::StraightenUpImage(const Mat rawImage, Mat& outImage, const RotatedRect rawCardArea, Rect2f& outCardArea, bool enforcePortraitMode) { //Rotate the image to straighten up the card. double angleToRotate = rectangleMethods->GetAnglesToStrightenUp(rawCardArea, enforcePortraitMode); RotateImage(rawImage, outImage, angleToRotate, rawCardArea.center); //Rotate the card area rectangle. outCardArea = converter->ToStraightRectangle(rawCardArea, enforcePortraitMode); } void ImageEditHelper::CropImage(const Mat rawImage, Mat& outImage, const Rect cropArea) { float centerX = (float)cropArea.x + cropArea.size().width / 2; float centerY = (float)cropArea.y + cropArea.size().height / 2; Point2f center(centerX, centerY); getRectSubPix(rawImage, cropArea.size(), center, outImage); } void ImageEditHelper::CropImageWithSolidBorder(const Mat rawImage, Mat& outImage, const Rect cropArea, int borderThickness) { //Crop the image. CropImage(rawImage, outImage, cropArea); //Add the border. copyMakeBorder( outImage, outImage, borderThickness, borderThickness, borderThickness, borderThickness, BORDER_ISOLATED, converter->ToScalarColour(White)); } void ImageEditHelper::ResizeImage(const Mat rawImage, Mat& outImage, int height) { float ratio = (float)rawImage.size().height / rawImage.size().width; int width = (int)round(height / ratio); Size newSize(width, height); resize(rawImage, outImage, newSize); } void ImageEditHelper::SetBackgroundByInverting(Mat& blackAndWhiteimage, bool setblackBackground) { bool isblackOnWhite = imageInfo->IsBlackTextWhiteBackground(blackAndWhiteimage); if (setblackBackground && isblackOnWhite || !setblackBackground && !isblackOnWhite) { blackAndWhiteimage = ~blackAndWhiteimage; } }
32.905882
154
0.782267
34f211ffa6f801582b60db6fe75a22298c813dd3
1,331
cpp
C++
src/library/sorry.cpp
leodemoura/lean_clone
cc077554b584d39bab55c360bc12a6fe7957afe6
[ "Apache-2.0" ]
130
2016-12-02T22:46:10.000Z
2022-03-22T01:09:48.000Z
src/library/sorry.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
8
2017-05-03T01:21:08.000Z
2020-02-25T11:38:05.000Z
src/library/sorry.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
28
2016-12-02T22:46:20.000Z
2022-03-18T21:28:20.000Z
/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/type_checker.h" #include "kernel/environment.h" #include "library/module.h" #include "library/constants.h" namespace lean { static name * g_l = nullptr; static expr * g_sorry_type = nullptr; void initialize_sorry() { g_l = new name("l"); g_sorry_type = new expr(mk_pi("A", mk_sort(mk_param_univ(*g_l)), mk_var(0), binder_info(true))); } void finalize_sorry() { delete g_sorry_type; delete g_l; } bool has_sorry(environment const & env) { auto decl = env.find(get_sorry_name()); return decl && decl->get_type() == *g_sorry_type; } environment declare_sorry(environment const & env) { if (auto decl = env.find(get_sorry_name())) { if (decl->get_type() != *g_sorry_type) throw exception("failed to declare 'sorry', environment already has an object named 'sorry'"); return env; } else { return module::add(env, check(env, mk_constant_assumption(get_sorry_name(), list<name>(*g_l), *g_sorry_type))); } } expr mk_sorry() { return mk_constant(get_sorry_name()); } bool is_sorry(expr const & e) { return is_constant(e) && const_name(e) == get_sorry_name(); } }
30.25
119
0.67994
34f55e2c82c209303e5e12fa681355f0770aae26
11,053
cpp
C++
src/module_handler/handler_base.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
src/module_handler/handler_base.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
src/module_handler/handler_base.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
#include "handler_base.h" #include <base/timer.h> #include <base/config.hpp> #include <base/logger/logger.h> #include <module_net/net/nat_type.hpp> #include <module_net/session_manager.h> #include <module_peer/routing_table.h> #include <module_peer/partner_table.h> #define BASE_REGISTER(_FUNC) std::bind(&HandlerBase::_FUNC,this, \ std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) //定时器事件 static bool heartbeat_probe(uint16_t SessionId) { net::Session* pCurSession = g_pSessionManager->session(SessionId); if (nullptr == pCurSession) { return true; } //当前连接断开,终止定时器 if (SessionStatus::STATUS_CONNECT_COMPLETE != pCurSession->status()) { return true; } //所有数据包都会重置超时次数,如果当前超时次数为0,这时得到1 uint8_t TimeoutCount = pCurSession->timeout(); //=2表示当前时间段内没有数据传输,发送一个心跳包检测 if (2 == TimeoutCount) { //对端收到之后会发送KCP的ACK报文,收到后会重置超时次数 //发送一个长度为0的心跳包即可 pCurSession->send_reliable(nullptr, 0); } else if (3 == TimeoutCount) { //断开连接 pCurSession->set_status(SessionStatus::STATUS_DISCONNECT); LOG_TRACE << "Session ID = " << SessionId << " disconnect, Reason:Timeout."; g_pSessionManager->disconnect_in_timer(SessionId); return true; } return false; } //定时器事件 namespace handler { HandlerBase::HandlerBase() {} void HandlerBase::register_recv_event() { //注册Recv事件的处理方式 //m_RecvHandlerMap[PROTOCOL_BASE_HEARTBEAT_ACK] = BASE_REGISTER(handle_heartbeat_ack); m_RecvHandlerMap[PROTOCOL_BASE_HEARTBEAT_REQ] = BASE_REGISTER(handle_heartbeat_req); m_RecvHandlerMap[PROTOCOL_BASE_PING_REQ] = BASE_REGISTER(handle_ping_req); m_RecvHandlerMap[PROTOCOL_BASE_PING_ACK] = BASE_REGISTER(handle_ping_ack); m_RecvHandlerMap[PROTOCOL_BASE_PING_HELP] = BASE_REGISTER(handle_ping_help); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_REQ] = BASE_REGISTER(handle_connect_req); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_ACK] = BASE_REGISTER(handle_connect_ack); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_RFS] = BASE_REGISTER(handle_connect_rfs); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_HELP_REQ] = BASE_REGISTER(handle_connect_help_req); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_HELP_ACK] = BASE_REGISTER(handle_connect_help_ack); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_HELP_RFS] = BASE_REGISTER(handle_connect_help_rfs); m_RecvHandlerMap[PROTOCOL_BASE_DISCONNECT] = BASE_REGISTER(handle_disconnect); m_RecvHandlerMap[PROTOCOL_BASE_NAT_TYPE_PROBE_REQ] = BASE_REGISTER(handle_nat_probe_req); m_RecvHandlerMap[PROTOCOL_BASE_NAT_TYPE_PROBE_ACK] = BASE_REGISTER(handle_nat_probe_ack); } void HandlerBase::register_gateway_event() { //注册Gateway事件的处理方式 m_RecvHandlerMap[PROTOCOL_BASE_PING_REQ] = BASE_REGISTER(handle_ping_req); m_RecvHandlerMap[PROTOCOL_BASE_PING_ACK] = BASE_REGISTER(handle_ping_ack); m_RecvHandlerMap[PROTOCOL_BASE_CONNECT_REQ] = BASE_REGISTER(handle_connect_req); m_RecvHandlerMap[PROTOCOL_BASE_NAT_TYPE_PROBE_REQ] = BASE_REGISTER(handle_nat_probe_req); m_RecvHandlerMap[PROTOCOL_BASE_NAT_TYPE_PROBE_ACK] = BASE_REGISTER(handle_nat_probe_ack); } int8_t HandlerBase::handle_event(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //解析基础协议头 uint16_t ProtocolId; parse_header(pMessage, ProtocolId); //如果协议注册过 if (0 != m_RecvHandlerMap.count(ProtocolId)) { return m_RecvHandlerMap[ProtocolId](SessionId, pMessage, Len); } //未注册协议直接无视 return DO_NOTHING; } int8_t HandlerBase::handle_connect_req(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //对端节点申请建立连接,如果连接建立需要加入定时器检测心跳包 //还未建立连接 if (ERROR_SESSION_ID == SessionId) { //回复接受 return DO_CONNECT; } //已建立连接,回复CONNECT_ACK create_header(pMessage, PROTOCOL_BASE_CONNECT_ACK); return DO_REPLY; } int8_t HandlerBase::handle_connect_ack(uint16_t& SessionId, char* pMessage, uint16_t& Len) { net::Session* pCurSession = g_pSessionManager->session(SessionId); if (nullptr == pCurSession) { return DO_NOTHING; } //第一次收到ACK包,创建定时器 if (SessionStatus::STATUS_CONNECT_COMPLETE != pCurSession->status()) { pCurSession->set_status(SessionStatus::STATUS_CONNECT_COMPLETE); //定时检测超时状态,然后发送心跳包 g_pTimer->add_timer(HEARTBEAT_CLOCK, std::bind(heartbeat_probe, SessionId)); //连接成功,接下来需要注册PID和查询CID g_pPeerManager->register_push(SessionId); {//TEST std::string strIP; uint16_t Port; PeerAddress CurPeerAddr = { 0 }; pCurSession->get_peer_addr(CurPeerAddr); bool res1 = peer::PeerManager::info(CurPeerAddr, strIP, Port); if (false != res1) { LOG_TRACE << "Connect to [" << strIP << ":" << Port<<"] successfully."; } }//TEST } //无需回复 return DO_NOTHING; } int8_t HandlerBase::handle_connect_rfs(uint16_t& SessionId, char* pMessage, uint16_t& Len) { LOG_DEBUG << "Connect Fail"; //对端节点发送CONNECT_RFS,表示对端节点拒绝建立连接,但是可以发送询问消息 if (ERROR_SESSION_ID == SessionId) { return DO_NOTHING; } return DO_DISCONNECT; } int8_t HandlerBase::handle_connect_help_req(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //其他Peer想要连接某个Peer,但是因为NAT的原因无法连接 //想通过我帮他建立连接 //Req发起连接的请求方 //Target被连接的接收方 uint16_t ReqSessionId = SessionId; net::Session* pReqSession = g_pSessionManager->session(ReqSessionId); if (nullptr == pReqSession) { return DO_NOTHING; } PeerAddress ReqPeerAddr = { 0 }, TargetPeerAddr = { 0 }; pReqSession->get_peer_addr(ReqPeerAddr); memcpy(&TargetPeerAddr, &pMessage[BASE_HEADER_LEN], KSOCKADDR_LEN_V6); uint16_t TargetSessionId = g_pPeerManager->session_id(TargetPeerAddr); {//Test std::string strIP, strIP1; uint16_t Port, Port1; bool res1 = peer::PeerManager::info(ReqPeerAddr, strIP, Port); bool res2 = peer::PeerManager::info(TargetPeerAddr, strIP1, Port1); if (res1 && res2) { LOG_TRACE << "["<<strIP << ":" << Port << "] want to connect [" << strIP1 << ":" << Port1<<"]"; } }//Test //目标Peer不可达,拒绝协助 if (0 == TargetSessionId || ERROR_SESSION_ID == TargetSessionId) { create_header(pMessage, PROTOCOL_BASE_CONNECT_HELP_RFS); pReqSession->send_reliable(pMessage, BASE_HEADER_LEN + KSOCKADDR_LEN_V6); return DO_NOTHING; } net::Session* pTargetSession = g_pSessionManager->session(TargetSessionId); if (nullptr == pTargetSession) { create_header(pMessage, PROTOCOL_BASE_CONNECT_HELP_RFS); pReqSession->send_reliable(pMessage, BASE_HEADER_LEN + KSOCKADDR_LEN_V6); return DO_NOTHING; } //可以协助当前Peer create_header(pMessage, PROTOCOL_BASE_CONNECT_HELP_ACK); //告知请求节点尝试继续连接,已通知目标节点协助UDP打洞 pReqSession->send_reliable(pMessage, Len); create_header(pMessage, PROTOCOL_BASE_PING_HELP); memcpy(&pMessage[BASE_HEADER_LEN], &ReqPeerAddr, KSOCKADDR_LEN_V6); //通知目标节点协助UDP打洞 pTargetSession->send_reliable(pMessage, BASE_HEADER_LEN + KSOCKADDR_LEN_V6); //TEST { std::string strIP, strIP1; uint16_t Port, Port1; bool res1 = peer::PeerManager::info(ReqPeerAddr, strIP, Port); bool res2 = peer::PeerManager::info(TargetPeerAddr, strIP1, Port1); if (res1 && res2) { LOG_TRACE << "Try help [" << strIP << ":" << Port << "] connect [" << strIP1 << ":" << Port1<<"]"; } } //TEST return DO_NOTHING; } int8_t HandlerBase::handle_connect_help_ack(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //对方已接受请求,已经通知另一个节点尝试ping自己 //如果NAT没问题可以实现UDP打洞 //继续尝试连接 PeerAddress TargetPeerAddr = { 0 }; memcpy(&TargetPeerAddr, &pMessage[BASE_HEADER_LEN], KSOCKADDR_LEN_V6); const uint8_t* pKey = (uint8_t*)&pMessage[BASE_HEADER_LEN+ KSOCKADDR_LEN_V6]; base::SHA1 CID = { 0 }; memcpy(&CID, pKey, KLEN_KEY); g_pSessionManager->connect_peer(CID, TargetPeerAddr); {//TEST std::string strIP, strIP1; uint16_t Port, Port1; net::Session* pAckSession = g_pSessionManager->session(SessionId); PeerAddress AckPeerAddr = { 0 }; pAckSession->get_peer_addr(AckPeerAddr); if (nullptr != pAckSession) { bool res1 = peer::PeerManager::info(AckPeerAddr, strIP, Port); bool res2 = peer::PeerManager::info(TargetPeerAddr, strIP1, Port1); if (res1 && res2) { LOG_TRACE << "["<<strIP << ":" << Port << "] will help me to connect [" << strIP1 << ":" << Port1<<"]"; } } } return DO_NOTHING; } int8_t HandlerBase::handle_connect_help_rfs(uint16_t& SessionId, char* pMessage, uint16_t& Len) { LOG_ERROR << "Conenct Help Rfs"; //拒绝协助,就直接断开连接 PeerAddress TargetPeeraddr = { 0 }; memcpy(&TargetPeeraddr, &pMessage[2], KSOCKADDR_LEN_V6); uint16_t TargetSessionId = g_pPeerManager->session_id(TargetPeeraddr); if (0 != TargetSessionId && ERROR_SESSION_ID != TargetSessionId) { g_pSessionManager->disconnect(TargetSessionId); //Test { std::string strIP; uint16_t Port; bool res = peer::PeerManager::info(TargetPeeraddr, strIP, Port); if (true == res) { LOG_TRACE << "Fail to connect " << strIP << ":" << Port << ", Relay Node can't help."; } } //Test } return DO_NOTHING; } int8_t HandlerBase::handle_ping_ack(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //对端节点发送PING_ACK,表示本机与对端节点可以建立直接连接并通信 net::Session* pCurSession = g_pSessionManager->session(SessionId); if (nullptr != pCurSession) { if (SessionStatus::STATUS_DISCONNECT == pCurSession->status()) { pCurSession->set_status(SessionStatus::STATUS_PING_COMPLETE); } } //无需回复 return DO_NOTHING; } int8_t HandlerBase::handle_ping_req(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //对端节点发送PING_REQ,尝试ping本机,直接回复ACK create_header(pMessage, PROTOCOL_BASE_PING_ACK); //当前状态未连接 return DO_REPLY; } int8_t HandlerBase::handle_ping_help(uint16_t& SessionId, char* pMessage, uint16_t& Len) { PeerAddress TargetPeerAddr = { 0 }; memcpy(&TargetPeerAddr, &pMessage[BASE_HEADER_LEN], KSOCKADDR_LEN_V6); g_pSessionManager->ping_peer(TargetPeerAddr); //TEST { std::string strIP; uint16_t Port; bool res1 = peer::PeerManager::info(TargetPeerAddr, strIP, Port); if (res1) { LOG_TRACE << "Ping [" << strIP << ":" << Port << "] to help it to connect me."; } } //TEST return DO_NOTHING; } int8_t HandlerBase::handle_heartbeat_req(uint16_t& SessionId, char* pMessage, uint16_t& Len) { LOG_DEBUG << "Recv Heartbeat"; //对端节点发送HEARTBEAT_REQ //重置心跳包定时器超时计数 net::Session* pCurSession = g_pSessionManager->session(SessionId); if (nullptr != pCurSession) { pCurSession->reset_timeout(); //回复HEARTBEAT_ACK表示连接无异常 create_header(pMessage, PROTOCOL_BASE_HEARTBEAT_ACK); return DO_REPLY; } return DO_NOTHING; } int8_t HandlerBase::handle_disconnect(uint16_t& SessionId, char* pMessage, uint16_t& Len) { return DO_DISCONNECT; } int8_t HandlerBase::handle_nat_probe_req(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //直接用其他端口返回NAT确认 LOG_TRACE << "NAT probe"; create_header(pMessage, PROTOCOL_BASE_NAT_TYPE_PROBE_ACK); return DO_REPLY_NAT; } int8_t HandlerBase::handle_nat_probe_ack(uint16_t& SessionId, char* pMessage, uint16_t& Len) { //能够收到表面自身NAT类型为B+ LOG_TRACE << "NAT = B+"; g_pHostNatType->set_nat_type(NAT_TYPE::NAT_TYPE_B_PLUS); //无需回复 return DO_NOTHING; } }
30.788301
108
0.733104
34f78628ca0943ee66cfcaa60a42f807b598d9f2
38,754
cpp
C++
JkDefrag/Source/JkDefragGui.cpp
dasmurphy/JKDefrag-Original
b6e636d073c7e3b72887f688ada0b3d60471a277
[ "Apache-2.0" ]
6
2019-04-03T19:50:40.000Z
2022-03-22T15:59:08.000Z
JkDefrag/Source/JkDefragGui.cpp
7lima/JKDefrag-Original
732af9e2858ba3bf0f94a1741ac5698d89b811da
[ "Apache-2.0" ]
null
null
null
JkDefrag/Source/JkDefragGui.cpp
7lima/JKDefrag-Original
732af9e2858ba3bf0f94a1741ac5698d89b811da
[ "Apache-2.0" ]
4
2019-02-28T18:30:10.000Z
2020-11-01T16:32:39.000Z
#include "StdAfx.h" /* #include "JKDefragStruct.h" #include "JKDefragLog.h" #include "JkDefragLib.h" #include "JkDefragGui.h" */ JKDefragGui *JKDefragGui::m_jkDefragGui = 0; JKDefragGui::JKDefragGui() { m_jkLib = JKDefragLib::getInstance(); m_bmp = NULL; jkStruct = new JKDefragStruct(); m_squareSize = 12; // m_clusterSquares = NULL; m_numDiskSquares = 0; m_offsetX = 26; m_offsetY = 16; clusterInfo = NULL; m_numClusters = 1; ProgressStartTime = 0; ProgressTime = 0; ProgressDone = 0; int i = 0; for (i = 0; i < 6; i++) *Messages[i] = '\0'; // RedrawScreen = 0; } JKDefragGui::~JKDefragGui() { delete jkStruct; delete m_jkDefragGui; /* if (m_jkDefragGui->m_clusterSquares != NULL) { delete[] m_jkDefragGui->m_clusterSquares; } */ if (m_bmp != NULL) { delete m_bmp; } } JKDefragGui *JKDefragGui::getInstance() { if (m_jkDefragGui == NULL) { m_jkDefragGui = new JKDefragGui(); } return m_jkDefragGui; } int JKDefragGui::Initialize(HINSTANCE hInstance, int nCmdShow, JKDefragLog *jkLog, int debugLevel) { ULONG_PTR gdiplusToken; GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); m_jkLog = jkLog; m_debugLevel = debugLevel; m_displayMutex = CreateMutex(NULL,FALSE,"JKDefrag"); m_wndClass.cbClsExtra = 0; m_wndClass.cbWndExtra = 0; m_wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); m_wndClass.hCursor = LoadCursor(NULL,IDC_ARROW); m_wndClass.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(1)); m_wndClass.hInstance = hInstance; m_wndClass.lpfnWndProc = (WNDPROC)JKDefragGui::ProcessMessagefn; m_wndClass.lpszClassName = "MyClass"; m_wndClass.lpszMenuName = NULL; m_wndClass.style = CS_HREDRAW | CS_VREDRAW; m_wndClass.cbSize = sizeof(WNDCLASSEX); m_wndClass.hIconSm = LoadIcon(hInstance,MAKEINTRESOURCE(1)); CHAR koko[100]; LoadString(hInstance,2,koko, 99); if (RegisterClassEx(&m_wndClass) == 0) { MessageBoxW(NULL,L"Cannot register class",jkStruct->VERSIONTEXT,MB_ICONEXCLAMATION | MB_OK); return(0); } m_hWnd = CreateWindowW(L"MyClass",jkStruct->VERSIONTEXT,WS_TILEDWINDOW, CW_USEDEFAULT,0,1024,768,NULL,NULL,hInstance,NULL); if (m_hWnd == NULL) { MessageBoxW(NULL,L"Cannot create window",jkStruct->VERSIONTEXT,MB_ICONEXCLAMATION | MB_OK); return(0); } /* Show the window in the state that Windows has specified, minimized or maximized. */ ShowWindow(m_hWnd,nCmdShow); UpdateWindow(m_hWnd); SetTimer(m_hWnd,1,300,NULL); // InvalidateRect(m_hWnd,NULL,FALSE); return 1; } WPARAM JKDefragGui::DoModal() { int GetMessageResult; /* The main message thread. */ while (TRUE) { GetMessageResult = GetMessage(&Message,NULL,0,0); if (GetMessageResult == 0) break; if (GetMessageResult == -1) break; if (Message.message == WM_QUIT) break; TranslateMessage(&Message); DispatchMessage(&Message); } return Message.wParam;; } void JKDefragGui::setDisplayData(HDC hdc) { Graphics graphics(hdc); Rect clientWindowSize; Status status = graphics.GetVisibleClipBounds(&clientWindowSize); m_clientWindowSize = clientWindowSize; /* if (m_clusterSquares != NULL) { delete[] m_clusterSquares; } */ m_topHeight = 33; if (m_debugLevel > 1) { m_topHeight = 49; } m_diskAreaSize.Width = clientWindowSize.Width - m_offsetX * 2; m_diskAreaSize.Height = clientWindowSize.Height - m_topHeight - m_offsetY * 2; m_numDiskSquaresX = (int)(m_diskAreaSize.Width / m_squareSize); m_numDiskSquaresY = (int)(m_diskAreaSize.Height / m_squareSize); m_numDiskSquares = m_numDiskSquaresX * m_numDiskSquaresY; // m_clusterSquares = new clusterSquareStruct[m_numDiskSquares]; for (int ii = 0; ii < m_numDiskSquares; ii++) { m_clusterSquares[ii].color = 0; m_clusterSquares[ii].dirty = true; } m_realOffsetX = (int)((m_clientWindowSize.Width - m_numDiskSquaresX * m_squareSize) * 0.5); m_realOffsetY = (int)((m_clientWindowSize.Height - m_topHeight - m_numDiskSquaresY * m_squareSize) * 0.5); if (m_bmp != NULL) { delete m_bmp; m_bmp = NULL; } m_bmp = new Bitmap(m_clientWindowSize.Width, m_clientWindowSize.Height); // Color bottomPartColor; // bottomPartColor.SetFromCOLORREF(RGB(255,255,255)); // SolidBrush bottomPartBrush(bottomPartColor); // Rect drawArea(0, 0, m_clientWindowSize.Width, m_clientWindowSize.Height); // graphics.FillRectangle(&bottomPartBrush, drawArea); /* Ask defragger to completely redraw the screen. */ // RedrawScreen = 0; } /* Callback: clear the screen. */ void JKDefragGui::ClearScreen(WCHAR *Format, ...) { va_list VarArgs; int i; /* If there is no message then return. */ if (Format == NULL) return; /* Clear all the messages. */ for (i = 0; i < 6; i++) *Messages[i] = '\0'; /* Save the message in Messages 0. */ va_start(VarArgs,Format); vswprintf_s(Messages[0],50000,Format,VarArgs); /* If there is no logfile then return. */ if (m_jkLog != NULL) { m_jkLog->LogMessage(Format, VarArgs); } va_end(VarArgs); PaintImage(m_hDC); // InvalidateRect(m_hWnd,NULL,FALSE); } /* Callback: whenever an item (file, directory) is moved on disk. */ void JKDefragGui::ShowMove(struct ItemStruct *Item, ULONG64 Clusters, ULONG64 FromLcn, ULONG64 ToLcn, ULONG64 FromVcn) { /* Save the message in Messages 3. */ if (Clusters == 1) { swprintf_s(Messages[3],50000,L"Moving 1 cluster from %I64d to %I64d.",FromLcn,ToLcn); } else { swprintf_s(Messages[3],50000,L"Moving %I64d clusters from %I64d to %I64d.", Clusters,FromLcn,ToLcn); } /* Save the name of the file in Messages 4. */ if ((Item != NULL) && (Item->LongPath != NULL)) { swprintf_s(Messages[4],50000,L"%s",Item->LongPath); } else { *(Messages[4]) = '\0'; } /* If debug mode then write a message to the logfile. */ if (m_debugLevel < 3) return; if (FromVcn > 0) { if (Clusters == 1) { m_jkLog->LogMessage(L"%s\n Moving 1 cluster from %I64d to %I64d, VCN=%I64d.", Item->LongPath,FromLcn,ToLcn,FromVcn); } else { m_jkLog->LogMessage(L"%s\n Moving %I64d clusters from %I64d to %I64d, VCN=%I64d.", Item->LongPath,Clusters,FromLcn,ToLcn,FromVcn); } } else { if (Clusters == 1) { m_jkLog->LogMessage(L"%s\n Moving 1 cluster from %I64d to %I64d.", Item->LongPath,FromLcn,ToLcn); } else { m_jkLog->LogMessage(L"%s\n Moving %I64d clusters from %I64d to %I64d.", Item->LongPath,Clusters,FromLcn,ToLcn); } } PaintImage(m_hDC); // InvalidateRect(m_hWnd,NULL,FALSE); } /* Callback: for every file during analysis. This subroutine is called one last time with Item=NULL when analysis has finished. */ void JKDefragGui::ShowAnalyze(struct DefragDataStruct *Data, struct ItemStruct *Item) { if ((Data != NULL) && (Data->CountAllFiles != 0)) { swprintf_s(Messages[3],50000,L"Files %I64d, Directories %I64d, Clusters %I64d", Data->CountAllFiles,Data->CountDirectories,Data->CountAllClusters); } else { swprintf_s(Messages[3],50000,L"Applying Exclude and SpaceHogs masks...."); } /* Save the name of the file in Messages 4. */ if ((Item != NULL) && (Item->LongPath != NULL)) { swprintf_s(Messages[4],50000,L"%s",Item->LongPath); } else { *(Messages[4]) = '\0'; } PaintImage(m_hDC); // InvalidateRect(m_hWnd,NULL,FALSE); } /* Callback: show a debug message. */ void JKDefragGui::ShowDebug(int Level, struct ItemStruct *Item, WCHAR *Format, ...) { va_list VarArgs; if (m_debugLevel < Level) return; /* Save the name of the file in Messages 4. */ if ((Item != NULL) && (Item->LongPath != NULL)) { swprintf_s(Messages[4],50000,L"%s",Item->LongPath); } /* If there is no message then return. */ if (Format == NULL) return; /* Save the debug message in Messages 5. */ va_start(VarArgs,Format); vswprintf_s(Messages[5],50000,Format,VarArgs); m_jkLog->LogMessage(Format, VarArgs); va_end(VarArgs); PaintImage(m_hDC); // InvalidateRect(m_hWnd,NULL,FALSE); } /* Callback: paint a cluster on the screen in a color. */ void JKDefragGui::DrawCluster(struct DefragDataStruct *Data, ULONG64 ClusterStart, ULONG64 ClusterEnd, int Color) { struct __timeb64 Now; Rect windowSize = m_clientWindowSize; /* Save the PhaseTodo and PhaseDone counters for later use by the progress counter. */ if (Data->PhaseTodo != 0) { _ftime64_s(&Now); ProgressTime = Now.time * 1000 + Now.millitm; ProgressDone = Data->PhaseDone; ProgressTodo = Data->PhaseTodo; } /* Sanity check. */ if (Data->TotalClusters == 0) return; if (m_hDC == NULL) return; if (ClusterStart == ClusterEnd) return; // if (ClusterStart > Data->TotalClusters) ClusterStart = 0; WaitForSingleObject(m_displayMutex,100); m_displayMutex = CreateMutex(NULL,FALSE,"JKDefrag"); if (m_numClusters != Data->TotalClusters || clusterInfo == NULL) { if (clusterInfo != NULL) { free(clusterInfo); clusterInfo = NULL; } m_numClusters = Data->TotalClusters; clusterInfo = (byte *)malloc((size_t)m_numClusters); for(int ii = 0; ii <= m_numClusters; ii++) { clusterInfo[ii] = JKDefragStruct::COLOREMPTY; } // RedrawScreen = 0; return; } for(ULONG64 ii = ClusterStart; ii <= ClusterEnd; ii++) { clusterInfo[ii] = Color; } float clusterPerSquare = (float)(m_numClusters / m_numDiskSquares); int clusterStartSquareNum = (int)((ULONG64)ClusterStart / (ULONG64)clusterPerSquare); int clusterEndSquareNum = (int)((ULONG64)ClusterEnd / (ULONG64)clusterPerSquare); FillSquares(clusterStartSquareNum, clusterEndSquareNum); ReleaseMutex(m_displayMutex); PaintImage(m_hDC); // InvalidateRect(m_hWnd,NULL,FALSE); } /* Callback: just before the defragger starts a new Phase, and when it finishes. */ void JKDefragGui::ShowStatus(struct DefragDataStruct *Data) { struct ItemStruct *Item; int Fragments; ULONG64 TotalFragments; ULONG64 TotalBytes; ULONG64 TotalClusters; struct ItemStruct *LargestItems[25]; int LastLargest; struct __timeb64 Now; int i; int j; /* Reset the progress counter. */ _ftime64_s(&Now); ProgressStartTime = Now.time * 1000 + Now.millitm; ProgressTime = ProgressStartTime; ProgressDone = 0; ProgressTodo = 0; /* Reset all the messages. */ for (i = 0; i < 6; i++) *(Messages[i]) = '\0'; /* Update Message 0 and 1. */ if (Data != NULL) { swprintf_s(Messages[0],50000,L"%s",Data->Disk.MountPoint); switch(Data->Phase) { case 1: wcscpy_s(Messages[1],50000,L"Phase 1: Analyze"); break; case 2: wcscpy_s(Messages[1],50000,L"Phase 2: Defragment"); break; case 3: wcscpy_s(Messages[1],50000,L"Phase 3: ForcedFill"); break; case 4: swprintf_s(Messages[1],50000,L"Zone %u: Sort",Data->Zone + 1); break; case 5: swprintf_s(Messages[1],50000,L"Zone %u: Fast Optimize",Data->Zone + 1); break; case 6: wcscpy_s(Messages[1],50000,L"Phase 3: Move Up"); break; case 7: wcscpy_s(Messages[1],50000,L"Finished."); swprintf_s(Messages[4],50000,L"Logfile: %s",m_jkLog->GetLogFilename()); break; case 8: wcscpy_s(Messages[1],50000,L"Phase 3: Fixup"); break; } m_jkLog->LogMessage(Messages[1]); } /* Write some statistics to the logfile. */ if ((Data != NULL) && (Data->Phase == 7)) { m_jkLog->LogMessage(L"- Total disk space: %I64d bytes (%.04f gigabytes), %I64d clusters", Data->BytesPerCluster * Data->TotalClusters, (double)(Data->BytesPerCluster * Data->TotalClusters) / (1024 * 1024 * 1024), Data->TotalClusters); m_jkLog->LogMessage(L"- Bytes per cluster: %I64d bytes",Data->BytesPerCluster); m_jkLog->LogMessage(L"- Number of files: %I64d",Data->CountAllFiles); m_jkLog->LogMessage(L"- Number of directories: %I64d",Data->CountDirectories); m_jkLog->LogMessage(L"- Total size of analyzed items: %I64d bytes (%.04f gigabytes), %I64d clusters", Data->CountAllClusters * Data->BytesPerCluster, (double)(Data->CountAllClusters * Data->BytesPerCluster) / (1024 * 1024 * 1024), Data->CountAllClusters); if (Data->CountAllFiles + Data->CountDirectories > 0) { m_jkLog->LogMessage(L"- Number of fragmented items: %I64d (%.04f%% of all items)", Data->CountFragmentedItems, (double)(Data->CountFragmentedItems * 100) / (Data->CountAllFiles + Data->CountDirectories)); } else { m_jkLog->LogMessage(L"- Number of fragmented items: %I64d",Data->CountFragmentedItems); } if ((Data->CountAllClusters > 0) && (Data->TotalClusters > 0)) { m_jkLog->LogMessage(L"- Total size of fragmented items: %I64d bytes, %I64d clusters, %.04f%% of all items, %.04f%% of disk", Data->CountFragmentedClusters * Data->BytesPerCluster, Data->CountFragmentedClusters, (double)(Data->CountFragmentedClusters * 100) / Data->CountAllClusters, (double)(Data->CountFragmentedClusters * 100) / Data->TotalClusters); } else { m_jkLog->LogMessage(L"- Total size of fragmented items: %I64d bytes, %I64d clusters", Data->CountFragmentedClusters * Data->BytesPerCluster, Data->CountFragmentedClusters); } if (Data->TotalClusters > 0) { m_jkLog->LogMessage(L"- Free disk space: %I64d bytes, %I64d clusters, %.04f%% of disk", Data->CountFreeClusters * Data->BytesPerCluster, Data->CountFreeClusters, (double)(Data->CountFreeClusters * 100) / Data->TotalClusters); } else { m_jkLog->LogMessage(L"- Free disk space: %I64d bytes, %I64d clusters", Data->CountFreeClusters * Data->BytesPerCluster, Data->CountFreeClusters); } m_jkLog->LogMessage(L"- Number of gaps: %I64d",Data->CountGaps); if (Data->CountGaps > 0) { m_jkLog->LogMessage(L"- Number of small gaps: %I64d (%.04f%% of all gaps)", Data->CountGapsLess16, (double)(Data->CountGapsLess16 * 100) / Data->CountGaps); } else { m_jkLog->LogMessage(L"- Number of small gaps: %I64d", Data->CountGapsLess16); } if (Data->CountFreeClusters > 0) { m_jkLog->LogMessage(L"- Size of small gaps: %I64d bytes, %I64d clusters, %.04f%% of free disk space", Data->CountClustersLess16 * Data->BytesPerCluster, Data->CountClustersLess16, (double)(Data->CountClustersLess16 * 100) / Data->CountFreeClusters); } else { m_jkLog->LogMessage(L"- Size of small gaps: %I64d bytes, %I64d clusters", Data->CountClustersLess16 * Data->BytesPerCluster, Data->CountClustersLess16); } if (Data->CountGaps > 0) { m_jkLog->LogMessage(L"- Number of big gaps: %I64d (%.04f%% of all gaps)", Data->CountGaps - Data->CountGapsLess16, (double)((Data->CountGaps - Data->CountGapsLess16) * 100) / Data->CountGaps); } else { m_jkLog->LogMessage(L"- Number of big gaps: %I64d", Data->CountGaps - Data->CountGapsLess16); } if (Data->CountFreeClusters > 0) { m_jkLog->LogMessage(L"- Size of big gaps: %I64d bytes, %I64d clusters, %.04f%% of free disk space", (Data->CountFreeClusters - Data->CountClustersLess16) * Data->BytesPerCluster, Data->CountFreeClusters - Data->CountClustersLess16, (double)((Data->CountFreeClusters - Data->CountClustersLess16) * 100) / Data->CountFreeClusters); } else { m_jkLog->LogMessage(L"- Size of big gaps: %I64d bytes, %I64d clusters", (Data->CountFreeClusters - Data->CountClustersLess16) * Data->BytesPerCluster, Data->CountFreeClusters - Data->CountClustersLess16); } if (Data->CountGaps > 0) { m_jkLog->LogMessage(L"- Average gap size: %.04f clusters", (double)(Data->CountFreeClusters) / Data->CountGaps); } if (Data->CountFreeClusters > 0) { m_jkLog->LogMessage(L"- Biggest gap: %I64d bytes, %I64d clusters, %.04f%% of free disk space", Data->BiggestGap * Data->BytesPerCluster, Data->BiggestGap, (double)(Data->BiggestGap * 100) / Data->CountFreeClusters); } else { m_jkLog->LogMessage(L"- Biggest gap: %I64d bytes, %I64d clusters", Data->BiggestGap * Data->BytesPerCluster, Data->BiggestGap); } if (Data->TotalClusters > 0) { m_jkLog->LogMessage(L"- Average end-begin distance: %.0f clusters, %.4f%% of volume size", Data->AverageDistance,100.0 * Data->AverageDistance / Data->TotalClusters); } else { m_jkLog->LogMessage(L"- Average end-begin distance: %.0f clusters",Data->AverageDistance); } for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if (Item->Unmovable != YES) continue; if (Item->Exclude == YES) continue; if ((Item->Directory == YES) && (Data->CannotMoveDirs > 20)) continue; break; } if (Item != NULL) { m_jkLog->LogMessage(L"These items could not be moved:"); m_jkLog->LogMessage(L" Fragments Bytes Clusters Name"); TotalFragments = 0; TotalBytes = 0; TotalClusters = 0; for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if (Item->Unmovable != YES) continue; if (Item->Exclude == YES) continue; if ((Item->Directory == YES) && (Data->CannotMoveDirs > 20)) continue; if ((Item->LongFilename != NULL) && ((_wcsicmp(Item->LongFilename,L"$BadClus") == 0) || (_wcsicmp(Item->LongFilename,L"$BadClus:$Bad:$DATA") == 0))) continue; Fragments = m_jkLib->FragmentCount(Item); if (Item->LongPath == NULL) { m_jkLog->LogMessage(L" %9lu %11I64u %9I64u [at cluster %I64u]",Fragments,Item->Bytes,Item->Clusters, m_jkLib->GetItemLcn(Item)); } else { m_jkLog->LogMessage(L" %9lu %11I64u %9I64u %s",Fragments,Item->Bytes,Item->Clusters,Item->LongPath); } TotalFragments = TotalFragments + Fragments; TotalBytes = TotalBytes + Item->Bytes; TotalClusters = TotalClusters + Item->Clusters; } m_jkLog->LogMessage(L" --------- ----------- --------- -----"); m_jkLog->LogMessage(L" %9I64u %11I64u %9I64u Total",TotalFragments,TotalBytes,TotalClusters); } for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if (Item->Exclude == YES) continue; if ((Item->Directory == YES) && (Data->CannotMoveDirs > 20)) continue; Fragments = m_jkLib->FragmentCount(Item); if (Fragments <= 1) continue; break; } if (Item != NULL) { m_jkLog->LogMessage(L"These items are still fragmented:"); m_jkLog->LogMessage(L" Fragments Bytes Clusters Name"); TotalFragments = 0; TotalBytes = 0; TotalClusters = 0; for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if (Item->Exclude == YES) continue; if ((Item->Directory == YES) && (Data->CannotMoveDirs > 20)) continue; Fragments = m_jkLib->FragmentCount(Item); if (Fragments <= 1) continue; if (Item->LongPath == NULL) { m_jkLog->LogMessage(L" %9lu %11I64u %9I64u [at cluster %I64u]",Fragments,Item->Bytes,Item->Clusters, m_jkLib->GetItemLcn(Item)); } else { m_jkLog->LogMessage(L" %9lu %11I64u %9I64u %s",Fragments,Item->Bytes,Item->Clusters,Item->LongPath); } TotalFragments = TotalFragments + Fragments; TotalBytes = TotalBytes + Item->Bytes; TotalClusters = TotalClusters + Item->Clusters; } m_jkLog->LogMessage(L" --------- ----------- --------- -----"); m_jkLog->LogMessage(L" %9I64u %11I64u %9I64u Total",TotalFragments,TotalBytes,TotalClusters); } LastLargest = 0; for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if ((Item->LongFilename != NULL) && ((_wcsicmp(Item->LongFilename,L"$BadClus") == 0) || (_wcsicmp(Item->LongFilename,L"$BadClus:$Bad:$DATA") == 0))) { continue; } for (i = LastLargest - 1; i >= 0; i--) { if (Item->Clusters < LargestItems[i]->Clusters) break; if ((Item->Clusters == LargestItems[i]->Clusters) && (Item->Bytes < LargestItems[i]->Bytes)) break; if ((Item->Clusters == LargestItems[i]->Clusters) && (Item->Bytes == LargestItems[i]->Bytes) && (Item->LongPath != NULL) && (LargestItems[i]->LongPath != NULL) && (_wcsicmp(Item->LongPath,LargestItems[i]->LongPath) > 0)) break; } if (i < 24) { if (LastLargest < 25) LastLargest++; for (j = LastLargest - 1; j > i + 1; j--) { LargestItems[j] = LargestItems[j-1]; } LargestItems[i + 1] = Item; } } if (LastLargest > 0) { m_jkLog->LogMessage(L"The 25 largest items on disk:"); m_jkLog->LogMessage(L" Fragments Bytes Clusters Name"); for (i = 0; i < LastLargest; i++) { if (LargestItems[i]->LongPath == NULL) { m_jkLog->LogMessage(L" %9u %11I64u %9I64u [at cluster %I64u]",m_jkLib->FragmentCount(LargestItems[i]), LargestItems[i]->Bytes,LargestItems[i]->Clusters,m_jkLib->GetItemLcn(LargestItems[i])); } else { m_jkLog->LogMessage(L" %9u %11I64u %9I64u %s",m_jkLib->FragmentCount(LargestItems[i]), LargestItems[i]->Bytes,LargestItems[i]->Clusters,LargestItems[i]->LongPath); } } } } } void JKDefragGui::PaintImage(HDC hdc) { Graphics *graphics = Graphics::FromImage(m_bmp); double Done; Rect windowSize = m_clientWindowSize; Rect drawArea; float squareSizeUnit = (float)(1 / (float)m_squareSize); /* Reset the display idle timer (screen saver) and system idle timer (power saver). */ SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED); if (ProgressTodo > 0) { Done = (double)((double)ProgressDone / (double)ProgressTodo); if (Done > 1) Done = 1; swprintf_s(Messages[2],50000,L"%.4f%%",100 * Done); } Color backColor1; backColor1.SetFromCOLORREF(RGB(0, 0, 255)); Color backColor2; backColor2.SetFromCOLORREF(RGB(255, 0, 0)); LinearGradientBrush bgBrush(windowSize,Color::DarkBlue,Color::LightBlue,LinearGradientModeForwardDiagonal); drawArea = windowSize; drawArea.Height = m_topHeight + 1; Color busyColor; busyColor.SetFromCOLORREF(Colors[JKDefragStruct::COLORBUSY]); SolidBrush busyBrush(busyColor); /* graphics->FillRectangle(&busyBrush, drawArea); */ graphics->FillRectangle(&bgBrush, drawArea); SolidBrush brush(Color::White); FontFamily fontFamily(L"Tahoma"); Font font(&fontFamily,12,FontStyleRegular, UnitPixel); WCHAR *text; PointF pointF(2.0f, 0.0f); text = Messages[0]; graphics->DrawString(text, -1, &font, pointF, &brush); pointF = PointF(40.0f, 0.0f); text = Messages[1]; graphics->DrawString(text, -1, &font, pointF, &brush); pointF = PointF(200.0f, 0.0f); text = Messages[2]; graphics->DrawString(text, -1, &font, pointF, &brush); pointF = PointF(280.0f, 0.0f); text = Messages[3]; graphics->DrawString(text, -1, &font, pointF, &brush); pointF = PointF(2.0f, 17.0f); text = Messages[4]; graphics->DrawString(text, -1, &font, pointF, &brush); if (m_debugLevel > 1) { pointF = PointF(2.0f, 33.0f); text = Messages[5]; graphics->DrawString(text, -1, &font, pointF, &brush); } int xx1 = m_realOffsetX - 1; int yy1 = m_realOffsetY + m_topHeight - 1; int xx2 = xx1 + m_numDiskSquaresX * m_squareSize + 1; int yy2 = yy1 + m_numDiskSquaresY * m_squareSize + 1; /* Color bottomPartColor; bottomPartColor.SetFromCOLORREF(Colors[JKDefragStruct::COLORBUSY]); SolidBrush bottomPartBrush(bottomPartColor); */ drawArea = Rect(0, m_topHeight + 1, m_clientWindowSize.Width, yy1 - m_topHeight - 2); /* graphics->FillRectangle(&bottomPartBrush, drawArea); */ graphics->FillRectangle(&bgBrush, drawArea); drawArea = Rect(0, yy2 + 2, m_clientWindowSize.Width, m_clientWindowSize.Height - yy2 - 2); /* graphics->FillRectangle(&bottomPartBrush, drawArea); */ graphics->FillRectangle(&bgBrush, drawArea); drawArea = Rect(0, yy1 - 1, xx1 - 1, yy2 - yy1 + 3); /* graphics->FillRectangle(&bottomPartBrush, drawArea); */ graphics->FillRectangle(&bgBrush, drawArea); drawArea = Rect(xx2, yy1 - 1, m_clientWindowSize.Width - xx2, yy2 - yy1 + 3); /* graphics->FillRectangle(&bottomPartBrush, drawArea); */ graphics->FillRectangle(&bgBrush, drawArea); Pen pen1(Color(0,0,0)); Pen pen2(Color(255,255,255)); graphics->DrawLine(&pen1, xx1, yy2, xx1, yy1); graphics->DrawLine(&pen1, xx1, yy1, xx2, yy1); graphics->DrawLine(&pen1, xx2, yy1, xx2, yy2); graphics->DrawLine(&pen1, xx2, yy2, xx1, yy2); graphics->DrawLine(&pen2, xx1 - 1, yy2 + 1, xx1 - 1, yy1 - 1); graphics->DrawLine(&pen2, xx1 - 1, yy1 - 1, xx2 + 1, yy1 - 1); graphics->DrawLine(&pen2, xx2 + 1, yy1 - 1, xx2 + 1, yy2 + 1); graphics->DrawLine(&pen2, xx2 + 1, yy2 + 1, xx1 - 1, yy2 + 1); COLORREF colEmpty = Colors[JKDefragStruct::COLOREMPTY]; Color colorEmpty; colorEmpty.SetFromCOLORREF(colEmpty); Pen pen(Color(210,210,210)); Pen penEmpty(colorEmpty); for (int jj = 0; jj < m_numDiskSquares; jj++) { if (m_clusterSquares[jj].dirty == false) { continue; } m_clusterSquares[jj].dirty = false; int x1 = jj % m_numDiskSquaresX; int y1 = jj / m_numDiskSquaresX; int xx1 = m_realOffsetX + x1 * m_squareSize; int yy1 = m_realOffsetY + y1 * m_squareSize + m_topHeight; byte clusterEmpty = (m_clusterSquares[jj].color & (1 << 7)) >> 7; byte clusterAllocated = (m_clusterSquares[jj].color & (1 << 6)) >> 6; byte clusterUnfragmented = (m_clusterSquares[jj].color & (1 << 5)) >> 5; byte clusterUnmovable = (m_clusterSquares[jj].color & (1 << 4)) >> 4; byte clusterFragmented = (m_clusterSquares[jj].color & (1 << 3)) >> 3; byte clusterBusy = (m_clusterSquares[jj].color & (1 << 2)) >> 2; byte clusterMft = (m_clusterSquares[jj].color & (1 << 1)) >> 1; byte clusterSpacehog = (m_clusterSquares[jj].color & 1); COLORREF col = Colors[JKDefragStruct::COLOREMPTY]; int emptyCluster = true; if (clusterBusy == 1) { col = Colors[JKDefragStruct::COLORBUSY]; emptyCluster = false; } else if (clusterUnmovable == 1) { col = Colors[JKDefragStruct::COLORUNMOVABLE]; emptyCluster = false; } else if (clusterFragmented == 1) { col = Colors[JKDefragStruct::COLORFRAGMENTED]; emptyCluster = false; } else if (clusterMft == 1) { col = Colors[JKDefragStruct::COLORMFT]; emptyCluster = false; } else if (clusterUnfragmented == 1) { col = Colors[JKDefragStruct::COLORUNFRAGMENTED]; emptyCluster = false; } else if (clusterSpacehog == 1) { col = Colors[JKDefragStruct::COLORSPACEHOG]; emptyCluster = false; } Color C1; Color C2; C1.SetFromCOLORREF(col); int RR = GetRValue(col) + 200; RR = (RR > 255) ? 255 : RR; int GG = GetGValue(col) + 200; GG = (GG > 255) ? 255 : GG; int BB = GetBValue(col) + 100; BB = (BB > 255) ? 255 : BB; C2.SetFromCOLORREF(RGB((byte)RR, (byte)GG, (byte)BB)); if (emptyCluster) { Rect drawArea2(xx1, yy1, m_squareSize - 0, m_squareSize - 0); LinearGradientBrush BB2(drawArea2,C1,C2,LinearGradientModeVertical); graphics->FillRectangle(&BB2, drawArea2); int lineX1 = drawArea2.X; int lineY1 = drawArea2.Y; int lineX2 = drawArea2.X + m_squareSize - 1; int lineY2 = drawArea2.Y; int lineX3 = drawArea2.X; int lineY3 = drawArea2.Y + m_squareSize - 1; int lineX4 = drawArea2.X + m_squareSize - 1; int lineY4 = drawArea2.Y + m_squareSize - 1; graphics->DrawLine(&penEmpty, lineX1, lineY1, lineX2, lineY2); graphics->DrawLine(&pen, lineX3, lineY3, lineX4, lineY4); } else { Rect drawArea2(xx1, yy1, m_squareSize - 0, m_squareSize - 0); LinearGradientBrush BB1(drawArea2,C2,C1,LinearGradientModeForwardDiagonal); graphics->FillRectangle(&BB1, drawArea2); int lineX1 = drawArea2.X; int lineY1 = drawArea2.Y + m_squareSize - 1; int lineX2 = drawArea2.X + m_squareSize - 1; int lineY2 = drawArea2.Y; int lineX3 = drawArea2.X + m_squareSize - 1; int lineY3 = drawArea2.Y + m_squareSize - 1; graphics->DrawLine(&pen, lineX1, lineY1, lineX3, lineY3); graphics->DrawLine(&pen, lineX2, lineY2, lineX3, lineY3); } } delete graphics; } void JKDefragGui::OnPaint(HDC hdc) { /* Bitmap bmp(m_clientWindowSize.Width, m_clientWindowSize.Height); Graphics *graphics2 = Graphics::FromImage(&bmp); */ Graphics graphics(hdc); /* graphics2->DrawImage(m_bmp,0,0); */ /* Color busyColor(128,128,128,128); SolidBrush busyBrush(busyColor); Rect rr = Rect(100, 100, 400, 100); graphics2->FillRectangle(&busyBrush, rr); SolidBrush brush(Color::White); FontFamily fontFamily(L"Tahoma"); Font font(&fontFamily,12,FontStyleRegular, UnitPixel); PointF pointF(132.0f, 120.0f); WCHAR *text; text = Messages[2]; graphics2->DrawString(text, -1, &font, pointF, &brush); */ graphics.DrawImage(m_bmp,0,0); /* delete graphics2; */ return; } /* Message handler. */ LRESULT CALLBACK JKDefragGui::ProcessMessagefn(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_TIMER: /* if (wParam == 333) { PAINTSTRUCT ps; WaitForSingleObject(m_jkDefragGui->m_displayMutex,100); m_jkDefragGui->m_displayMutex = CreateMutex(NULL,FALSE,"JKDefrag"); m_jkDefragGui->m_hDC = BeginPaint(hWnd, &ps); m_jkDefragGui->setDisplayData(m_jkDefragGui->m_hDC); m_jkDefragGui->FillSquares( 0, m_jkDefragGui->m_numDiskSquares); m_jkDefragGui->PaintImage(m_jkDefragGui->m_hDC); EndPaint(hWnd, &ps); ReleaseMutex(m_jkDefragGui->m_displayMutex); KillTimer(m_jkDefragGui->m_hWnd, m_jkDefragGui->m_sizeTimer); } */ InvalidateRect(hWnd,NULL,FALSE); return 0; case WM_PAINT: { /* Grab the display mutex, to make sure that we are the only thread changing the window. */ WaitForSingleObject(m_jkDefragGui->m_displayMutex,100); m_jkDefragGui->m_displayMutex = CreateMutex(NULL,FALSE,"JKDefrag"); PAINTSTRUCT ps; m_jkDefragGui->m_hDC = BeginPaint(hWnd, &ps); m_jkDefragGui->OnPaint(m_jkDefragGui->m_hDC); EndPaint(hWnd, &ps); ReleaseMutex(m_jkDefragGui->m_displayMutex); } return 0; case WM_ERASEBKGND: { // m_jkDefragGui->RedrawScreen = 0; InvalidateRect(m_jkDefragGui->m_hWnd,NULL,FALSE); } return 0; /* case WM_WINDOWPOSCHANGED: { m_jkDefragGui->RedrawScreen = 0; InvalidateRect(m_jkDefragGui->m_hWnd,NULL,FALSE); } return 0; */ case WM_SIZE: { /* m_jkDefragGui->m_sizeTimer = SetTimer(m_jkDefragGui->m_hWnd,333,500,NULL); */ PAINTSTRUCT ps; WaitForSingleObject(m_jkDefragGui->m_displayMutex,100); m_jkDefragGui->m_displayMutex = CreateMutex(NULL,FALSE,"JKDefrag"); m_jkDefragGui->m_hDC = BeginPaint(hWnd, &ps); m_jkDefragGui->setDisplayData(m_jkDefragGui->m_hDC); m_jkDefragGui->FillSquares( 0, m_jkDefragGui->m_numDiskSquares); m_jkDefragGui->PaintImage(m_jkDefragGui->m_hDC); EndPaint(hWnd, &ps); ReleaseMutex(m_jkDefragGui->m_displayMutex); } return 0; } return(DefWindowProc(hWnd,Message,wParam,lParam)); } void JKDefragGui::FillSquares( int clusterStartSquareNum, int clusterEndSquareNum ) { float clusterPerSquare = (float)(m_numClusters / m_numDiskSquares); for(int ii = clusterStartSquareNum; ii <= clusterEndSquareNum; ii++) { byte currentColor = JKDefragStruct::COLOREMPTY; byte clusterEmpty = 0; byte clusterAllocated = 0; byte clusterUnfragmented = 0; byte clusterUnmovable= 0; byte clusterFragmented = 0; byte clusterBusy = 0; byte clusterMft = 0; byte clusterSpacehog = 0; for(int kk = (int)(ii * clusterPerSquare); kk < m_numClusters && kk < (int)((ii + 1) * clusterPerSquare); kk++) { switch (clusterInfo[kk]) { case JKDefragStruct::COLOREMPTY: clusterEmpty = 1; break; case JKDefragStruct::COLORALLOCATED: clusterAllocated = 1; break; case JKDefragStruct::COLORUNFRAGMENTED: clusterUnfragmented = 1; break; case JKDefragStruct::COLORUNMOVABLE: clusterUnmovable = 1; break; case JKDefragStruct::COLORFRAGMENTED: clusterFragmented = 1; break; case JKDefragStruct::COLORBUSY: clusterBusy = 1; break; case JKDefragStruct::COLORMFT: clusterMft = 1; break; case JKDefragStruct::COLORSPACEHOG: clusterSpacehog = 1; break; } } if (ii < m_numDiskSquares) { m_clusterSquares[ii].dirty = true; m_clusterSquares[ii].color = //maxColor; clusterEmpty << 7 | clusterAllocated << 6 | clusterUnfragmented << 5 | clusterUnmovable << 4 | clusterFragmented << 3 | clusterBusy << 2 | clusterMft << 1 | clusterSpacehog; } } } /* Show a map on the screen of all the clusters on disk. The map shows which clusters are free and which are in use. The Data->RedrawScreen flag controls redrawing of the screen. It is set to "2" (busy) when the subroutine starts. If another thread changes it to "1" (request) while the subroutine is busy then it will immediately exit without completing the redraw. When redrawing is completely finished the flag is set to "0" (no). */ void JKDefragGui::ShowDiskmap(struct DefragDataStruct *Data) { struct ItemStruct *Item; STARTING_LCN_INPUT_BUFFER BitmapParam; struct { ULONG64 StartingLcn; ULONG64 BitmapSize; BYTE Buffer[65536]; /* Most efficient if binary multiple. */ } BitmapData; ULONG64 Lcn; ULONG64 ClusterStart; DWORD ErrorCode; int Index; int IndexMax; BYTE Mask; int InUse; int PrevInUse; DWORD w; int i; // *Data->RedrawScreen = 2; /* Set the flag to "busy". */ /* Exit if the library is not processing a disk yet. */ if (Data->Disk.VolumeHandle == NULL) { // *Data->RedrawScreen = 0; /* Set the flag to "no". */ return; } /* Clear screen. */ ClearScreen(NULL); /* Show the map of all the clusters in use. */ Lcn = 0; ClusterStart = 0; PrevInUse = 1; do { if (*Data->Running != RUNNING) break; // if (*Data->RedrawScreen != 2) break; if (Data->Disk.VolumeHandle == INVALID_HANDLE_VALUE) break; /* Fetch a block of cluster data. */ BitmapParam.StartingLcn.QuadPart = Lcn; ErrorCode = DeviceIoControl(Data->Disk.VolumeHandle,FSCTL_GET_VOLUME_BITMAP, &BitmapParam,sizeof(BitmapParam),&BitmapData,sizeof(BitmapData),&w,NULL); if (ErrorCode != 0) { ErrorCode = NO_ERROR; } else { ErrorCode = GetLastError(); } if ((ErrorCode != NO_ERROR) && (ErrorCode != ERROR_MORE_DATA)) break; /* Sanity check. */ if (Lcn >= BitmapData.StartingLcn + BitmapData.BitmapSize) break; /* Analyze the clusterdata. We resume where the previous block left off. */ Lcn = BitmapData.StartingLcn; Index = 0; Mask = 1; IndexMax = sizeof(BitmapData.Buffer); if (BitmapData.BitmapSize / 8 < IndexMax) IndexMax = (int)(BitmapData.BitmapSize / 8); while ((Index < IndexMax) && (*Data->Running == RUNNING)) { InUse = (BitmapData.Buffer[Index] & Mask); /* If at the beginning of the disk then copy the InUse value as our starting value. */ if (Lcn == 0) PrevInUse = InUse; /* At the beginning and end of an Exclude draw the cluster. */ if ((Lcn == Data->MftExcludes[0].Start) || (Lcn == Data->MftExcludes[0].End) || (Lcn == Data->MftExcludes[1].Start) || (Lcn == Data->MftExcludes[1].End) || (Lcn == Data->MftExcludes[2].Start) || (Lcn == Data->MftExcludes[2].End)) { if ((Lcn == Data->MftExcludes[0].End) || (Lcn == Data->MftExcludes[1].End) || (Lcn == Data->MftExcludes[2].End)) { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLORUNMOVABLE); } else if (PrevInUse == 0) { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLOREMPTY); } else { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLORALLOCATED); } InUse = 1; PrevInUse = 1; ClusterStart = Lcn; } if ((PrevInUse == 0) && (InUse != 0)) /* Free */ { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLOREMPTY); ClusterStart = Lcn; } if ((PrevInUse != 0) && (InUse == 0)) /* In use */ { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLORALLOCATED); ClusterStart = Lcn; } PrevInUse = InUse; if (Mask == 128) { Mask = 1; Index = Index + 1; } else { Mask = Mask << 1; } Lcn = Lcn + 1; } } while ((ErrorCode == ERROR_MORE_DATA) && (Lcn < BitmapData.StartingLcn + BitmapData.BitmapSize)); if ((Lcn > 0)/* && (*Data->RedrawScreen == 2)*/) { if (PrevInUse == 0) /* Free */ { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLOREMPTY); } if (PrevInUse != 0) /* In use */ { DrawCluster(Data,ClusterStart,Lcn,JKDefragStruct::COLORALLOCATED); } } /* Show the MFT zones. */ for (i = 0; i < 3; i++) { // if (*Data->RedrawScreen != 2) break; if (Data->MftExcludes[i].Start <= 0) continue; DrawCluster(Data,Data->MftExcludes[i].Start, Data->MftExcludes[i].End, JKDefragStruct::COLORMFT); } /* Colorize all the files on the screen. Note: the "$BadClus" file on NTFS disks maps the entire disk, so we have to ignore it. */ for (Item = m_jkLib->TreeSmallest(Data->ItemTree); Item != NULL; Item = m_jkLib->TreeNext(Item)) { if (*Data->Running != RUNNING) break; // if (*Data->RedrawScreen != 2) break; if ((Item->LongFilename != NULL) && ((_wcsicmp(Item->LongFilename,L"$BadClus") == 0) || (_wcsicmp(Item->LongFilename,L"$BadClus:$Bad:$DATA") == 0))) continue; m_jkLib->ColorizeItem(Data,Item,0,0,NO); } /* Set the flag to "no". */ // if (*Data->RedrawScreen == 2) *Data->RedrawScreen = 0; }
26.616758
128
0.645843
5a560a47e4c98284c4949d131cbe6cd6b3f1822b
2,056
hpp
C++
types/containers/ColumnVectorUtil.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
types/containers/ColumnVectorUtil.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
types/containers/ColumnVectorUtil.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * 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. **/ #ifndef QUICKSTEP_TYPES_CONTAINERS_COLUMN_VECTOR_UTIL_HPP_ #define QUICKSTEP_TYPES_CONTAINERS_COLUMN_VECTOR_UTIL_HPP_ #include "types/containers/ColumnVector.hpp" namespace quickstep { /** \addtogroup Types * @{ */ /** * @brief Invoke a generic functor (or lambda) on a ColumnVector that is * downcast to its actual concrete type. * * @param column_vector A ColumnVector that will be downcast to its concrete * type so that inline methods can be used. * @param functor A generic functor or lambda that has a templated call * operator taking a single argument. The call operator will be invoked * with the downcast column_vector as its argument. * @return The return value of functor's call operator applied to the downcast * column_vector. **/ template <typename FunctorT> auto InvokeOnColumnVector(const ColumnVector &column_vector, const FunctorT &functor) { if (column_vector.isNative()) { return functor(static_cast<const NativeColumnVector&>(column_vector)); } else { return functor(static_cast<const IndirectColumnVector&>(column_vector)); } } /** @} */ } // namespace quickstep #endif // QUICKSTEP_TYPES_CONTAINERS_COLUMN_VECTOR_UTIL_HPP_
35.448276
78
0.738327
5a6056593fed418eec1850f6ec3aad256a72945f
9,432
cpp
C++
KeePass.1.39.a/LibraryMB/Date.cpp
rrvt/KeePassLastPass
217b627d906cf0af21ac69643a2d2e24e88f934b
[ "MIT" ]
null
null
null
KeePass.1.39.a/LibraryMB/Date.cpp
rrvt/KeePassLastPass
217b627d906cf0af21ac69643a2d2e24e88f934b
[ "MIT" ]
1
2020-05-01T00:37:31.000Z
2020-05-01T00:37:31.000Z
KeePass.1.39.a/LibraryMB/Date.cpp
rrvt/KeePassLastPass
217b627d906cf0af21ac69643a2d2e24e88f934b
[ "MIT" ]
1
2020-02-25T09:11:37.000Z
2020-02-25T09:11:37.000Z
// Date & Time using CTime #include "stdafx.h" #include "Date.h" #include "MessageBox.h" #include "StringInput.h" // Helper functions for dealing with Edit boxes static bool vrfyMnth( int cnt, TCchar ch, int& v); static bool vrfyDay( int cnt, TCchar ch, int& v); static bool vrfyYr( int cnt, TCchar ch, int& v); static void replDtSel(int i, TCchar ch, CEdit& ctrl); static bool vrfyHr( int cnt, TCchar ch, int& v); static bool vrfyMin( int cnt, TCchar ch, int& v); static void replTmSel(int i, TCchar ch, CEdit& ctrl); const int Date::MinDate = 30000; typedef struct tm Tm; const double Date::SecondsPerDay = 86400; static TCchar* msg = _T("Date format accepted:\n" "mm/dd - defaults to current year\n" "mm/dd/yr\n" "where:\n" " mm is 1 - 12\n" " dd is 1 - 31\n" " yr is 0 - 69 translates to 2000 - 2069\n" " 70 - 99 translates to 1970 - 1999\n" " >100 - exact year\n" " Date only good from 1/1/1970 to year 3000\n" "At least one slash ('/') must be present to accept a date.\n" "Time Formats include the following where\n" " H is either one or two hour digits:\n" " Hmm -- Hours and minutes\n" " hh:mm:ss -- Hour, minutes and seconds\n" " <time>a -- am\n" " <time>p -- pm\n" " hhmm -- Hour and minutes in the 24-hour system\n" "Notes:\n" " ':' -- may separate hours and minutes in any of the above except the latter\n" " H > 12 -- 24 hour clock always interpreted correctly"); typedef LexT<StringInput, LexTOut, false, false, false> Lex; static int utcOffset = 0; Date::Date() : dt(0) { Tm utcTime; Tm lclTime; int noDays; dt.GetGmtTm(&utcTime); dt.GetLocalTm(&lclTime); noDays = lclTime.tm_yday ? 365 - lclTime.tm_yday : 0; utcOffset = ((noDays * 24 - lclTime.tm_hour) * 60 + lclTime.tm_min) * 60 + lclTime.tm_sec; } Date Date::operator= (String& s) { Lex lex; __time64_t tm = 0; int nDigits; int mm = 0; // Date may not be ealier than 1/1/1970 at UTC int dd = 0; int yr = 0; int hr = 0; // Time w/o date based on 1/1/70 date. Sorry no zero date! int mn = 0; int ss = 0; Token* t; Token* t1; Tm today; getToday(); dt.GetLocalTm(&today); lex.initialize(); lex.input.set(s); lex.get_token(); t = lex.token; t1 = lex.token1; if (t1->code == SlashToken) { if (t->code == IntLitToken) { mm = t->value.integer; if (mm < 1 || 12 < mm) {messageBox(msg); goto finDate;} lex.accept_two_tokens(); if (lex.get_token() == IntLitToken) { t = lex.token; t1 = lex.token1; dd = t->value.integer; if (dd < 1 || 31 < dd) {messageBox(msg); goto finDate;} lex.accept_token(); if (t1->code == SlashToken) { lex.accept_two_tokens(); if (lex.get_token() == IntLitToken) { yr = lex.token->value.integer; if ( 0 <= yr && yr < 70) yr += 2000; else if (70 <= yr && yr < 100) yr += 1900; lex.accept_token(); } } else yr = today.tm_year + 1900; } } } if (lex.get_token() == SlashToken) lex.accept_token(); if (lex.get_token() == EolToken || lex.token->code == EOFToken) goto finDate; if (lex.get_token() == IntLitToken) { t = lex.token; hr = t->value.integer; nDigits = t->noDigits; if (hr > 60 || nDigits > 2) {mn = hr % 100; hr = hr / 100;} if (hr < 0 || 24 <= hr || mn < 0 || 60 <= mn) {messageBox(msg); goto finDate;} if (nDigits == 4) goto finDate; lex.accept_token(); if (lex.get_token() == ColonToken) { lex.accept_token(); if (lex.get_token() == IntLitToken) { mn = lex.token->value.integer; lex.accept_token(); if (mn < 0 || 60 <= mn) {messageBox(msg); goto finDate;} lex.accept_token(); if (lex.get_token() == ColonToken) { lex.accept_token(); if (lex.get_token() == IntLitToken) {ss = lex.token->value.integer;} lex.accept_token(); if (ss < 0 || 60 <= ss) {messageBox(msg); goto finDate;} } } } if (lex.get_token() == IdentToken) { if (!amPM(hr, lex.token->name)) messageBox(msg); goto finDate; } if (lex.get_token() == EolToken || lex.token->code == EOFToken) goto finDate; } messageBox(msg); finDate: if (!yr) {int t = (hr * 60 + mn) * 60 + ss + utcOffset; CTime x((__time64_t) t); dt = x;} else {CTime x(yr, mm, dd, hr, mn, ss); dt = x; } return *this; } bool Date::amPM(int& h, String& txt) { if ((txt == _T("a") || txt == _T("A")) && h <= 12) return true; if ((txt == _T("p") || txt == _T("P")) && h <= 12) {h += 12; return true;} return false; } static const double secPerDay = 86400; // 60 * 60 * 24 Date::operator variant_t() { double t = double(dt.GetTime()); variant_t v; v.date = t / secPerDay; v.vt = VT_DATE; return v; } String Date::getTime() {CString s; s = dt.Format(_T("%X")); return s;} String Date::getHHMM() {CString s; s = dt.Format(_T("%R")); return s;} String Date::getHHMMSS() {CString s; s = dt.Format(_T("%T")); return s;} String Date::getDate() {CString s = dt.Format(_T("%x")); return s;} String Date::dayOfWeek() {CString s = dt.Format("%a"); return s;} static bool updateDate = false; void Date::onChangeDate(CEdit& ctrl) { CString date; int i; int n; String s; int count = 0; int slCnt = 0; bool legal; int mon = 0; int day = 0; int yr = 0; if (!updateDate) { // To avoid infinite recursion updateDate = true; ctrl.GetWindowText(date); s = date; for (i = 0, n = s.length(); i < n; i++) { Tchar ch = s[i]; legal = false; if (_T('0') <= ch && ch <= _T('9')) { legal = true; if (count || ch != _T('0')) { if (slCnt == 0 && !vrfyMnth(count, ch, mon)) {replDtSel(i, 0, ctrl); break;} if (slCnt == 1 && !vrfyDay( count, ch, day)) {replDtSel(i, 0, ctrl); break;} if (slCnt == 2 && !vrfyYr( count, ch, yr)) {replDtSel(i, 0, ctrl); break;} } if (count > 1) {replDtSel(i, slCnt < 2 ? ch : 0, ctrl); break;} count++; } if (ch == _T('/')) { if (slCnt >= 2) {replDtSel(i, 0, ctrl); break;} count = 0; slCnt++; legal = true; } if (!legal) {replDtSel(i, 0, ctrl); break;} } updateDate = false; } } bool vrfyMnth(int cnt, TCchar ch, int& v) {v = v * cnt * 10 + ch - _T('0'); return 1 <= v && v <= 12;} bool vrfyDay( int cnt, TCchar ch, int& v) {v = v * cnt * 10 + ch - _T('0'); return 1 <= v && v <= 31;} bool vrfyYr( int cnt, TCchar ch, int& v) {v = v * cnt * 10 + ch - _T('0'); return 0 <= v && v <= 40;} void replDtSel(int i, TCchar ch, CEdit& ctrl) { bool aCh = ch != 0; String s; if (aCh) {s = _T('/'); s += ch;} else {Beep(1500, 120);} ctrl.SetSel(i, i+1); ctrl.ReplaceSel(s); } static bool updateTime = false; void Date::onChangeTime(CEdit& ctrl) { CString time; int i; int n; String s; int count = 0; int clnCnt = 0; bool legal; int hr = 0; int min = 0; if (!updateTime) { // To avoid infinite recursion updateTime = true; ctrl.GetWindowText(time); s = time; for (i = 0, n = s.length(); i < n; i++) { Tchar ch = s[i]; legal = false; if (_T('0') <= ch && ch <= _T('9')) { legal = true; if (count || ch != _T('0')) { if (i > 4) {replTmSel(i, 0, ctrl); break;} if (count > 1) {replTmSel(i, ch, ctrl); clnCnt++; count = 1; break; } if ( !clnCnt && !vrfyHr( count, ch, hr)) {replTmSel(i, 0, ctrl); break;} else if (clnCnt && !vrfyMin(count, ch, min)) {replTmSel(i, 0, ctrl); break;} } count++; } if (ch == _T(':')) { if (clnCnt >= 1) {replTmSel(i, 0, ctrl); break;} count = 0; clnCnt++; legal = true; } if (!legal) {replTmSel(i, 0, ctrl); break;} } updateTime = false; } } bool vrfyHr( int cnt, TCchar ch, int& v) {v = v * cnt * 10 + ch - _T('0'); return v < 24;} bool vrfyMin(int cnt, TCchar ch, int& v) {v = v * cnt * 10 + ch - _T('0'); return v < 60;} void replTmSel(int i, TCchar ch, CEdit& ctrl) { bool aCh = ch != 0; String s; if (aCh) {s = _T(':'); s += ch;} else {Beep(1500, 120);} ctrl.SetSel(i, i+1); ctrl.ReplaceSel(s); } void ToDate::convert() { if (stg.length() < 14) return; year = next(4); month = next(2); day = next(2); hour = next(2); min = next(2); sec = next(2); Date d(year, month, day, hour, min, sec); date = d; } int ToDate::next(int noChar) { String s = stg.substr(pos, noChar); uint x; pos += noChar; return s.stoi(x); }
24.886544
105
0.502969
5a63f54de0d91ae503705aea54597e7b8c540ec2
4,572
cpp
C++
active16/src/libalf/libalf_interfaces/jalf/src/jni_algorithm_kearns_vazirani.cpp
adiojha629/JIRP_LRM
a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3
[ "MIT" ]
2
2021-09-22T13:02:55.000Z
2021-11-08T19:16:55.000Z
active16/src/libalf/libalf_interfaces/jalf/src/jni_algorithm_kearns_vazirani.cpp
adiojha629/JIRP_LRM
a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3
[ "MIT" ]
null
null
null
active16/src/libalf/libalf_interfaces/jalf/src/jni_algorithm_kearns_vazirani.cpp
adiojha629/JIRP_LRM
a06e3725a8f4f406a100d2a4c2c69d4e9450a2d3
[ "MIT" ]
null
null
null
/* $Id: jni_algorithm_angluin.cpp 1081 2009-11-11 16:33:40Z davidpiegdon $ * vim: fdm=marker * * This file is part of libalf. * * libalf 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 3 of the License, or * (at your option) any later version. * * libalf 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 libalf. If not, see <http://www.gnu.org/licenses/>. * * (c) 2010 Lehrstuhl Softwaremodellierung und Verifikation (I2), RWTH Aachen University * and Lehrstuhl Logik und Theorie diskreter Systeme (I7), RWTH Aachen University * Author: Daniel Neider <neider@automata.rwth-aachen.de> * */ #include <iostream> #include <libalf/knowledgebase.h> #include <libalf/learning_algorithm.h> #include <libalf/algorithm_kearns_vazirani.h> #include <jni.h> #include "jni_algorithm_kearns_vazirani.h" using namespace std; using namespace libalf; JNIEXPORT jlong JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_init__JI (JNIEnv *env, jobject obj, jlong knowledgebase_pointer, jint alphabet_size) { // Get the knowledgebase object knowledgebase<bool> *base = (knowledgebase<bool>*) knowledgebase_pointer; /* * Return the new object */ learning_algorithm<bool>* algorithm = new kearns_vazirani<bool>(base, NULL, alphabet_size, true); return ((jlong)algorithm); } JNIEXPORT jlong JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_init__JIJ (JNIEnv *env, jobject obj, jlong knowledgebase_pointer, jint alphabet_size, jlong logger_pointer) { // Get the knowledgebase object knowledgebase<bool> *base = (knowledgebase<bool>*) knowledgebase_pointer; // Get the logger object buffered_logger *logger = (buffered_logger*) logger_pointer; /* * Return the new object */ learning_algorithm<bool>* algorithm = new kearns_vazirani<bool>(base, logger, alphabet_size, true); return ((jlong)algorithm); } JNIEXPORT jlong JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_init__JIZ (JNIEnv *env, jobject obj, jlong knowledgebase_pointer, jint alphabet_size, jboolean use_binary_search) { // Get the knowledgebase object knowledgebase<bool> *base = (knowledgebase<bool>*) knowledgebase_pointer; /* * Return the new object */ learning_algorithm<bool>* algorithm = new kearns_vazirani<bool>(base, NULL, alphabet_size, use_binary_search); return ((jlong)algorithm); } JNIEXPORT jlong JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_init__JIJZ (JNIEnv *env, jobject obj, jlong knowledgebase_pointer, jint alphabet_size, jlong logger_pointer, jboolean use_binary_search) { // Get the knowledgebase object knowledgebase<bool> *base = (knowledgebase<bool>*) knowledgebase_pointer; // Get the logger object buffered_logger *logger = (buffered_logger*) logger_pointer; /* * Return the new object */ learning_algorithm<bool>* algorithm = new kearns_vazirani<bool>(base, logger, alphabet_size, use_binary_search); return ((jlong)algorithm); } JNIEXPORT jint JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_get_1inner_1node_1count (JNIEnv *env, jobject obj, jlong pointer) { // Get the algorithm object kearns_vazirani<bool>* algorithm = (kearns_vazirani<bool>*)pointer; // Forward method call return algorithm->get_inner_node_count(); } JNIEXPORT jint JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_get_1leaf_1node_1count (JNIEnv *env, jobject obj, jlong pointer) { // Get the algorithm object kearns_vazirani<bool>* algorithm = (kearns_vazirani<bool>*)pointer; // Forward method call return algorithm->get_leaf_node_count(); } JNIEXPORT jboolean JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_uses_1binary_1search (JNIEnv *env, jobject obj, jlong pointer) { // Get the algorithm object kearns_vazirani<bool>* algorithm = (kearns_vazirani<bool>*)pointer; // Forward method call return algorithm->uses_binary_search(); } JNIEXPORT void JNICALL Java_de_libalf_jni_JNIAlgorithmKearnsVazirani_set_1binary_1search (JNIEnv *env, jobject obj, jlong pointer, jboolean use_binary_search) { // Get the algorithm object kearns_vazirani<bool>* algorithm = (kearns_vazirani<bool>*)pointer; // Forward method call return algorithm->set_binary_search(use_binary_search); }
38.1
208
0.783902
5a669cb970f23e3dc4e79c2350eaf2177bf271a6
36
cpp
C++
src/lib/universal_include.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
src/lib/universal_include.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
src/lib/universal_include.cpp
abainbridge/trex-warrior
fac95802ce7efd8dc9c50f915ce8d5891f545640
[ "BSD-2-Clause" ]
null
null
null
#include "lib/universal_include.h"
18
35
0.777778
5a6a1c2975c6531dff0687018ae8062dd9ace258
1,354
hpp
C++
include/utility/container/helper/in_place_t.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
2
2017-12-10T10:59:48.000Z
2017-12-13T04:11:14.000Z
include/utility/container/helper/in_place_t.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
include/utility/container/helper/in_place_t.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
#ifndef __UTILITY_CONTAINER_HELPER_IN_PLACE_T__ #define __UTILITY_CONTAINER_HELPER_IN_PLACE_T__ /** * \file ignore_t.hpp * \author Inochi Amaoto * */ #include<utility/config/utility_config.hpp> #include<utility/trait/trait_helper.hpp> namespace utility { namespace container { namespace helper { struct in_place_t { explicit in_place_t() = default;}; __UTILITY_CPP17_INLINE__ constexpr in_place_t in_place{}; template<typename _T> struct in_place_type_t { explicit in_place_type_t() = default;}; #ifndef __UTILITY_NO_CPP14__ template<typename _T> __UTILITY_CPP17_INLINE__ constexpr in_place_type_t<_T> in_place_type{}; #endif // ! __UTILITY_NO_CPP14__ template<size_t _I> struct in_place_index_t { explicit in_place_index_t() = default;}; #ifndef __UTILITY_NO_CPP14__ template<size_t _I> __UTILITY_CPP17_INLINE__ constexpr in_place_index_t<_I> in_place_index{}; #endif // ! __UTILITY_NO_CPP14__ } // helper namespace helper_traits { template<typename _T> struct is_in_place_type: public trait::false_type { }; template<typename _T> struct is_in_place_type<helper::in_place_type_t<_T>>: public trait::true_type { }; } } } #endif // ! __UTILITY_CONTAINER_HELPER_IN_PLACE_T__
21.492063
84
0.70384
5a6bba96e35124ac92ce3b4f4a40e291e65d674f
1,591
cpp
C++
data/train/cpp/469397c48114ed209f7e63666c457ceb0a48a171StreamInterface.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/469397c48114ed209f7e63666c457ceb0a48a171StreamInterface.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/cpp/469397c48114ed209f7e63666c457ceb0a48a171StreamInterface.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
///////////////////////////////////////////////////////////// /** @file StreamInterface.cpp * @ingroup Utils * * @author Luk2010 * @version 0.1A * * @date 04/01/2013 - 23/03/2014 * * Implements the Streams class. * **/ ///////////////////////////////////////////////////////////// #include "StreamInterface.h" namespace APro { CursorStream::CursorStream() { } CursorStream::~CursorStream() { } bool CursorStream::operator bool() const { return !isEOS(); } size_t CursorStream::size() { size_t _p, _ret; _p = tell(); seek(0, CP_END); _ret = tell(); seek(_p, CP_BEGIN); return ret; } InputStream::InputStream() : CursorStream() { } InputStream::~CursorStream() { } InputStream& InputStream::operator >> (String& str) { readWord(str); return *this; } InputStream& InputStream::operator >> (Real& r) { readReal(r); return *this; } InputStream& InputStream::operator >> (int& i) { readInt(i); return *this; } OutputStream::OutputStream() { } OutputStream::~OutputStream() { } OutputStream& OutputStream::operator << (const String& str) { write(str); return *this; } OutputStream& OutputStream::operator << (const Real& r) { write(r); return *this; } OutputStream& OutputStream::operator << (const int& i) { write(i); return *this; } }
15.598039
63
0.478944
5a6d51ec62e418d64eab8cc29602dbba21ee1c56
3,011
cpp
C++
src/PID.cpp
iamsumit16/PID_Controller_Project-9
a71e79eb2bbffb761c757acb9620948ec075e6f6
[ "MIT" ]
null
null
null
src/PID.cpp
iamsumit16/PID_Controller_Project-9
a71e79eb2bbffb761c757acb9620948ec075e6f6
[ "MIT" ]
null
null
null
src/PID.cpp
iamsumit16/PID_Controller_Project-9
a71e79eb2bbffb761c757acb9620948ec075e6f6
[ "MIT" ]
null
null
null
#include "PID.h" using namespace std; /* * TODO: Complete the PID class. */ PID::PID() {} PID::~PID() {} void PID::Init(double Kp, double Ki, double Kd) { // Assign to instance variables this -> Kp = Kp; this -> Ki = Ki; this -> Kd = Kd; // Initialize errors to zero p_error = 0.0; i_error = 0.0; d_error = 0.0; // Twiddle vars initialization tol = 0.005; iter = 0; dp[0] = Kp * 0.1; dp[1] = Ki * 0.1; dp[2] = Kd * 0.1; } void PID::UpdateError(double cte) { // Differential Error d_error = cte - p_error; // Proportional Error p_error = cte; // Integral Error i_error += cte; iter += 1; } double PID::TotalError() { return CalculateTotalError(Kp, Ki, Kd); } double PID::CalculateTotalError(double k_p, double k_i, double k_d){ double steer = - k_p * p_error - k_i * i_error - k_d * d_error; // Keep within the [-1, 1] steer value of the simulator if (steer < -1 ){ steer = -1; } else if( steer > 1 ) { steer = 1; } return steer; } void PID::Twiddle(float tol, double steering_angle){ double best_err = abs(TotalError()); double best_cte = p_error; double rho = p_error / sin(steering_angle); double err; double err_d; double new_cte; p[0] = Kp; p[1] = Ki; p[2] = Kd; // Loop while ((abs(dp[0]) + abs(dp[1]) + abs(dp[2])) > tol){ // For each p for(int i = 0; i < 3; ++i){ p[i] += dp[i]; // Error err = abs(CalculateTotalError(p[0], p[1], p[2])); // Convert to Degrees err_d = err * (180 / M_PI); // Assign CTE new_cte = best_cte + (rho * sin(err_d)); if((abs(new_cte) < abs(best_cte)) && (abs(err) < abs(best_err))){ best_err = err; best_cte = new_cte; dp[i] *= 1.1; } else{ // Search in the negative (other) direction p[i] -= 2 * dp[i]; err = abs(CalculateTotalError(p[0], p[1], p[2])); err_d = err * (180 / M_PI); new_cte = best_cte + (rho * sin(err_d)); if ((abs(new_cte) < abs(best_cte)) && (abs(err) < abs(best_err))){ best_cte = new_cte; best_err = err; dp[i] *= 1.1; } else { p[i] += dp[i]; dp[i] *= 0.9; } } } } // Dealing with the - coeff for (int z = 0; z < 3; ++z) { if (p[z] < 0.0) { p[z] = abs(p[z]); } } // Reinitialize Kp = p[0]; Ki = p[1]; Kd = p[2]; dp[0] = Kp * 0.1; dp[1] = Ki * 0.1; dp[2] = Kd * 0.1; }
23.341085
83
0.42544
5a6dac2ed132145899c82aff673bf5521101c34d
2,484
cpp
C++
src/event.cpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
src/event.cpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
src/event.cpp
jaykang920/x2boost
2a1160b7f840b7ceea6b18e61603ab4e0ce7a94c
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2017 Jae-jun Kang // See the file LICENSE for details. #include "x2boost/event.hpp" #include <boost/functional/hash.hpp> #include <boost/thread/once.hpp> #include "x2boost/deserializer.hpp" #include "x2boost/event_factory.hpp" #include "x2boost/serializer.hpp" using namespace x2boost; namespace { event::tag event_tag; boost::once_flag event_once = BOOST_ONCE_INIT; void event_init() { event_tag.set(NULL, 1, 0); } struct static_event_initializer { static_event_initializer() { event_factory::enroll(0, event::_new); } }; static_event_initializer static_event_init; } bool event::_equals(const cell& other) const { if (!cell::_equals(other)) { return false; } const event& o = static_cast<const event&>(other); if (_handle_ != o._handle_) { return false; } return true; } bool event::_equivalent(const cell& other) const { if (!cell::_equivalent(other)) { return false; } const event& o = static_cast<const event&>(other); if (fingerprint_[_tag()->offset() + 0]) { if (_handle_ != o._handle_) { return false; } } return true; } std::size_t event::_hash_code() const { return _hash_code(fingerprint_, _type_id()); } std::size_t event::_hash_code(const fingerprint& fp) const { std::size_t value = cell::_hash_code(fp); if (fp[_tag()->offset() + 0]) { boost::hash_combine(value, _handle_); } return value; } std::size_t event::_hash_code(const fingerprint& fp, boost::int32_t type_id) const { std::size_t value = 17; boost::hash_combine(value, _hash_code(fp)); boost::hash_combine(value, type_id); return value; } const event::tag* event::_tag() { boost::call_once(event_init, event_once); return &event_tag; } const cell::tag* event::_type_tag() const { return _tag(); } void event::_describe(std::ostringstream& /*oss*/) const { return; } void event::_deserialize(deserializer& deserializer) { cell::_deserialize(deserializer); } int event::_get_encoded_length() const { int length = serializer::get_encoded_length((boost::int32_t)_type_id()); length += cell::_get_encoded_length(); return length; } void event::_serialize(serializer& serializer) const { serializer.write((boost::int32_t)_type_id()); cell::_serialize(serializer); } // EOF event.cpp
20.032258
82
0.646135
5a6f5388a2fccc8bc1c1b26effb8ed7388b6643e
8,267
cpp
C++
Source/Platform/String.cpp
Hork-Engine/Hork-Source
1670e7b04dcfd28d6efdcae06a30c00e303be28f
[ "MIT" ]
17
2022-01-31T07:43:06.000Z
2022-03-29T10:30:25.000Z
Source/Platform/String.cpp
Hork-Engine/Hork-Source
1670e7b04dcfd28d6efdcae06a30c00e303be28f
[ "MIT" ]
2
2022-02-06T14:46:40.000Z
2022-02-08T09:46:54.000Z
Source/Platform/String.cpp
Hork-Engine/Hork-Source
1670e7b04dcfd28d6efdcae06a30c00e303be28f
[ "MIT" ]
1
2022-02-15T08:23:23.000Z
2022-02-15T08:23:23.000Z
/* Hork Engine Source Code MIT License Copyright (C) 2017-2022 Alexander Samusev. This file is part of the Hork Engine Source Code. 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 <Platform/String.h> #include <Platform/Memory/Memory.h> #define STB_SPRINTF_IMPLEMENTATION #define STB_SPRINTF_STATIC #include "stb_sprintf.h" namespace Platform { int Stricmp(const char* _S1, const char* _S2) { char c1, c2; HK_ASSERT(_S1 && _S2); do { c1 = *_S1++; c2 = *_S2++; if (c1 != c2) { if (c1 >= 'a' && c1 <= 'z') { c1 -= ('a' - 'A'); } if (c2 >= 'a' && c2 <= 'z') { c2 -= ('a' - 'A'); } if (c1 != c2) { return (int)((uint8_t)c1 - (uint8_t)c2); } } } while (c1); return 0; } int StricmpN(const char* _S1, const char* _S2, int _Num) { char c1, c2; HK_ASSERT(_S1 && _S2 && _Num >= 0); do { if (!_Num--) { return 0; } c1 = *_S1++; c2 = *_S2++; if (c1 != c2) { if (c1 >= 'a' && c1 <= 'z') { c1 -= ('a' - 'A'); } if (c2 >= 'a' && c2 <= 'z') { c2 -= ('a' - 'A'); } if (c1 != c2) { return (int)((uint8_t)c1 - (uint8_t)c2); } } } while (c1); return 0; } int Strcmp(const char* _S1, const char* _S2) { HK_ASSERT(_S1 && _S2); while (*_S1 == *_S2) { if (!*_S1) { return 0; } _S1++; _S2++; } return (int)((uint8_t)*_S1 - (uint8_t)*_S2); } int StrcmpN(const char* _S1, const char* _S2, int _Num) { char c1, c2; HK_ASSERT(_S1 && _S2 && _Num >= 0); do { if (!_Num--) { return 0; } c1 = *_S1++; c2 = *_S2++; if (c1 != c2) { return (int)((uint8_t)c1 - (uint8_t)c2); } } while (c1); return 0; } int Sprintf(char* _Buffer, size_t _Size, const char* _Format, ...) { int result; va_list va; va_start(va, _Format); result = stbsp_vsnprintf(_Buffer, _Size, _Format, va); va_end(va); return result; } int VSprintf(char* _Buffer, size_t _Size, const char* _Format, va_list _VaList) { HK_ASSERT(_Buffer && _Format); return stbsp_vsnprintf(_Buffer, _Size, _Format, _VaList); } char* Fmt(const char* _Format, ...) { HK_ASSERT(_Format); thread_local static char String[4][16384]; thread_local static int Index = 0; va_list VaList; Index = (Index + 1) & 3; // for nested calls va_start(VaList, _Format); stbsp_vsnprintf(String[Index], sizeof(String[0]), _Format, VaList); va_end(VaList); return String[Index]; } void Strcat(char* _Dest, size_t _Size, const char* _Src) { if (!_Dest || !_Src) { return; } //#ifdef HK_COMPILER_MSVC // strcat_s( _Dest, _Size, _Src ); //#else size_t destLength = Strlen(_Dest); if (destLength >= _Size) { return; } Strcpy(_Dest + destLength, _Size - destLength, _Src); //#endif } void StrcatN(char* _Dest, size_t _Size, const char* _Src, int _Num) { if (!_Dest || !_Src) { return; } size_t destLength = Strlen(_Dest); if (destLength >= _Size) { return; } int len = Strlen(_Src); if (len > _Num) { len = _Num; } StrcpyN(_Dest + destLength, _Size - destLength, _Src, _Num); } void Strcpy(char* _Dest, size_t _Size, const char* _Src) { if (!_Dest) { return; } if (!_Src) { _Src = ""; } //#ifdef HK_COMPILER_MSVC // strcpy_s( _Dest, _Size, _Src ); //#else if (_Size > 0) { while (*_Src && --_Size != 0) { *_Dest++ = *_Src++; } *_Dest = 0; } //#endif } void StrcpyN(char* _Dest, size_t _Size, const char* _Src, int _Num) { if (!_Dest) { return; } if (!_Src) { _Src = ""; } //#ifdef HK_COMPILER_MSVC // strncpy_s( _Dest, _Size, _Src, _Num ); //#else if (_Size > 0 && _Num > 0) { while (*_Src && --_Size != 0 && --_Num != -1) { *_Dest++ = *_Src++; } *_Dest = 0; } //#endif } char* ToLower(char* _Str) { char* p = _Str; if (p) { while (*p) { *p = ::tolower(*p); p++; } } return _Str; } char ToLower(char Ch) { return ::tolower(Ch); } char* ToUpper(char* _Str) { char* p = _Str; if (p) { while (*p) { *p = ::toupper(*p); p++; } } return _Str; } char ToUpper(char Ch) { return ::toupper(Ch); } int Strlen(const char* _Str) { if (!_Str) { return 0; } const char* p = _Str; while (*p) { p++; } return p - _Str; //return (int)strlen( _Str ); } int StrContains(const char* _String, char _Ch) { if (_String) { for (const char* s = _String; *s; s++) { if (*s == _Ch) { return s - _String; } } } return -1; } int Substring(const char* _Str, const char* _SubStr) { if (!_Str || !_SubStr) { return -1; } const char* s = strstr(_Str, _SubStr); if (!s) { return -1; } return (int)(s - _Str); } int SubstringIcmp(const char* _Str, const char* _SubStr) { if (!_Str || !_SubStr) { return -1; } const char* s = _Str; int length = Strlen(_SubStr); while (*s) { if (StricmpN(s, _SubStr, length) == 0) { return (int)(s - _Str); } ++s; } return -1; } uint32_t HexToUInt32(const char* _Str, int _Len) { uint32_t value = 0; if (!_Str) { return 0; } for (int i = std::max(0, _Len - 8); i < _Len; i++) { uint32_t ch = _Str[i]; if (ch >= 'A' && ch <= 'F') { value = (value << 4) + ch - 'A' + 10; } else if (ch >= 'a' && ch <= 'f') { value = (value << 4) + ch - 'a' + 10; } else if (ch >= '0' && ch <= '9') { value = (value << 4) + ch - '0'; } else { return value; } } return value; } uint64_t HexToUInt64(const char* _Str, int _Len) { uint64_t value = 0; if (!_Str) { return 0; } for (int i = std::max(0, _Len - 16); i < _Len; i++) { uint64_t ch = _Str[i]; if (ch >= 'A' && ch <= 'F') { value = (value << 4) + ch - 'A' + 10; } else if (ch >= 'a' && ch <= 'f') { value = (value << 4) + ch - 'a' + 10; } else if (ch >= '0' && ch <= '9') { value = (value << 4) + ch - '0'; } else { return value; } } return value; } } // namespace Platform
18.961009
79
0.477803
5a7101e2844fbc9e66964710842291a84c9e091d
4,022
cpp
C++
Project1.cpp
TomasOchoa/CSCI-261-Project1-SimpleFileProcessing
a3413ee5b404944a2e4ea9204c35ad252f899e84
[ "MIT" ]
null
null
null
Project1.cpp
TomasOchoa/CSCI-261-Project1-SimpleFileProcessing
a3413ee5b404944a2e4ea9204c35ad252f899e84
[ "MIT" ]
null
null
null
Project1.cpp
TomasOchoa/CSCI-261-Project1-SimpleFileProcessing
a3413ee5b404944a2e4ea9204c35ad252f899e84
[ "MIT" ]
null
null
null
// CSCI 216 Fundamentals of Programming II Spring 2015 // Program #1: Getting started // Author: Tomas Ochoa // Date Due: 26 January 2015 // // This object of this program is to do some simple file processing. The program will first // ask the user to input a file name. If it doesn't exist it will continue to ask the user // to enter a file name until one that exists is found or exited manually. The program then // takes the first and last number in the file and finds the average between them. The results // are then printed //neccearry header files #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { //Declaration for the file object and name of the file //user wants fstream dataFile; char name[50]; //gets the name of the file the user wants cout << "What file should I use? "; cin >> name; dataFile.open(name, ios::in || ios::binary); //Check if it exists //If it doesnt exist keep asking user for a correct file if (dataFile.fail()) { do { cout << "That file does not exist!" << endl << endl << "What file should I use? "; cin >> name; dataFile.open(name, ios::in | ios::binary); } while (dataFile.fail()); } //Declaration for variables needed to see how many //items are in the file. Set to one because we automatically //take the first item before loop, which would then not account //for it int itemCount = 1; //Variables for the first and last number double firstNum = 0, lastNum = 0; //Variable to store the average of the first and second number double avg = 0; //since we're already at the beggining of the file, simply set //firstNum to the first item of the file dataFile >> firstNum; //This loop counts the number of items in the file while (!dataFile.eof()) { //Everytime the loop iterates the variable lastNum changes acording //to the current iteration. By the time its at the end of the file, the //lastNum will be set to the last number in the file, which is what we //want dataFile >> lastNum; itemCount++; } //Once reached to this point clear the screen for better legibility system("CLS"); //calculate the avg avg = ((firstNum + lastNum) / 2); //displays the info cout << "For the file " << name << endl << endl << "There are " << itemCount << " numbers in the file" << endl << "The first number is: " << firstNum << endl << "The last number is: " << lastNum << endl << "The average of the two is: " << setprecision(8) << avg << endl; //Close the file dataFile.close(); system("Pause"); return 0; } /* *********************************************************** IF "data1.txt" IS INPUTED: *********************************************************** For the file data1.txt There are 10000 numbers in the file The first number is: 195650 The last number is: 887747 The average of the two is: 541698.5 Press any key to continue... *********************************************************** IF DIFFERENT THINGS RATHER THAN AN EXISTING FILE IS INPUTEDID: *********************************************************** What File should I use? sdasd That file does not exist! What File should I use? data That file does not exist! What File should I use? data7.txt That file does not exist! What File should I use? data1 That file does not exist! What file should I use? (will continue to ask unless a file exists or closed manually) ************************************************************ IF "data3.txt" IS INPUTED: *********************************************************** For the file data3.txt There are 100000 numbers in the file The first number is: 195650 The last number is: 922741 The average of the two is: 559195.5 Press any key to continue... */
28.323944
95
0.58901
5a72682a7ae8be6fabc274a1d8efa6a2371a9390
96
cpp
C++
src/examples/06_module/02_shapes/circle.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-willcastl3
47a99259ea78662bd61a7f3390c8d59e004179e3
[ "MIT" ]
null
null
null
src/examples/06_module/02_shapes/circle.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-willcastl3
47a99259ea78662bd61a7f3390c8d59e004179e3
[ "MIT" ]
null
null
null
src/examples/06_module/02_shapes/circle.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-willcastl3
47a99259ea78662bd61a7f3390c8d59e004179e3
[ "MIT" ]
1
2021-05-25T20:20:15.000Z
2021-05-25T20:20:15.000Z
//circle.cpp #include "circle.h" using std::cout; void Circle::draw() { cout<<"Circle\n"; }
12
21
0.625
5a77c92d07cdc42e7f340155d5922230aa50d47a
4,199
cpp
C++
ofxTweener/src/ofxTweener.cpp
itsukichang/vacuuuum
9bb8605270d3da1acc6901287f9d08fc31119d87
[ "MIT" ]
null
null
null
ofxTweener/src/ofxTweener.cpp
itsukichang/vacuuuum
9bb8605270d3da1acc6901287f9d08fc31119d87
[ "MIT" ]
null
null
null
ofxTweener/src/ofxTweener.cpp
itsukichang/vacuuuum
9bb8605270d3da1acc6901287f9d08fc31119d87
[ "MIT" ]
null
null
null
/* * ofxTweener.cpp * openFrameworks * * Created by Sander ter Braak on 26-08-10. * */ #include "ofxTweener.h" ofxTweener Tweener; ofxTweener::ofxTweener(){ _scale = 1; setMode(TWEENMODE_OVERRIDE); } void ofxTweener::addTween(float &var, float to, float time, void (^callback)(float * arg)){ addTween(var,to,time, &ofxTransitions::easeOutExpo ,0,0,false, callback); } void ofxTweener::addTween(float &var, float to, float time, float (ofxTransitions::*ease) (float,float,float,float), void (^callback)(float * arg)){ addTween(var,to,time,ease,0,0,false, callback); } void ofxTweener::addTween(float &var, float to, float time, float (ofxTransitions::*ease) (float,float,float,float), float delay, void (^callback)(float * arg)){ addTween(var,to,time,ease,delay,0,false, callback); } void ofxTweener::addTween(float &var, float to, float time, float (ofxTransitions::*ease) (float,float,float,float), float delay, float bezierPoint, void (^callback)(float * arg)){ addTween(var,to,time,ease,delay, bezierPoint, true, callback); } void ofxTweener::addTween(float &var, float to, float time, float (ofxTransitions::*ease) (float,float,float,float), float delay, float bezierPoint, bool useBezier, void (^callback)(float * arg)){ float from = var; float _delay = delay; Poco::Timestamp latest = 0; for(int i = 0; i < tweens.size(); ++i){ if(tweens[i]._var == &var) { // object already tweening, just kill the old one if(_override){ tweens[i]._from = from; tweens[i]._to = to; tweens[i]._by = bezierPoint; tweens[i]._useBezier = useBezier; tweens[i]._easeFunction = ease; tweens[i]._timestamp = Poco::Timestamp() + ((delay / _scale) * 1000000.0f) ; tweens[i]._duration = (time / _scale) * 1000000.0f; return; } else { //sequence mode if((tweens[i]._timestamp + tweens[i]._duration) > latest){ latest = (tweens[i]._timestamp + tweens[i]._duration); delay = _delay + ((tweens[i]._duration - tweens[i]._timestamp.elapsed())/1000000.0f); from = tweens[i]._to; } } } } Tween t; t._var = &var; t._from = from; t._to = to; t._by = bezierPoint; t._useBezier = useBezier; t._easeFunction = ease; t._timestamp = Poco::Timestamp() + ((delay / _scale) * 1000000.0f) ; t._duration = (time / _scale) * 1000000.0f; tweens.push_back(t); if (callback!=NULL) callbacks[t._var] = callback; } void ofxTweener::update(){ for(int i = tweens.size() -1; i >= 0; --i){ if(float(tweens[i]._timestamp.elapsed()) >= float(tweens[i]._duration)){ //tween is done bool found = false; if(!_override){ //if not found anymore, place on exact place for(int j = 0; j < tweens.size(); ++j){ if(tweens[j]._var == tweens[i]._var) { found = true; break; } } } if(!found) tweens[i]._var[0] = tweens[i]._to; map<float *,void (^)(float * arg)>::iterator it = callbacks.find(tweens[i]._var); if(it != callbacks.end()) { it->second(tweens[i]._var); callbacks.erase(it); } tweens.erase(tweens.begin() + i); } else if(float(tweens[i]._timestamp.elapsed()) > 0){ //smaller than 0 would be delayed if(tweens[i]._useBezier) tweens[i]._var[0] = bezier(tweens[i]._from, tweens[i]._to ,(a.*tweens[i]._easeFunction )(float(tweens[i]._timestamp.elapsed()), 0, 1, float(tweens[i]._duration)), tweens[i]._by); else tweens[i]._var[0] = (a.*tweens[i]._easeFunction )(float(tweens[i]._timestamp.elapsed()), tweens[i]._from, tweens[i]._to - tweens[i]._from, float(tweens[i]._duration)); } } } void ofxTweener::removeTween(float &var){ for(int i = 0; i < tweens.size(); i++){ if(tweens[i]._var == &var) { // tween found, erase it tweens.erase(tweens.begin() + i); return; } } } float ofxTweener::bezier(float b, float e, float t, float p){ return b + t*(2*(1-t)*(p-b) + t*(e - b)); } void ofxTweener::removeAllTweens(){ tweens.clear(); } void ofxTweener::setMode(int mode){ _override = (mode == TWEENMODE_OVERRIDE); } int ofxTweener::getTweenCount(){ return int(tweens.size()); } void ofxTweener::setTimeScale(float scale){ _scale = scale; }
30.208633
206
0.637056
5a7821bce812b57e30493eaad57b046a6b4320a8
319
cpp
C++
test/io.cpp
victorrseloy/JSCPP-LIVE-REPL
941b5fd787b05e7ff18327a982b0a225ebfba70f
[ "MIT" ]
773
2015-05-26T23:51:00.000Z
2022-03-12T13:39:09.000Z
test/io.cpp
victorrseloy/JSCPP-LIVE-REPL
941b5fd787b05e7ff18327a982b0a225ebfba70f
[ "MIT" ]
128
2015-03-28T09:11:26.000Z
2022-03-11T09:14:28.000Z
test/io.cpp
victorrseloy/JSCPP-LIVE-REPL
941b5fd787b05e7ff18327a982b0a225ebfba70f
[ "MIT" ]
74
2015-06-16T08:44:49.000Z
2022-02-22T18:48:58.000Z
#include "iostream" #include "iomanip" using namespace std; int main() { double f = 3.14159; cout << setprecision(5) << f << '\n'; cout << setprecision(9) << f << '\n'; cout << fixed; cout << setprecision(5) << f << '\n'; cout << setprecision(9) << f << '\n'; cout << setw(15) << f << '\n'; return 0; }
22.785714
39
0.532915
5a7921f5c48252f44f0dcb2adfe8895fe89dcca0
189
cpp
C++
mod01/ex05/main.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod01/ex05/main.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod01/ex05/main.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
2
2021-01-31T13:52:11.000Z
2021-05-19T18:36:17.000Z
#include <iostream> #include "Human.hpp" int main() { Human bob; std::cout << bob.identity() << std::endl; std::cout << bob.getBrain().identity() << std::endl; return 0; }
17.181818
56
0.582011
5a798feffd0da4d3021a49dd4b74f077919dffa2
5,576
cpp
C++
implementations/ugene/src/corelibs/U2Lang/src/model/ExternalToolCfg.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Lang/src/model/ExternalToolCfg.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Lang/src/model/ExternalToolCfg.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <U2Core/BaseDocumentFormats.h> #include <U2Lang/BaseTypes.h> #include <U2Lang/ExternalToolCfg.h> namespace U2 { const DocumentFormatId DataConfig::STRING_VALUE = DocumentFormatId("string-value"); const DocumentFormatId DataConfig::OUTPUT_FILE_URL = DocumentFormatId("output-file-url"); bool DataConfig::isStringValue() const { return (BaseTypes::STRING_TYPE()->getId() == type) && (STRING_VALUE == format); } bool DataConfig::isFileUrl() const { return (OUTPUT_FILE_URL == format); } bool DataConfig::isSequence() const { return (BaseTypes::DNA_SEQUENCE_TYPE()->getId() == type); } bool DataConfig::isAnnotations() const { return (BaseTypes::ANNOTATION_TABLE_TYPE()->getId() == type); } bool DataConfig::isAnnotatedSequence() const { return (SEQ_WITH_ANNS == type); } bool DataConfig::isAlignment() const { return (BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId() == type); } bool DataConfig::isText() const { return (BaseTypes::STRING_TYPE()->getId() == type) && (BaseDocumentFormats::PLAIN_TEXT == format); } bool DataConfig::operator==(const DataConfig &other) const { return attributeId == other.attributeId && attrName == other.attrName && type == other.type && format == other.format && description == other.description; } const QString AttributeConfig::NUMBER_DEPRECATED_TYPE = "Number"; const QString AttributeConfig::URL_DEPRECATED_TYPE = "URL"; const QString AttributeConfig::BOOLEAN_TYPE = "Boolean"; const QString AttributeConfig::STRING_TYPE = "String"; const QString AttributeConfig::INTEGER_TYPE = "Integer"; const QString AttributeConfig::DOUBLE_TYPE = "Double"; const QString AttributeConfig::INPUT_FILE_URL_TYPE = "Input_file_URL"; const QString AttributeConfig::OUTPUT_FILE_URL_TYPE = "Output_file_URL"; const QString AttributeConfig::INPUT_FOLDER_URL_TYPE = "Input_dir_URL"; const QString AttributeConfig::OUTPUT_FOLDER_URL_TYPE = "Output_dir_URL"; AttributeConfig::AttributeConfig() : flags(None) { } void AttributeConfig::fixTypes() { if (type == URL_DEPRECATED_TYPE) { type = INPUT_FILE_URL_TYPE; } else if (type == NUMBER_DEPRECATED_TYPE) { type = STRING_TYPE; } } bool AttributeConfig::isOutputUrl() const { return type == OUTPUT_FILE_URL_TYPE || type == OUTPUT_FOLDER_URL_TYPE; } bool AttributeConfig::isFile() const { return type == INPUT_FILE_URL_TYPE || type == OUTPUT_FILE_URL_TYPE; } bool AttributeConfig::isFolder() const { return type == INPUT_FOLDER_URL_TYPE || type == OUTPUT_FOLDER_URL_TYPE; } bool AttributeConfig::operator==(const AttributeConfig &other) const { return attributeId == other.attributeId && attrName == other.attrName && type == other.type && defaultValue == other.defaultValue && description == other.description && flags == other.flags; } ExternalProcessConfig::ExternalProcessConfig() : useIntegratedTool(false) { } #define CHECK_EQ(expr1, expr2) \ if (!(expr1 == expr2)) { \ return false; \ } bool ExternalProcessConfig::operator==(const ExternalProcessConfig &other) const { CHECK_EQ(inputs.size(), other.inputs.size()); CHECK_EQ(outputs.size(), other.outputs.size()); CHECK_EQ(attrs.size(), other.attrs.size()); CHECK_EQ(cmdLine, other.cmdLine); CHECK_EQ(id, other.id); CHECK_EQ(name, other.name); CHECK_EQ(description, other.description); CHECK_EQ(templateDescription, other.templateDescription); CHECK_EQ(useIntegratedTool, other.useIntegratedTool); CHECK_EQ(customToolPath, other.customToolPath); CHECK_EQ(integratedToolId, other.integratedToolId); foreach (const DataConfig &in, inputs) { CHECK_EQ(other.inputs.contains(in), true); } foreach (const DataConfig &out, outputs) { CHECK_EQ(other.outputs.contains(out), true); } foreach (const AttributeConfig &at, attrs) { CHECK_EQ(other.attrs.contains(at), true); } return true; } bool ExternalProcessConfig::operator!=(const ExternalProcessConfig &other) const { return !operator==(other); } ExternalToolCfgRegistry::ExternalToolCfgRegistry(QObject *_parent) : QObject(_parent) { } bool ExternalToolCfgRegistry::registerExternalTool(ExternalProcessConfig *cfg) { if (configs.contains(cfg->id)) { return false; } else { configs.insert(cfg->id, cfg); return true; } } void ExternalToolCfgRegistry::unregisterConfig(const QString &id) { // TODO: UTI-294 configs.remove(id); } ExternalProcessConfig *ExternalToolCfgRegistry::getConfigById(const QString &id) const { return configs.value(id, nullptr); } QList<ExternalProcessConfig *> ExternalToolCfgRegistry::getConfigs() const { return configs.values(); } } // namespace U2
32.8
194
0.725072
5a7a8fd8615ec69ed0acb0c456a9a617b264a834
11,651
cpp
C++
Examples/Example1/Example1.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
null
null
null
Examples/Example1/Example1.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
null
null
null
Examples/Example1/Example1.cpp
mpartio/MXADataModel
cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57
[ "BSD-3-Clause" ]
1
2020-08-26T07:08:26.000Z
2020-08-26T07:08:26.000Z
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, 2010 Michael A. Jackson for BlueQuartz Software // All rights reserved. // BSD License: http://www.opensource.org/licenses/bsd-license.html // // This code was written under United States Air Force Contract number // FA8650-04-C-5229 // /////////////////////////////////////////////////////////////////////////////// /** * This example demonstrates the following: * Programmitically Creating a Data Model * Exporting the Model to an XML File * Retrieving a list of the Data Dimensions * Retrieving a list of the Data Records * Saving the Model to an HDF5 File * Writing some sample data to the HDF5 file * Shows 2 different ways to get the value from a User Defined Meta Data Object */ //-- MXA Includes #include "MXA/MXA.h" #include <MXA/Common/MXATypeDefs.h> #include <MXA/Common/LogTime.h> #include <MXA/Core/MXADataDimension.h> #include <MXA/Core/MXADataRecord.h> #include <MXA/Core/MXADataModel.h> #include "MXA/Core/MXADataModelWriter.hpp" #include <MXA/HDF5/H5Lite.h> #include <MXA/HDF5/H5Utilities.h> #include <MXA/HDF5/H5MXAUtilities.h> #include <MXA/HDF5/H5MXADataFile.h> #include <MXA/DataWrappers/MXAArrayTemplate.hpp> #include <MXA/XML/XMLFileUtilities.hpp> #include <Examples/ExampleFileLocations.h> // HDF5 Include #include <hdf5.h> // Declare methods void listDataDimensions(MXADataModel* model); void listDataRecords(MXADataModel* model); void captureSampleImage(std::vector<uint8_t> &imageBuffer); void listUserMetaData(IDataFile::Pointer dataFile); // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int main(int argc, char **argv) { std::cout << "Starting Example 1." << std::endl; //Instatiate a new model using the predefined boost shared pointer type MXADataModel::Pointer modelPtr = MXADataModel::New(); MXADataModel* model = modelPtr.get(); //Define at what path in the HDF5 file the data will be stored model->setDataRoot("/Experimental Data"); //Instantiate 2 Data Dimensions // The first dimension has 10 elements from 0 to 9 and increments by 1. Since this // is the first dimension we give it an index of 0 int32_t index = 0; int32_t count = 10; int32_t start = 0; int32_t end = 9; int32_t increment = 1; int32_t uniform = 1; MXADataDimension::Pointer dim1 = MXADataDimension::New("Time", "Time (minutes)", index, count, start, end, increment, uniform); // The second dimension will have 4 elements ranging from 2 to 8 with an increment of 2; index = 1; count = 4; start = 200; end = 800; increment = 200; uniform = 1; MXADataDimension::Pointer dim2 = MXADataDimension::New("Pressure", "Press (kPa)", index, count, start, end, increment, uniform); //Next we need to add these dimensions to the model. Since we are using Boost shared pointers // the dimension objects are refcounted thus relieving us from having to worry about cleaning up // the memory allocations model->addDataDimension(dim1); model->addDataDimension(dim2); // Next we need to create a data record to hold one of the dependent variables for our experiment. // In our sample experiment we are going to measure the temperature and record an image of the sample. // The important argument is the 'luid' argument. These need to be unique within each group of Data Records. MXADataRecord::Pointer temp = MXADataRecord::New(0, "Temperature" , "Temp (K)"); MXADataRecord::Pointer cameraImage = MXADataRecord::New(1, "Camera", "Camera Image"); // Next, add these Records to the Data Model model->addDataRecord(temp); model->addDataRecord(cameraImage); //Lastly a certain number of meta data fields are required to be set to non-empty values std::map<std::string, std::string> md; md[MXA::MXA_CREATOR_TAG] = "Mike Jackson"; // Who is performing the experiment md[MXA::MXA_DATE_TAG] = "2006:12:24 15:34.51"; // What date is the experiment being performed md[MXA::MXA_DSET_NAME_TAG] = "Testing Data Import"; // Give this specific experiment a name or other identifying tag md[MXA::MXA_DESCRIPTION_TAG] = "Application to test importing data to the data file"; // Give a short description of the experiment md[MXA::MXA_PEDIGREE_TAG] = MXA::MXA_PEDIGREE_ORIGINAL_VALUE; // Is the data being stored original data or was it imported from another source? md[MXA::MXA_DERIVED_SRC_TAG] = MXA::MXA_NOT_APPLICABLE_VALUE; // The data is original from the instrument so this tag is not needed md[MXA::MXA_RIGHTS_TAG] = MXA::MXA_RIGHTS_UNLIMITED_VALUE; // There are no limitations on the distribution of the data md[MXA::MXA_RELEASE_NUMBER_TAG] = "90312901291239012390"; // The Data has been through a local public affairs office which assigned the data this unique ID model->setRequiredMetaData(md); // So now our model should be valid. We can check the validity of the model with the following: std::string message; bool valid = model->isValid(message); if ( !valid ) { std::cout << "Model was NOT valid. Exiting with Failure. Error message given was: \n" << message << std::endl; return EXIT_FAILURE; } // Add some user defined Meta Data to the model float value = 12.234234f; IMXAArray::Pointer umd = MXAArrayTemplate<float>::CreateSingleValueArray(value); model->addUserMetaData("Float32 User Meta Data", umd); int32_t iMDValue = 34212; IMXAArray::Pointer iUmd = MXAArrayTemplate<int32_t>::CreateSingleValueArray(iMDValue); model->addUserMetaData("Int32 User Meta Data", iUmd); int32_t err = MXAXMLModelFileWriter::writeModel(modelPtr, Examples::Example1_XMLFile); if (err < 0) { std::cout << "Error writing model to an xml file" << std::endl; return -1; } // List the Data Dimensions of the model listDataDimensions(model); // List the Data Records in the model listDataRecords(model); //Write the model to a new HDF5 file, deleting any existing file and // allowing the Hdf5 file to remain open for further processing IDataFile::Pointer dataFile = H5MXADataFile::CreateFileWithModel(Examples::Example1File, modelPtr); if (NULL == dataFile.get() ) { std::cout << "Error Writing Model to HDF5 File" << std::endl; return EXIT_FAILURE; } //List the User Meta Data listUserMetaData(dataFile); //Lets store some data into the HDF5 File. In our experiment we are recording the time // in 1 minute intervals for 10 minutes and also incrementing the pressure by // 200 KPa starting at 200 and ending at 800 KPa. At each combination of those // values we are taking the temperature and capturing an image of our sample hid_t fileId = dataFile->getFileId();//We need the HDF5 indentifier for the open file std::vector<int32_t> indices(2, 0); // we keep this for re-use during the loop std::string temperaturePath; std::string cameraImagePath; std::string::size_type pos = 0; float temperature = 1200.0f; std::vector<uint8_t> image; err = 0; // Define the height/width of our camera "image" std::vector<hsize_t> dims (2,0); dims[0] = 10; dims[1] = 10; for (int t = 0; t <= 9; ++t) { indices[0] = t; for (int p = 200; p <= 800; p+=200) { temperature += (float)p; indices[1] = p; temperaturePath = H5MXAUtilities::generateH5PathToDataset(modelPtr, indices, temp ); cameraImagePath = H5MXAUtilities::generateH5PathToDataset(modelPtr, indices, cameraImage ); pos = temperaturePath.find_last_of("/"); std::string parentPath ( temperaturePath.substr(0, pos) ); // Make sure the path to the dataset in the HDF5 file is already created. H5Utilities::createGroupsFromPath(parentPath, fileId); // Write the temperature value to the HDF5 File err = H5Lite::writeScalarDataset(fileId, temperaturePath, temperature); if (err < 0) { std::cout << "Error writing temperature dataset for (t,p):" << t << "," << p << std::endl; break; } captureSampleImage(image); err = H5Lite::writeVectorDataset(fileId, cameraImagePath, dims, image); if (err < 0) { std::cout << "Error writing image dataset for (t,p):" << t << "," << p << std::endl; break; } } } std::cout << "... Ending Example 1" << std::endl; return EXIT_SUCCESS; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void captureSampleImage(std::vector<uint8_t> &imageBuffer) { imageBuffer.clear(); // Clear the Array first for (int i = 0; i < 10; ++i) { for (int j = 0; j < 10; ++j) { imageBuffer.push_back(i*j); } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void listUserMetaData(IDataFile::Pointer dataFile) { IDataModel::Pointer modelPtr = dataFile->getDataModel(); MXAAbstractAttributes userMetaData = modelPtr->getUserMetaData(); float* fAttr = NULL; IMXAArray::Pointer attr; std::string key; //std::string value; for (MXAAbstractAttributes::iterator iter = userMetaData.begin(); iter != userMetaData.end(); ++iter ) { key = (*iter).first; attr = (*iter).second; if (key.compare("Int32 User Meta Data") == 0) { // This works because we have a-priori knowledge of the type of data stored int32_t* valuePtr = static_cast<int32_t*>( attr->getVoidPointer(0) ); std::cout << "Value is: " << *valuePtr << std::endl; } if (key.compare("Float32 User Meta Data") == 0) { // This works because we have a-priori knowledge of the type of data stored fAttr = static_cast<float*>(attr->getVoidPointer(0) ); std::cout << "Value is: " << *fAttr << std::endl; } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void listDataDimensions(MXADataModel* model) { //We can now get a list of the Data Dimensions and print out various properties for each IDataDimension::Container dims = model->getDataDimensions(); MXADataDimension* dim = NULL; // Use a Pointer to make the code a bit easier to read for (IDataDimension::Container::iterator iter = dims.begin(); iter != dims.end(); ++iter ) { dim = static_cast<MXADataDimension*>((*(iter)).get() ); if (NULL == dim) { std::cout << logTime() << "Error: Dimension was NULL. " << std::endl; break; } std::cout << "Data Dimension:[" << dim->getIndex() << "]: " << dim->getDimensionName() << std::endl; } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void listDataRecords(MXADataModel* model) { // We can get a list of Data Records and print out the top level records. // Note that Data Records are stored in a tree structure, so without any type of // tree traversal, this code will only print the top level records. IDataRecord::Container records = model->getDataRecords(); MXADataRecord* rec = NULL; //Create a convenience pointer for (IDataRecord::Container::iterator iter = records.begin(); iter != records.end(); ++iter ) { rec = static_cast<MXADataRecord*>( (*(iter)).get() ); std::cout << "Data Record: " << rec->getRecordName() << std::endl; } }
40.314879
157
0.634967
5a7bd61fb13f1c2a6333018f5dd33db02ad43053
345
cpp
C++
C++/queue/queueTest2.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
C++/queue/queueTest2.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
C++/queue/queueTest2.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> using namespace std; int main() { queue<int> q; q.push(11); while (!q.empty()) { int x = q.front(); q.pop(); cout << x << endl; int y = x / 2; if (y > 1) { if ((x % 2)) { q.push(y - 1); q.push(y + 1); } else { q.push(y); } } } }
12.777778
22
0.402899
5a7d5025b11a7afb6aa28b7aab0f0696421d0e6b
2,410
hxx
C++
opencascade/Vrml_Separator.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Vrml_Separator.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Vrml_Separator.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1997-03-27 // Created by: Alexander BRIVIN and Dmitry TARASOV // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // 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, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Vrml_Separator_HeaderFile #define _Vrml_Separator_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Vrml_SeparatorRenderCulling.hxx> #include <Standard_Boolean.hxx> #include <Standard_OStream.hxx> //! defines a Separator node of VRML specifying group properties. //! This group node performs a push (save) of the traversal state before traversing its children //! and a pop (restore) after traversing them. This isolates the separator's children from the //! rest of the scene graph. A separator can include lights, cameras, coordinates, normals, //! bindings, and all other properties. //! Separators can also perform render culling. Render culling skips over traversal of the //! separator's children if they are not going to be rendered, based on the comparison of the //! separator's bounding box with the current view volume. Culling is controlled by the //! renderCulling field. These are set to AUTO by default, allowing the implementation to //! decide whether or not to cull. class Vrml_Separator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Vrml_Separator(const Vrml_SeparatorRenderCulling aRenderCulling); Standard_EXPORT Vrml_Separator(); Standard_EXPORT void SetRenderCulling (const Vrml_SeparatorRenderCulling aRenderCulling); Standard_EXPORT Vrml_SeparatorRenderCulling RenderCulling() const; Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream); protected: private: Vrml_SeparatorRenderCulling myRenderCulling; Standard_Boolean myFlagPrint; }; #endif // _Vrml_Separator_HeaderFile
29.390244
96
0.785477
5a7e22263a30f08d591916b4d9b50b99e85f836b
11,581
cpp
C++
source/de/hackcraft/world/sub/computer/rController.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
23
2015-12-08T19:29:10.000Z
2021-09-22T04:13:31.000Z
source/de/hackcraft/world/sub/computer/rController.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
7
2018-04-30T13:05:57.000Z
2021-08-25T03:58:07.000Z
source/de/hackcraft/world/sub/computer/rController.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
4
2018-01-25T03:05:19.000Z
2021-08-25T03:30:15.000Z
#include "rController.h" #include "de/hackcraft/log/Logger.h" #include "de/hackcraft/world/Entity.h" #include "de/hackcraft/world/World.h" #include "de/hackcraft/world/object/cMech.h" #include "de/hackcraft/world/sub/weapon/rTarcom.h" #include <cstdlib> #include <cassert> #include <sstream> using std::string; Logger* rController::logger = Logger::getLogger("de.hackcraft.world.sub.computer.rController"); std::string rController::cname = "CONTROLLER"; unsigned int rController::cid = 3637; rController::rController(Entity* entity, bool enable) { object = entity; enabled = enable; lastDisturbedBy = 0; disturbedBy = 0; enemyNearby = 0; aimtarget = 0; firetarget = false; walktargetdist = 0.0f; vector_zero(walktarget); idling = false; aimrange = 0; walkrange = 0; nearToDistance = 23; debugState = !true; debugTransitions = !true; debugStep = !true; } rController::~rController() { while (!commandStack.empty()) commandStack.pop_back(); } void rController::doit(OID aim, float* go, bool fire, float distance) { aimtarget = aim; firetarget = fire; if (go != NULL) { vector_cpy(walktarget, go); } else if (aimtarget == 0) { vector_set(walktarget, float_NAN, float_NAN, float_NAN); } else { Entity* tgt = World::getInstance()->getObject(aimtarget); if (tgt != NULL) { vector_cpy(walktarget, tgt->pos0); } else { vector_set(walktarget, float_NAN, float_NAN, float_NAN); } } walktargetdist = distance; idling = !firetarget && (aimtarget == 0) && (go == NULL); /* if (!true) { //object->do_moveFor(go); //object->do_aimFor(aim); object->do_aimAt(); if (go) { object->do_moveTowards(); } else if (aim) { object->do_moveNear(); } if (fire) object->do_fireAt(); if (idling) object->do_idle(); } */ } void rController::printState() { int framesize = getFrameSize(); string framename = getFrameName(); logger->debug() << "CtrlSt of " << object->name.c_str() << "#" << object->oid << " Frame: " << framename << " Framesize:" << framesize << " Stack: " << commandStack.size() << "\n"; } string rController::getFrameName() { //cout << "getFrameName()\n"; const char* names[] = { "WAIT", "ATTACK", "FOLLOW", "GOTO", "REPEAT", "NOSTATENAME" }; unsigned int i = commandStack.back(); i = (i < OPCODE_MAX) ? i : OPCODE_MAX - 1; string s = string(names[i]); return s; }; unsigned int rController::getFrameSizeOf(int opcode) { switch (opcode) { case WAIT: return 3; case ATTACK: return 2; case FOLLOW: return 3; case GOTO: return 5; case REPEAT: return 2; default: return 2; } } unsigned int rController::getFrameSize() { return getFrameSizeOf(commandStack.back()); } OID rController::getParameter(int offset) { return commandStack[commandStack.size() - offset - 1]; } void rController::setParameter(int offset, OID value) { commandStack[commandStack.size() - offset - 1] = value; } void rController::push(OID value) { commandStack.push_back(value); } void rController::pop(std::string reason) { if (debugTransitions) { logger->debug() << object->name.c_str() << "#" << object->oid << ".pop(" << reason << ")\n"; } int size = getFrameSize(); // Important: eval outside loop-condition! for (int i = 0; i < size; i++) { commandStack.pop_back(); } if (debugTransitions) { printState(); } } void rController::animate(float spf) { if (debugState) logger->debug() << "cController::process()\n"; if (!active || !enabled || object == NULL) return; if (commandStack.empty()) pushWaitEvent(); if (debugStep) printState(); switch (commandStack.back()) { case WAIT: waitEvent(); break; case ATTACK: attackEnemy(); break; case FOLLOW: followLeader(); break; case GOTO: gotoDestination(); break; case REPEAT: repeatInstructions(); break; default: logger->error() << "Invalid Instruction Request!\n"; break; } if (debugStep) { logger->debug() << "=> "; printState(); } } // ------------------------------------------------------------- void rController::pushWaitEvent(long mseconds, bool patrol) { push(patrol); push(mseconds); push(WAIT); } void rController::waitEvent() { //OID opcode = getParameter(0); long mseconds = getParameter(1); bool patrol = getParameter(2); { this->doit(0, NULL, false); } if (patrol) { OID enemy = 0; if (enemy == 0 && lastDisturbedBy != disturbedBy) { // Ignore next time - probably destroyed. // FIXME: Find better solution to prevent jumpy/locked behavior. lastDisturbedBy = disturbedBy; enemy = disturbedBy; //cout << "DISTURBER !!!!!!!!!!!!!\n"; } if (enemy == 0) { enemy = enemyNearby; if (enemy != 0) { //cout << "INTRUDER !!!!!!!!!!!!!\n"; } } if (enemy) { { OID self = object->oid; std::stringstream s; s << self << ": Intruder!\n"; //World::getInstance()->sendMessage(0, self, 0, "DEBUG", s.str()); } this->doit(enemy, NULL, false, nearToDistance); pushAttackEnemy(enemy); } } if (mseconds > 0) { mseconds -= 1000 / 40; setParameter(1, mseconds); if (mseconds <= 0) { pop("Timeout for wait was reached."); return; } } } // ------------------------------------------------------------- void rController::pushAttackEnemy(OID entity) { if (debugTransitions) { logger->debug() << object->name.c_str() << "#" << object->oid << ".pushAttackEnemy( " << entity << " )\n"; } { //OID self = mDevice->mSerial; //World::getInstance()->sendMessage("@%llu: All ur base belongs to us.\n", entity); } push(entity); push(ATTACK); } void rController::attackEnemy() { //OID opcode = getParameter(0); OID entity = getParameter(1); { //((cMech*)mDevice)->Pattern(tf, "nrnlln"); this->doit(entity, NULL, aimrange < 50.0f, nearToDistance); } // FIXME: Depends on Mech/tarcom. //cMech* mech = (cMech*) object; if (disturbedBy != 0 && disturbedBy != entity) { pop("Changing target (disturbed by another)"); pushAttackEnemy(disturbedBy); return; } //Entity* target = World::getInstance()->getObject(entity); rTarget* target = WeaponSystem::getInstance()->findTargetByEntity(entity); rTarcom* tarcom = WeaponSystem::getInstance()->findTarcomByEntity(this->object->oid); if (target == NULL) { this->doit(0, NULL, false); pop("Target disappeared (removed from world: fragged)."); return; } else if (tarcom == NULL) { this->doit(0, NULL, false); pop("Tarcom disappeared (removed from world: fragged)."); return; //} else if (!mech->tarcom->isEnemy(&target->tags)) { // TODO: Change dependency. } else if (!target->isEnemy(tarcom)) { this->doit(0, NULL, false); pop("Not an enemy anymore (maybe dead or not interesting anymore)."); return; } else if (aimrange > 60.0f && disturbedBy == 0) { this->doit(0, NULL, false); pop("Target is out of targeting range."); return; } } // ------------------------------------------------------------- void rController::pushFollowLeader(OID entity, bool patrol) { if (debugTransitions) { logger->debug() << object->name.c_str() << "#" << object->oid << ".pushFollowLeader( " << entity << ", " << patrol << " )\n"; } push(patrol ? 1 : 0); push(entity); push(FOLLOW); } void rController::followLeader() { //OID opcode = getParameter(0); OID entity = getParameter(1); OID patrol = getParameter(2); { this->doit(entity, NULL, false, nearToDistance); } if (patrol) { OID nearby = enemyNearby; //controlledDevice->enemyNearby(); if (nearby) { this->doit(nearby, NULL, false, nearToDistance); pushAttackEnemy(nearby); return; } } } // ------------------------------------------------------------- void rController::pushGotoDestination(float* v, bool patrol) { if (v == NULL) return; if (debugTransitions) { logger->debug() << object->name.c_str() << "#" << object->oid << ".pushGotoDestination( <" << v[0] << "," << v[1] << "," << v[2] << ">, " << patrol << " )\n"; } unsigned long *p = (unsigned long*) v; push(patrol ? !0 : 0); push(p[2]); push(p[1]); push(p[0]); push(GOTO); } void rController::gotoDestination() { //OID opcode = getParameter(0); OID v0 = getParameter(1); OID v1 = getParameter(2); OID v2 = getParameter(3); OID patrol = getParameter(4); // Store data in integer array that really holds binary float data. unsigned long p[] = { (unsigned long) v0, (unsigned long) v1, (unsigned long) v2 }; // Now re-interprete as a float array. float* v = (float*) ((void*) p); { if (debugState) logger->debug() << "going " << ((patrol > 0) ? "patrolling" : "directly") << " to <" << v[0] << "," << v[1] << "," << v[2] << " >\n"; float* u = new float[3]; vector_set(u, v[0], v[1], v[2]); this->doit(0, u, false); delete[] u; } float range = walkrange; if (debugState) logger->debug() << "DestinationRange " << range << "\n"; if (range < 8.0f) { this->doit(0, NULL, false); pop("Destination was reached (within destination range)."); return; } if (patrol) { OID nearby = enemyNearby; if (nearby) { this->doit(nearby, NULL, false, nearToDistance); pushAttackEnemy(nearby); return; } } } // ------------------------------------------------------------- void rController::pushRepeatInstructions(int n) { if (debugTransitions) { logger->debug() << object->name.c_str() << "#" << object->oid << ".pushRepeatInstructions( " << n << " )\n"; } push(n); push(REPEAT); } void rController::repeatInstructions() { OID opcode = getParameter(0); OID n = getParameter(1); if (debugState) { printState(); } unsigned int first = getFrameSize(); if (debugState) logger->debug() << "first " << first << " -> opcode " << opcode << "\n"; unsigned int last = first; for (int i = 0; i < (int) n; i++) { int opcode = getParameter(last); last += getFrameSizeOf(opcode); if (debugState) logger->debug() << "last " << last << " -> opcode " << opcode << "\n"; } int size = last - first; if (debugState) logger->debug() << size << " = " << last << " - " << first << "\n"; for (int i = 0; i < size; i++) { push(getParameter(last - 1)); } }
24.640426
187
0.528711
5a7f917a1641628bc3ba2cee0b77fbc8aedb6a29
34
cpp
C++
src/IceRay/type/type.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/type/type.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/type/type.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include "./general/general.cpp"
17
33
0.705882
5a8379011405bdc4d048a92c93eb0001eb3e44e7
1,756
cpp
C++
Logger.cpp
alonf/UniversalACRemote
6d4bb6e475a5f71e264a4b48a757ae182df796aa
[ "MIT" ]
1
2019-12-26T01:11:30.000Z
2019-12-26T01:11:30.000Z
Logger.cpp
alonf/UniversalACRemote
6d4bb6e475a5f71e264a4b48a757ae182df796aa
[ "MIT" ]
1
2020-12-06T12:55:01.000Z
2020-12-06T12:55:01.000Z
Logger.cpp
alonf/UniversalACRemote
6d4bb6e475a5f71e264a4b48a757ae182df796aa
[ "MIT" ]
null
null
null
#include "Logger.h" using namespace std; Logger::Logger(int redLedPin, int greenLedPin, int baudRate /*= 115200*/): _ledsLogger(LedsLogger::Create(redLedPin, greenLedPin)) { Serial.begin(baudRate); Serial.setDebugOutput(true); } void Logger::OnCommand(const String &commandName, int commandId) const { Serial.println(commandName + " command recieved"); _ledsLogger->BlinkGreen(commandId, 250); } void Logger::WriteErrorMessage(const String& message, int blinks) const { Serial.println(message.c_str()); _ledsLogger->BlinkRed(blinks, 500); } void Logger::OnWiFiStatusChanged(const ConnectionStatus& status) const { if (status.IsAccessPointModeOn()) { if (status.IsJustConnected()) { _ledsLogger->SetRed(1); _ledsLogger->SetGreen(1); } if (status.IsJustDissconnected()) { _ledsLogger->BlinkGreen(1000000, 150); _ledsLogger->BlinkRed(1000000, 150); } return; } if (status.IsJustConnected()) { Serial.println(status.Message().c_str()); Serial.print("IP address: "); Serial.println(status.LocalIP()); } _ledsLogger->SetGreen(status.IsConnected() ? HIGH : LOW); _ledsLogger->SetRed(status.IsConnected() ? LOW : HIGH); if (status.IsConnected()) { _ledsLogger->BlinkIpAddress(status.LocalIP()); } else { _ledsLogger->BlinkRed(3 + status.WifiCode(), 250); } } void Logger::OnLongButtonPressDetection() const { _ledsLogger->BlinkGreen(1000, 40); _ledsLogger->BlinkRed(1000, 40); } void Logger::OnVeryLongButtonPressDetection() const { _ledsLogger->BlinkGreen(10000, 20); _ledsLogger->BlinkRed(10000, 20); } void Logger::WriteMessage(const String& message) { Serial.println(message.c_str()); } void Logger::TestLeds() const { _ledsLogger->BlinkGreen(3, 100); _ledsLogger->BlinkRed(3, 100); }
21.679012
130
0.723235
5a870fd79cf4d1010645b3db87f9e3820b60be81
392
cpp
C++
1451/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1451/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1451/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; int solve_x(int x) { if (x == 1) { return 0; } else if (x == 2) { return 1; } else if (x & 1) { return 1 + solve_x(x - 1); } else { return 2; } } int solve() { int n; scanf("%d", &n); return solve_x(n); } int main() { int t; scanf("%d", &t); while (t--) { printf("%d\n", solve()); } }
12.645161
30
0.484694
5a9035c976299f8f74d6b077936d00b2cef53368
7,932
hpp
C++
shared/dumps/UnityEngine_GameObject.hpp
zoller27osu/beatsaber-hook
83a4bb55ed8b2f9e4c977877bc1b0601fed36f39
[ "MIT" ]
1
2020-04-22T07:37:13.000Z
2020-04-22T07:37:13.000Z
shared/dumps/UnityEngine_GameObject.hpp
zoller27osu/beatsaber-hook
83a4bb55ed8b2f9e4c977877bc1b0601fed36f39
[ "MIT" ]
null
null
null
shared/dumps/UnityEngine_GameObject.hpp
zoller27osu/beatsaber-hook
83a4bb55ed8b2f9e4c977877bc1b0601fed36f39
[ "MIT" ]
null
null
null
#ifndef UnityEngine_GameObject_DEFINED #define UnityEngine_GameObject_DEFINED // This .hpp file was compiled via beatsaber-hook/shared/helper.py's Parse Mode. // Created by Sc2ad. // Methods may not be valid! #include <dlfcn.h> #include <string_view> #include "../utils/typedefs.h" #include "../utils/il2cpp-functions.hpp" #include "../utils/il2cpp-utils.hpp" // Contains MethodInfo/Il2CppClass data for: UnityEngine.GameObject namespace UnityEngine_GameObject { // UnityEngine.GameObject typedef struct Class : Il2CppObject { } Class; static bool __cached = false; static Il2CppClass* klass; static const MethodInfo* CreatePrimitive_PrimitiveType; static const MethodInfo* GetComponent_generic; static const MethodInfo* GetComponent_Type; static const MethodInfo* GetComponentFastPath_Type_IntPtr; static const MethodInfo* GetComponentByName_string; static const MethodInfo* GetComponent_string; static const MethodInfo* GetComponentInChildren_Type_bool; static const MethodInfo* GetComponentInChildren_Type; static const MethodInfo* GetComponentInChildren_generic; static const MethodInfo* GetComponentInChildren_bool_generic; static const MethodInfo* GetComponentInParent_Type; static const MethodInfo* GetComponentsInternal_Type_bool_bool_bool_bool_object; static const MethodInfo* GetComponents_Type; static const MethodInfo* GetComponents; static const MethodInfo* GetComponents_List1; static const MethodInfo* GetComponentsInChildren_Type_bool; static const MethodInfo* GetComponentsInChildren_bool; static const MethodInfo* GetComponentsInChildren_bool_List1; static const MethodInfo* GetComponentsInChildren; static const MethodInfo* GetComponentsInParent_Type_bool; static const MethodInfo* GetComponentsInParent_bool_List1; static const MethodInfo* GetComponentsInParent_bool; static const MethodInfo* Internal_AddComponentWithType_Type; static const MethodInfo* AddComponent_Type; static const MethodInfo* AddComponent_generic; static const MethodInfo* get_transform; static const MethodInfo* get_layer; static const MethodInfo* set_layer; static const MethodInfo* SetActive_bool; static const MethodInfo* get_activeSelf; static const MethodInfo* get_activeInHierarchy; static const MethodInfo* get_tag; static const MethodInfo* set_tag; static const MethodInfo* FindGameObjectsWithTag_string; static const MethodInfo* SendMessage_string_object_SendMessageOptions; static const MethodInfo* BroadcastMessage_string_object_SendMessageOptions; static const MethodInfo* Internal_CreateGameObject_GameObject_string; static const MethodInfo* Find_string; static const MethodInfo* get_scene; static const MethodInfo* get_gameObject; static const MethodInfo* get_scene_Injected_out_Scene; // The Initialization function that must be called before using any of these definitions static void Init() { if (!__cached) { klass = il2cpp_utils::GetClassFromName("UnityEngine", "GameObject"); CreatePrimitive_PrimitiveType = il2cpp_functions::class_get_method_from_name(klass, "CreatePrimitive", 1); GetComponent_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 0); GetComponent_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 1); GetComponentFastPath_Type_IntPtr = il2cpp_functions::class_get_method_from_name(klass, "GetComponentFastPath", 2); GetComponentByName_string = il2cpp_functions::class_get_method_from_name(klass, "GetComponentByName", 1); GetComponent_string = il2cpp_functions::class_get_method_from_name(klass, "GetComponent", 1); GetComponentInChildren_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 2); GetComponentInChildren_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 1); GetComponentInChildren_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 0); GetComponentInChildren_bool_generic = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInChildren", 1); GetComponentInParent_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponentInParent", 1); GetComponentsInternal_Type_bool_bool_bool_bool_object = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInternal", 6); GetComponents_Type = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 1); GetComponents = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 0); GetComponents_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponents", 1); GetComponentsInChildren_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 2); GetComponentsInChildren_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 1); GetComponentsInChildren_bool_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 2); GetComponentsInChildren = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInChildren", 0); GetComponentsInParent_Type_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 2); GetComponentsInParent_bool_List1 = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 2); GetComponentsInParent_bool = il2cpp_functions::class_get_method_from_name(klass, "GetComponentsInParent", 1); Internal_AddComponentWithType_Type = il2cpp_functions::class_get_method_from_name(klass, "Internal_AddComponentWithType", 1); AddComponent_Type = il2cpp_functions::class_get_method_from_name(klass, "AddComponent", 1); AddComponent_generic = il2cpp_functions::class_get_method_from_name(klass, "AddComponent", 0); get_transform = il2cpp_functions::class_get_method_from_name(klass, "get_transform", 0); get_layer = il2cpp_functions::class_get_method_from_name(klass, "get_layer", 0); set_layer = il2cpp_functions::class_get_method_from_name(klass, "set_layer", 1); SetActive_bool = il2cpp_functions::class_get_method_from_name(klass, "SetActive", 1); get_activeSelf = il2cpp_functions::class_get_method_from_name(klass, "get_activeSelf", 0); get_activeInHierarchy = il2cpp_functions::class_get_method_from_name(klass, "get_activeInHierarchy", 0); get_tag = il2cpp_functions::class_get_method_from_name(klass, "get_tag", 0); set_tag = il2cpp_functions::class_get_method_from_name(klass, "set_tag", 1); FindGameObjectsWithTag_string = il2cpp_functions::class_get_method_from_name(klass, "FindGameObjectsWithTag", 1); SendMessage_string_object_SendMessageOptions = il2cpp_functions::class_get_method_from_name(klass, "SendMessage", 3); BroadcastMessage_string_object_SendMessageOptions = il2cpp_functions::class_get_method_from_name(klass, "BroadcastMessage", 3); Internal_CreateGameObject_GameObject_string = il2cpp_functions::class_get_method_from_name(klass, "Internal_CreateGameObject", 2); Find_string = il2cpp_functions::class_get_method_from_name(klass, "Find", 1); get_scene = il2cpp_functions::class_get_method_from_name(klass, "get_scene", 0); get_gameObject = il2cpp_functions::class_get_method_from_name(klass, "get_gameObject", 0); get_scene_Injected_out_Scene = il2cpp_functions::class_get_method_from_name(klass, "get_scene_Injected", 1); __cached = true; } } } #endif /* UnityEngine_GameObject_DEFINED */
73.444444
148
0.775466
5a9b0d466153bbd7f0f42fe011b3fd24696215c6
5,388
hh
C++
src/mem/tcu/cmds.hh
Barkhausen-Institut/gem5-TCU
c3c86be12debec937b9b5dd351df13e5ea43ab4a
[ "BSD-3-Clause" ]
null
null
null
src/mem/tcu/cmds.hh
Barkhausen-Institut/gem5-TCU
c3c86be12debec937b9b5dd351df13e5ea43ab4a
[ "BSD-3-Clause" ]
null
null
null
src/mem/tcu/cmds.hh
Barkhausen-Institut/gem5-TCU
c3c86be12debec937b9b5dd351df13e5ea43ab4a
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015, Christian Menard * Copyright (C) 2020 Nils Asmussen, Barkhausen Institut * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 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 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #ifndef __MEM_TCU_CMDS_HH__ #define __MEM_TCU_CMDS_HH__ #include "mem/tcu/base.hh" #include "mem/tcu/error.hh" class Tcu; class TcuCommands { public: enum class AbortType { NONE, LOCAL, REMOTE, }; public: TcuCommands(Tcu &_tcu); const std::string name() const; void regStats(); void startCommand(RegFile::Result written, PacketPtr pkt, Tick when); void stopCommand(); void scheduleCmdFinish(Cycles delay, TcuError error = TcuError::NONE); void scheduleExtCmdFinish(Cycles delay, TcuError error, RegFile::reg_t arg); void setRemoteCommand(bool remote) { cmdIsRemote = remote; } bool isCommandAborting() const { return abort != AbortType::NONE; } private: void executeCommand(PacketPtr pkt); void abortCommand(); void executePrivCommand(PacketPtr pkt); void finishAbort(); void executeExtCommand(PacketPtr pkt); void finishCommand(TcuError error); void finishExtCommand(TcuError error, RegFile::reg_t arg); private: struct CmdEvent : public Event { TcuCommands& cmds; CmdEvent(TcuCommands& _cmds) : cmds(_cmds) {} const std::string name() const override; }; struct ExecCmdEvent : public CmdEvent { PacketPtr pkt; ExecCmdEvent(TcuCommands& _cmds, PacketPtr _pkt) : CmdEvent(_cmds), pkt(_pkt) {} void process() override { cmds.executeCommand(pkt); setFlags(AutoDelete); } const char* description() const override { return "ExecCmdEvent"; } }; struct ExecPrivCmdEvent : public CmdEvent { PacketPtr pkt; ExecPrivCmdEvent(TcuCommands& _cmds, PacketPtr _pkt) : CmdEvent(_cmds), pkt(_pkt) {} void process() override { cmds.executePrivCommand(pkt); setFlags(AutoDelete); } const char* description() const override { return "ExecPrivCmdEvent"; } }; struct ExecExtCmdEvent : public CmdEvent { PacketPtr pkt; ExecExtCmdEvent(TcuCommands& _cmds, PacketPtr _pkt) : CmdEvent(_cmds), pkt(_pkt) {} void process() override { cmds.executeExtCommand(pkt); setFlags(AutoDelete); } const char* description() const override { return "ExecExtCmdEvent"; } }; struct FinishCommandEvent : public CmdEvent { TcuError error; FinishCommandEvent(TcuCommands& _cmds, TcuError _error = TcuError::NONE) : CmdEvent(_cmds), error(_error) {} void process() override { cmds.finishCommand(error); setFlags(AutoDelete); } const char* description() const override { return "FinishCommandEvent"; } }; struct FinishExtCommandEvent : public CmdEvent { TcuError error; RegFile::reg_t arg; FinishExtCommandEvent(TcuCommands& _cmds, TcuError _error, RegFile::reg_t _arg) : CmdEvent(_cmds), error(_error), arg(_arg) {} void process() override { cmds.finishExtCommand(error, arg); setFlags(AutoDelete); } const char* description() const override { return "FinishExtCommandEvent"; } }; Tcu &tcu; PacketPtr cmdPkt; PacketPtr privCmdPkt; PacketPtr extCmdPkt; FinishCommandEvent *cmdFinish; FinishExtCommandEvent *extCmdFinish; AbortType abort; bool cmdIsRemote; public: Stats::Vector commands; Stats::Vector privCommands; Stats::Vector extCommands; }; #endif // __MEM_TCU_CMDS_HH__
25.17757
81
0.648107
5a9e15128229c9f829ebe95b5c346e9c54dfd520
30,756
cpp
C++
taglib/mp4tag.cpp
acristoffers/SimplePlayer
aba0702901960648fc6602201f85198af87377ed
[ "MIT-0" ]
null
null
null
taglib/mp4tag.cpp
acristoffers/SimplePlayer
aba0702901960648fc6602201f85198af87377ed
[ "MIT-0" ]
null
null
null
taglib/mp4tag.cpp
acristoffers/SimplePlayer
aba0702901960648fc6602201f85198af87377ed
[ "MIT-0" ]
null
null
null
/************************************************************************** * copyright : (C) 2007,2011 by Lukáš Lalinský * email : lalinsky@gmail.com **************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tdebug.h> #include <tstring.h> #include <tpropertymap.h> #include "mp4atom.h" #include "mp4tag.h" #include "id3v1genres.h" using namespace TagLib; class MP4::Tag::TagPrivate { public: TagPrivate() : file(0), atoms(0) { } ~TagPrivate() { } TagLib::File *file; Atoms *atoms; ItemListMap items; }; MP4::Tag::Tag() { d = new TagPrivate; } MP4::Tag::Tag(TagLib::File *file, MP4::Atoms *atoms) { d = new TagPrivate; d->file = file; d->atoms = atoms; MP4::Atom *ilst = atoms->find("moov", "udta", "meta", "ilst"); if (!ilst) { // debug("Atom moov.udta.meta.ilst not found."); return; } for (unsigned int i = 0; i < ilst->children.size(); i++) { MP4::Atom *atom = ilst->children[i]; file->seek(atom->offset + 8); if (atom->name == "----") { parseFreeForm(atom, file); } else if ((atom->name == "trkn") || (atom->name == "disk")) { parseIntPair(atom, file); } else if ((atom->name == "cpil") || (atom->name == "pgap") || (atom->name == "pcst") || (atom->name == "hdvd")) { parseBool(atom, file); } else if (atom->name == "tmpo") { parseInt(atom, file); } else if ((atom->name == "tvsn") || (atom->name == "tves") || (atom->name == "cnID") || (atom->name == "sfID") || (atom->name == "atID") || (atom->name == "geID")) { parseUInt(atom, file); } else if (atom->name == "plID") { parseLongLong(atom, file); } else if ((atom->name == "stik") || (atom->name == "rtng") || (atom->name == "akID")) { parseByte(atom, file); } else if (atom->name == "gnre") { parseGnre(atom, file); } else if (atom->name == "covr") { parseCovr(atom, file); } else { parseText(atom, file); } } } MP4::Tag::~Tag() { delete d; } MP4::AtomDataList MP4::Tag::parseData2(MP4::Atom *atom, TagLib::File *file, int expectedFlags, bool freeForm) { AtomDataList result; ByteVector data = file->readBlock(atom->length - 8); int i = 0; unsigned int pos = 0; while (pos < data.size()) { const int length = static_cast<int>(data.toUInt(pos)); ByteVector name = data.mid(pos + 4, 4); const int flags = static_cast<int>(data.toUInt(pos + 8)); if (freeForm && (i < 2)) { if ((i == 0) && (name != "mean")) { debug("MP4: Unexpected atom \"" + name + "\", expecting \"mean\""); return result; } else if ((i == 1) && (name != "name")) { debug("MP4: Unexpected atom \"" + name + "\", expecting \"name\""); return result; } result.append(AtomData(AtomDataType(flags), data.mid(pos + 12, length - 12))); } else { if (name != "data") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\""); return result; } if ((expectedFlags == -1) || (flags == expectedFlags)) { result.append(AtomData(AtomDataType(flags), data.mid(pos + 16, length - 16))); } } pos += length; i++; } return result; } ByteVectorList MP4::Tag::parseData(MP4::Atom *atom, TagLib::File *file, int expectedFlags, bool freeForm) { AtomDataList data = parseData2(atom, file, expectedFlags, freeForm); ByteVectorList result; for (uint i = 0; i < data.size(); i++) { result.append(data[i].data); } return result; } void MP4::Tag::parseInt(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { addItem(atom->name, (int) data[0].toShort()); } } void MP4::Tag::parseUInt(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { addItem(atom->name, data[0].toUInt()); } } void MP4::Tag::parseLongLong(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { addItem(atom->name, data[0].toLongLong()); } } void MP4::Tag::parseByte(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { addItem(atom->name, (uchar) data[0].at(0)); } } void MP4::Tag::parseGnre(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { int idx = (int) data[0].toShort(); if (idx > 0) { addItem("\251gen", StringList(ID3v1::genre(idx - 1))); } } } void MP4::Tag::parseIntPair(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { const int a = data[0].toShort(2U); const int b = data[0].toShort(4U); addItem(atom->name, MP4::Item(a, b)); } } void MP4::Tag::parseBool(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if (data.size()) { bool value = data[0].size() ? data[0][0] != '\0' : false; addItem(atom->name, value); } } void MP4::Tag::parseText(MP4::Atom *atom, TagLib::File *file, int expectedFlags) { ByteVectorList data = parseData(atom, file, expectedFlags); if (data.size()) { StringList value; for (unsigned int i = 0; i < data.size(); i++) { value.append(String(data[i], String::UTF8)); } addItem(atom->name, value); } } void MP4::Tag::parseFreeForm(MP4::Atom *atom, TagLib::File *file) { AtomDataList data = parseData2(atom, file, -1, true); if (data.size() > 2) { String name = "----:" + String(data[0].data, String::UTF8) + ':' + String(data[1].data, String::UTF8); AtomDataType type = data[2].type; for (uint i = 2; i < data.size(); i++) { if (data[i].type != type) { debug("MP4: We currently don't support values with multiple types"); break; } } if (type == TypeUTF8) { StringList value; for (uint i = 2; i < data.size(); i++) { value.append(String(data[i].data, String::UTF8)); } Item item(value); item.setAtomDataType(type); addItem(name, item); } else { ByteVectorList value; for (uint i = 2; i < data.size(); i++) { value.append(data[i].data); } Item item(value); item.setAtomDataType(type); addItem(name, item); } } } void MP4::Tag::parseCovr(MP4::Atom *atom, TagLib::File *file) { MP4::CoverArtList value; ByteVector data = file->readBlock(atom->length - 8); unsigned int pos = 0; while (pos < data.size()) { const int length = static_cast<int>(data.toUInt(pos)); ByteVector name = data.mid(pos + 4, 4); const int flags = static_cast<int>(data.toUInt(pos + 8)); if (name != "data") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\""); break; } if ((flags == TypeJPEG) || (flags == TypePNG) || (flags == TypeBMP) || (flags == TypeGIF) || (flags == TypeImplicit)) { value.append(MP4::CoverArt(MP4::CoverArt::Format(flags), data.mid(pos + 16, length - 16))); } else { debug("MP4: Unknown covr format " + String::number(flags)); } pos += length; } if (value.size() > 0) { addItem(atom->name, value); } } ByteVector MP4::Tag::padIlst(const ByteVector &data, int length) { if (length == -1) { length = ((data.size() + 1023) & ~1023) - data.size(); } return renderAtom("free", ByteVector(length, '\1')); } ByteVector MP4::Tag::renderAtom(const ByteVector &name, const ByteVector &data) { return ByteVector::fromUInt(data.size() + 8) + name + data; } ByteVector MP4::Tag::renderData(const ByteVector &name, int flags, const ByteVectorList &data) { ByteVector result; for (unsigned int i = 0; i < data.size(); i++) { result.append(renderAtom("data", ByteVector::fromUInt(flags) + ByteVector(4, '\0') + data[i])); } return renderAtom(name, result); } ByteVector MP4::Tag::renderBool(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(1, item.toBool() ? '\1' : '\0')); return renderData(name, TypeInteger, data); } ByteVector MP4::Tag::renderInt(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector::fromShort(item.toInt())); return renderData(name, TypeInteger, data); } ByteVector MP4::Tag::renderUInt(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector::fromUInt(item.toUInt())); return renderData(name, TypeInteger, data); } ByteVector MP4::Tag::renderLongLong(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector::fromLongLong(item.toLongLong())); return renderData(name, TypeInteger, data); } ByteVector MP4::Tag::renderByte(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(1, item.toByte())); return renderData(name, TypeInteger, data); } ByteVector MP4::Tag::renderIntPair(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(2, '\0') + ByteVector::fromShort(item.toIntPair().first) + ByteVector::fromShort(item.toIntPair().second) + ByteVector(2, '\0')); return renderData(name, TypeImplicit, data); } ByteVector MP4::Tag::renderIntPairNoTrailing(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(2, '\0') + ByteVector::fromShort(item.toIntPair().first) + ByteVector::fromShort(item.toIntPair().second)); return renderData(name, TypeImplicit, data); } ByteVector MP4::Tag::renderText(const ByteVector &name, MP4::Item &item, int flags) { ByteVectorList data; StringList value = item.toStringList(); for (unsigned int i = 0; i < value.size(); i++) { data.append(value[i].data(String::UTF8)); } return renderData(name, flags, data); } ByteVector MP4::Tag::renderCovr(const ByteVector &name, MP4::Item &item) { ByteVector data; MP4::CoverArtList value = item.toCoverArtList(); for (unsigned int i = 0; i < value.size(); i++) { data.append(renderAtom("data", ByteVector::fromUInt(value[i].format()) + ByteVector(4, '\0') + value[i].data())); } return renderAtom(name, data); } ByteVector MP4::Tag::renderFreeForm(const String &name, MP4::Item &item) { StringList header = StringList::split(name, ":"); if (header.size() != 3) { debug("MP4: Invalid free-form item name \"" + name + "\""); return ByteVector::null; } ByteVector data; data.append(renderAtom("mean", ByteVector::fromUInt(0) + header[1].data(String::UTF8))); data.append(renderAtom("name", ByteVector::fromUInt(0) + header[2].data(String::UTF8))); AtomDataType type = item.atomDataType(); if (type == TypeUndefined) { if (!item.toStringList().isEmpty()) { type = TypeUTF8; } else { type = TypeImplicit; } } if (type == TypeUTF8) { StringList value = item.toStringList(); for (unsigned int i = 0; i < value.size(); i++) { data.append(renderAtom("data", ByteVector::fromUInt(type) + ByteVector(4, '\0') + value[i].data(String::UTF8))); } } else { ByteVectorList value = item.toByteVectorList(); for (unsigned int i = 0; i < value.size(); i++) { data.append(renderAtom("data", ByteVector::fromUInt(type) + ByteVector(4, '\0') + value[i])); } } return renderAtom("----", data); } bool MP4::Tag::save() { ByteVector data; for (MP4::ItemListMap::Iterator i = d->items.begin(); i != d->items.end(); i++) { const String name = i->first; if (name.startsWith("----")) { data.append(renderFreeForm(name, i->second)); } else if (name == "trkn") { data.append(renderIntPair(name.data(String::Latin1), i->second)); } else if (name == "disk") { data.append(renderIntPairNoTrailing(name.data(String::Latin1), i->second)); } else if ((name == "cpil") || (name == "pgap") || (name == "pcst") || (name == "hdvd")) { data.append(renderBool(name.data(String::Latin1), i->second)); } else if (name == "tmpo") { data.append(renderInt(name.data(String::Latin1), i->second)); } else if ((name == "tvsn") || (name == "tves") || (name == "cnID") || (name == "sfID") || (name == "atID") || (name == "geID")) { data.append(renderUInt(name.data(String::Latin1), i->second)); } else if (name == "plID") { data.append(renderLongLong(name.data(String::Latin1), i->second)); } else if ((name == "stik") || (name == "rtng") || (name == "akID")) { data.append(renderByte(name.data(String::Latin1), i->second)); } else if (name == "covr") { data.append(renderCovr(name.data(String::Latin1), i->second)); } else if (name.size() == 4) { data.append(renderText(name.data(String::Latin1), i->second)); } else { debug("MP4: Unknown item name \"" + name + "\""); } } data = renderAtom("ilst", data); AtomList path = d->atoms->path("moov", "udta", "meta", "ilst"); if (path.size() == 4) { saveExisting(data, path); } else { saveNew(data); } return true; } void MP4::Tag::updateParents(AtomList &path, long delta, int ignore) { for (unsigned int i = 0; i < path.size() - ignore; i++) { d->file->seek(path[i]->offset); long size = d->file->readBlock(4).toUInt(); // 64-bit if (size == 1) { d->file->seek(4, File::Current); // Skip name long long longSize = d->file->readBlock(8).toLongLong(); // Seek the offset of the 64-bit size d->file->seek(path[i]->offset + 8); d->file->writeBlock(ByteVector::fromLongLong(longSize + delta)); } // 32-bit else { d->file->seek(path[i]->offset); d->file->writeBlock(ByteVector::fromUInt(size + delta)); } } } void MP4::Tag::updateOffsets(long delta, long offset) { MP4::Atom *moov = d->atoms->find("moov"); if (moov) { MP4::AtomList stco = moov->findall("stco", true); for (unsigned int i = 0; i < stco.size(); i++) { MP4::Atom *atom = stco[i]; if (atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 12); ByteVector data = d->file->readBlock(atom->length - 12); unsigned int count = data.toUInt(); d->file->seek(atom->offset + 16); uint pos = 4; while (count--) { long o = static_cast<long>(data.toUInt(pos)); if (o > offset) { o += delta; } d->file->writeBlock(ByteVector::fromUInt(o)); pos += 4; } } MP4::AtomList co64 = moov->findall("co64", true); for (unsigned int i = 0; i < co64.size(); i++) { MP4::Atom *atom = co64[i]; if (atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 12); ByteVector data = d->file->readBlock(atom->length - 12); unsigned int count = data.toUInt(); d->file->seek(atom->offset + 16); uint pos = 4; while (count--) { long long o = data.toLongLong(pos); if (o > offset) { o += delta; } d->file->writeBlock(ByteVector::fromLongLong(o)); pos += 8; } } } MP4::Atom *moof = d->atoms->find("moof"); if (moof) { MP4::AtomList tfhd = moof->findall("tfhd", true); for (unsigned int i = 0; i < tfhd.size(); i++) { MP4::Atom *atom = tfhd[i]; if (atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 9); ByteVector data = d->file->readBlock(atom->length - 9); const unsigned int flags = data.toUInt(0, 3, true); if (flags & 1) { long long o = data.toLongLong(7U); if (o > offset) { o += delta; } d->file->seek(atom->offset + 16); d->file->writeBlock(ByteVector::fromLongLong(o)); } } } } void MP4::Tag::saveNew(ByteVector &data) { data = renderAtom("meta", TagLib::ByteVector(4, '\0') + renderAtom("hdlr", TagLib::ByteVector(8, '\0') + TagLib::ByteVector("mdirappl") + TagLib::ByteVector(9, '\0')) + data + padIlst(data)); AtomList path = d->atoms->path("moov", "udta"); if (path.size() != 2) { path = d->atoms->path("moov"); data = renderAtom("udta", data); } long offset = path[path.size() - 1]->offset + 8; d->file->insert(data, offset, 0); updateParents(path, data.size()); updateOffsets(data.size(), offset); } void MP4::Tag::saveExisting(ByteVector &data, AtomList &path) { MP4::Atom *ilst = path[path.size() - 1]; long offset = ilst->offset; long length = ilst->length; MP4::Atom *meta = path[path.size() - 2]; AtomList::Iterator index = meta->children.find(ilst); // check if there is an atom before 'ilst', and possibly use it as padding if (index != meta->children.begin()) { AtomList::Iterator prevIndex = index; prevIndex--; MP4::Atom *prev = *prevIndex; if (prev->name == "free") { offset = prev->offset; length += prev->length; } } // check if there is an atom after 'ilst', and possibly use it as padding AtomList::Iterator nextIndex = index; nextIndex++; if (nextIndex != meta->children.end()) { MP4::Atom *next = *nextIndex; if (next->name == "free") { length += next->length; } } long delta = data.size() - length; if ((delta > 0) || ((delta < 0) && (delta > -8))) { data.append(padIlst(data)); delta = data.size() - length; } else if (delta < 0) { data.append(padIlst(data, -delta - 8)); delta = 0; } d->file->insert(data, offset, length); if (delta) { updateParents(path, delta, 1); updateOffsets(delta, offset); } } String MP4::Tag::title() const { if (d->items.contains("\251nam")) { return d->items["\251nam"].toStringList().toString(", "); } return String::null; } String MP4::Tag::artist() const { if (d->items.contains("\251ART")) { return d->items["\251ART"].toStringList().toString(", "); } return String::null; } String MP4::Tag::album() const { if (d->items.contains("\251alb")) { return d->items["\251alb"].toStringList().toString(", "); } return String::null; } String MP4::Tag::comment() const { if (d->items.contains("\251cmt")) { return d->items["\251cmt"].toStringList().toString(", "); } return String::null; } String MP4::Tag::genre() const { if (d->items.contains("\251gen")) { return d->items["\251gen"].toStringList().toString(", "); } return String::null; } unsigned int MP4::Tag::year() const { if (d->items.contains("\251day")) { return d->items["\251day"].toStringList().toString().toInt(); } return 0; } unsigned int MP4::Tag::track() const { if (d->items.contains("trkn")) { return d->items["trkn"].toIntPair().first; } return 0; } void MP4::Tag::setTitle(const String &value) { d->items["\251nam"] = StringList(value); } void MP4::Tag::setArtist(const String &value) { d->items["\251ART"] = StringList(value); } void MP4::Tag::setAlbum(const String &value) { d->items["\251alb"] = StringList(value); } void MP4::Tag::setComment(const String &value) { d->items["\251cmt"] = StringList(value); } void MP4::Tag::setGenre(const String &value) { d->items["\251gen"] = StringList(value); } void MP4::Tag::setYear(uint value) { d->items["\251day"] = StringList(String::number(value)); } void MP4::Tag::setTrack(uint value) { d->items["trkn"] = MP4::Item(value, 0); } MP4::ItemListMap &MP4::Tag::itemListMap() { return d->items; } static const char *keyTranslation[][2] = { { "\251nam", "TITLE" }, { "\251ART", "ARTIST" }, { "\251alb", "ALBUM" }, { "\251cmt", "COMMENT" }, { "\251gen", "GENRE" }, { "\251day", "DATE" }, { "\251wrt", "COMPOSER" }, { "\251grp", "GROUPING" }, { "trkn", "TRACKNUMBER" }, { "disk", "DISCNUMBER" }, { "cpil", "COMPILATION" }, { "tmpo", "BPM" }, { "cprt", "COPYRIGHT" }, { "\251lyr", "LYRICS" }, { "\251too", "ENCODEDBY" }, { "soal", "ALBUMSORT" }, { "soaa", "ALBUMARTISTSORT" }, { "soar", "ARTISTSORT" }, { "sonm", "TITLESORT" }, { "soco", "COMPOSERSORT" }, { "sosn", "SHOWSORT" }, { "----:com.apple.iTunes:MusicBrainz Track Id", "MUSICBRAINZ_TRACKID" }, { "----:com.apple.iTunes:MusicBrainz Artist Id", "MUSICBRAINZ_ARTISTID" }, { "----:com.apple.iTunes:MusicBrainz Album Id", "MUSICBRAINZ_ALBUMID" }, { "----:com.apple.iTunes:MusicBrainz Album Artist Id", "MUSICBRAINZ_ALBUMARTISTID" }, { "----:com.apple.iTunes:MusicBrainz Release Group Id", "MUSICBRAINZ_RELEASEGROUPID" }, { "----:com.apple.iTunes:MusicBrainz Work Id", "MUSICBRAINZ_WORKID" }, { "----:com.apple.iTunes:ASIN", "ASIN" }, { "----:com.apple.iTunes:LABEL", "LABEL" }, { "----:com.apple.iTunes:LYRICIST", "LYRICIST" }, { "----:com.apple.iTunes:CONDUCTOR", "CONDUCTOR" }, { "----:com.apple.iTunes:REMIXER", "REMIXER" }, { "----:com.apple.iTunes:ENGINEER", "ENGINEER" }, { "----:com.apple.iTunes:PRODUCER", "PRODUCER" }, { "----:com.apple.iTunes:DJMIXER", "DJMIXER" }, { "----:com.apple.iTunes:MIXER", "MIXER" }, { "----:com.apple.iTunes:SUBTITLE", "SUBTITLE" }, { "----:com.apple.iTunes:DISCSUBTITLE", "DISCSUBTITLE" }, { "----:com.apple.iTunes:MOOD", "MOOD" }, { "----:com.apple.iTunes:ISRC", "ISRC" }, { "----:com.apple.iTunes:CATALOGNUMBER", "CATALOGNUMBER" }, { "----:com.apple.iTunes:BARCODE", "BARCODE" }, { "----:com.apple.iTunes:SCRIPT", "SCRIPT" }, { "----:com.apple.iTunes:LANGUAGE", "LANGUAGE" }, { "----:com.apple.iTunes:LICENSE", "LICENSE" }, { "----:com.apple.iTunes:MEDIA", "MEDIA" }, }; PropertyMap MP4::Tag::properties() const { static Map<String, String> keyMap; if (keyMap.isEmpty()) { int numKeys = sizeof(keyTranslation) / sizeof(keyTranslation[0]); for (int i = 0; i < numKeys; i++) { keyMap[keyTranslation[i][0]] = keyTranslation[i][1]; } } PropertyMap props; MP4::ItemListMap::ConstIterator it = d->items.begin(); for ( ; it != d->items.end(); ++it) { if (keyMap.contains(it->first)) { String key = keyMap[it->first]; if ((key == "TRACKNUMBER") || (key == "DISCNUMBER")) { MP4::Item::IntPair ip = it->second.toIntPair(); String value = String::number(ip.first); if (ip.second) { value += "/" + String::number(ip.second); } props[key] = value; } else if (key == "BPM") { props[key] = String::number(it->second.toInt()); } else if (key == "COMPILATION") { props[key] = String::number(it->second.toBool()); } else { props[key] = it->second.toStringList(); } } else { props.unsupportedData().append(it->first); } } return props; } void MP4::Tag::removeUnsupportedProperties(const StringList &props) { StringList::ConstIterator it = props.begin(); for ( ; it != props.end(); ++it) { d->items.erase(*it); } } PropertyMap MP4::Tag::setProperties(const PropertyMap &props) { static Map<String, String> reverseKeyMap; if (reverseKeyMap.isEmpty()) { int numKeys = sizeof(keyTranslation) / sizeof(keyTranslation[0]); for (int i = 0; i < numKeys; i++) { reverseKeyMap[keyTranslation[i][1]] = keyTranslation[i][0]; } } PropertyMap origProps = properties(); PropertyMap::ConstIterator it = origProps.begin(); for ( ; it != origProps.end(); ++it) { if (!props.contains(it->first) || props[it->first].isEmpty()) { d->items.erase(reverseKeyMap[it->first]); } } PropertyMap ignoredProps; it = props.begin(); for ( ; it != props.end(); ++it) { if (reverseKeyMap.contains(it->first)) { String name = reverseKeyMap[it->first]; if ((it->first == "TRACKNUMBER") || (it->first == "DISCNUMBER")) { int first = 0, second = 0; StringList parts = StringList::split(it->second.front(), "/"); if (parts.size() > 0) { first = parts[0].toInt(); if (parts.size() > 1) { second = parts[1].toInt(); } d->items[name] = MP4::Item(first, second); } } else if (it->first == "BPM") { int value = it->second.front().toInt(); d->items[name] = MP4::Item(value); } else if (it->first == "COMPILATION") { bool value = (it->second.front().toInt() != 0); d->items[name] = MP4::Item(value); } else { d->items[name] = it->second; } } else { ignoredProps.insert(it->first, it->second); } } return ignoredProps; } void MP4::Tag::addItem(const String &name, const Item &value) { if (!d->items.contains(name)) { d->items.insert(name, value); } else { debug("MP4: Ignoring duplicate atom \"" + name + "\""); } }
34.479821
134
0.486897
5a9ee72d815a1f4b94f13c9cef4bd3b03565c5bd
3,060
cpp
C++
Algorithms-Library/BinTree.cpp
huozk0804/CPlusPlusArithmeticProject
75edbec76304a74b8d8bfa4166272ac8c08c20cf
[ "MIT" ]
1
2020-04-28T16:21:45.000Z
2020-04-28T16:21:45.000Z
Algorithms-Library/BinTree.cpp
huozk0804/CPlusPlusArithmeticProject
75edbec76304a74b8d8bfa4166272ac8c08c20cf
[ "MIT" ]
null
null
null
Algorithms-Library/BinTree.cpp
huozk0804/CPlusPlusArithmeticProject
75edbec76304a74b8d8bfa4166272ac8c08c20cf
[ "MIT" ]
null
null
null
#include"Tree.h" treeNode* BinTree::CreateTree(char* str) { treeNode* st[100]; treeNode* p = NULL; int top, k, j = 0; top = -1; char ch = str[j]; treeNode* b = NULL; while (ch != '\0') { switch (ch) { case'(': top++; st[top] = p; k = 1; break; case')': top--; break; case',': k = 2; break; default: p = (treeNode*)malloc(sizeof(treeNode)); p->value = ch; p->lchild = p->rchild = NULL; if (b == NULL) b = p; else { switch (k) { case 1: st[top]->lchild = p; break; case 2: st[top]->rchild = p; break; default: break; } } break; } } return b; } treeNode* BinTree::CreateTree(treeNode* bintree) { treeNode* st[100]; treeNode* s; int front, rear; char ch; ch = getchar(); bintree = NULL; front = 1; rear = 0; while (ch != '#') { s = NULL; if (ch != '@') { s = (treeNode*)malloc(sizeof(treeNode)); s->value = ch; s->lchild = s->rchild = NULL; } rear++; st[rear] = s; if (rear == 1) bintree = s; else { if (s != NULL && st[front] != NULL) { if (rear % 2 == 0) st[front]->lchild = s; else st[front]->rchild = s; if (rear % 2 != 0) front++; } ch = getchar(); } return bintree; } } void BinTree::Preorder(treeNode* bintree) { if (bintree != NULL) { printf("%c", bintree->value); Preorder(bintree->lchild); Preorder(bintree->rchild); } } void BinTree::Preorder1(treeNode* bintree) { stack<treeNode*> s; s.push(bintree); while (!s.empty()) { bintree = s.top(); s.pop(); if (bintree != NULL) { printf("%c", bintree->value); s.push(bintree->rchild); s.push(bintree->lchild); } } } void BinTree::Inorder(treeNode* bintree) { if (bintree != NULL) { Inorder(bintree->lchild); printf("%c", bintree->value); Inorder(bintree->rchild); } } void BinTree::Inorder1(treeNode* bintree) { stack<treeNode*> s; treeNode* p; s.push(bintree); while (!s.empty()) { while (s.top()) s.push(s.top()->lchild); s.pop(); p = s.top(); if (!s.empty()) { printf("%c", s.top()->value); p = s.top(); s.pop(); s.push(p->rchild); } } } void BinTree::Inorder2(treeNode* bintree) { treeNode* st[100]; int top = 0; st[top] = bintree; do { while (st[100] != NULL) { top = top + 1; st[top] = st[top - 1]->lchild; } top = top - 1; if (top >= 0) { printf("%c", st[top]->value); st[top] = st[top]->rchild; } } while (top != -1); } void BinTree::Postorder(treeNode* bintree) { if (bintree != NULL) { Postorder(bintree->lchild); Postorder(bintree->rchild); printf("%c", bintree->value); } } void BinTree::TransLevel(treeNode* bt) { queue<treeNode*> q; if (bt == NULL)return; else { printf("%c", bt->value); q.push(bt); while (!q.empty()) { bt = q.front(); q.pop(); if (bt->lchild != NULL) { printf("%c", bt->lchild->value); q.push(bt->lchild); } if (bt->rchild != NULL) { printf("%c", bt->rchild->value); q.push(bt->rchild); } } } }
15.773196
50
0.529085
5aa0f5a538f4ade6671944c5a38053e19c403cf2
12,382
tpp
C++
src/sdm/core/joint.tpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/core/joint.tpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/core/joint.tpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
#define DEFINE_JOINT(CLASS) \ /* This macro allow to define a specific joint on std::shared_ptr<CLASS> that inherites from CLASS. */ \ template <> \ class Joint<std::shared_ptr<CLASS>> : public CLASS, public std::vector<std::shared_ptr<CLASS>>, public Function<number, std::shared_ptr<CLASS>> \ { \ public: \ using value_type = std::shared_ptr<CLASS>; \ \ Joint() {} \ Joint(std::size_t size) : std::vector<std::shared_ptr<CLASS>>(size) {} \ Joint(std::size_t size, std::shared_ptr<CLASS> default_value) : std::vector<std::shared_ptr<CLASS>>(size, default_value) {} \ Joint(const std::vector<std::shared_ptr<CLASS>> &joint_item) : std::vector<std::shared_ptr<CLASS>>(joint_item) {} \ Joint(const std::vector<number> &, const std::vector<std::shared_ptr<CLASS>> &joint_item) : std::vector<std::shared_ptr<CLASS>>(joint_item) {} \ Joint(std::initializer_list<std::shared_ptr<CLASS>> list_values) : std::vector<std::shared_ptr<CLASS>>(list_values) {} \ \ const std::shared_ptr<CLASS> &get(const number &index) const \ { \ return this->at(index); \ } \ \ number getNumAgents() const \ { \ return this->size(); \ } \ \ template <typename TOutput> \ std::shared_ptr<Joint<std::shared_ptr<TOutput>>> toJoint() \ { \ auto joint_output = std::make_shared<Joint<std::shared_ptr<TOutput>>>(); \ \ for (const auto &item : *this) \ { \ joint_output->push_back(std::static_pointer_cast<TOutput>(item)); \ } \ \ return joint_output; \ } \ \ std::shared_ptr<CLASS> operator()(const number &i) \ { \ return (*this)[i]; \ } \ \ std::string str() const \ { \ std::ostringstream res; \ res << "[" << this->getNumAgents() << "]("; \ if (this->getNumAgents() > 0) \ { \ number ag; \ for (ag = 0; ag < this->getNumAgents() - 1; ++ag) \ { \ res << this->get(ag)->str() << ", "; \ } \ res << this->get(ag)->str(); \ } \ res << ")"; \ return res.str(); \ } \ friend std::ostream &operator<<(std::ostream &os, const Joint<std::shared_ptr<CLASS>> &joint_action) \ { \ os << joint_action.str(); \ return os; \ } \ }; namespace sdm { // Specialisation for the Joint Action DEFINE_JOINT(Item); // Specialisation for the Joint Action DEFINE_JOINT(Action); // Specialisation for the Joint State DEFINE_JOINT(State); // Specialisation for the Joint Observation DEFINE_JOINT(Observation); template <typename T> Joint<T>::Joint() {} template <typename T> Joint<T>::Joint(std::size_t size) : std::vector<T>(size) {} template <typename T> Joint<T>::Joint(std::size_t size, T default_value) : std::vector<T>(size, default_value) {} template <typename T> Joint<T>::Joint(const std::vector<T> &joint_item) : std::vector<T>(joint_item) {} template <typename T> Joint<T>::Joint(const std::vector<number> &, const std::vector<T> &joint_item) : std::vector<T>(joint_item) {} template <typename T> Joint<T>::Joint(std::initializer_list<T> list_values) : std::vector<T>(list_values) {} template <typename T> Joint<T>::~Joint() {} template <typename T> const T &Joint<T>::get(const number &index) const { return this->at(index); } template <typename T> number Joint<T>::getNumAgents() const { return this->size(); } template <typename T> template <typename TOutput> std::shared_ptr<Joint<std::shared_ptr<TOutput>>> Joint<T>::toJoint() { auto joint_output = std::make_shared<Joint<std::shared_ptr<TOutput>>>(); for (const auto &item : *this) { joint_output->push_back(std::static_pointer_cast<TOutput>(item)); } return joint_output; } template <typename T> T Joint<T>::operator()(const number &i) { return (*this)[i]; } template <typename T> std::string Joint<T>::str() const { std::ostringstream res; res << "[" << this->getNumAgents() << "]("; if (this->getNumAgents() > 0) { number ag; for (ag = 0; ag < this->getNumAgents() - 1; ++ag) { res << this->get(ag) << ", "; } res << this->get(ag); } res << ")"; return res.str(); } } // namespace sdm namespace std { template <typename T> struct hash<sdm::Joint<T>> { typedef sdm::Joint<T> argument_type; typedef std::size_t result_type; result_type operator()(argument_type const &in) const { return std::hash<std::vector<T>>()(in); } }; }
73.702381
194
0.220966
5aa87fe1c04f1ac8be1528f7d60a790f841cc03d
1,330
cpp
C++
xenon/src/xenon/core/asset.cpp
Neathan/Xenon
d376337dd086ac8ccb84cbaf97b6537ad6dda8a4
[ "MIT" ]
1
2021-09-21T23:37:22.000Z
2021-09-21T23:37:22.000Z
xenon/src/xenon/core/asset.cpp
Neathan/Xenon
d376337dd086ac8ccb84cbaf97b6537ad6dda8a4
[ "MIT" ]
null
null
null
xenon/src/xenon/core/asset.cpp
Neathan/Xenon
d376337dd086ac8ccb84cbaf97b6537ad6dda8a4
[ "MIT" ]
null
null
null
#include "asset.h" #include "xenon/core/log.h" namespace xe { void copyAssetMetaRuntimeData(const Asset* source, Asset* target) { target->metadata.handle = source->metadata.handle; target->metadata.type = source->metadata.type; target->metadata.path = source->metadata.path; target->runtimeData.loaded = source->runtimeData.loaded; target->runtimeData.parent = source->runtimeData.parent; target->runtimeData.filename = source->runtimeData.filename; target->runtimeData.extension = source->runtimeData.extension; } AssetType getAssetTypeFromPath(const std::string& path) { auto index = path.find_last_of('.'); if (index != std::string::npos) { std::string extension = path.substr(index + 1); // Images if (extension == "png") return AssetType::Texture; if (extension == "jpg") return AssetType::Texture; if (extension == "jpeg") return AssetType::Texture; if (extension == "tga") return AssetType::Texture; if (extension == "bmp") return AssetType::Texture; if (extension == "psd") return AssetType::Texture; if (extension == "ktx") return AssetType::Texture; // Models if (extension == "glb") return AssetType::Model; if (extension == "gltf") return AssetType::Model; } XE_LOG_TRACE_F("ASSET: No extension match for: {}", path); return AssetType::None; } }
32.439024
68
0.696241
5aab948085ff5abeee86e7106a25b873fbf0d801
5,641
cc
C++
src/outlinerdebug.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
4
2021-09-02T16:52:23.000Z
2022-02-07T16:39:50.000Z
src/outlinerdebug.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
87
2021-09-12T06:09:57.000Z
2022-02-15T00:05:43.000Z
src/outlinerdebug.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
1
2021-09-28T21:38:30.000Z
2021-09-28T21:38:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // // CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR // CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR // CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR // CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R // CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R // // CAVE OUTLINER -- Cave 3D model processing software // // Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information. // /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // Includes /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #include <stdarg.h> #include <cassert> #include <string.h> #include <stdlib.h> #include <iostream> #include "outlinertypes.hh" #include "outlinerconstants.hh" #include "outlinerdebug.hh" /////////////////////////////////////////////////////////////////////////////////////////////// // Local variables //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// static bool info = 0; static bool debug = 0; static bool deepdebug = 0; static bool deepdeepdebug = 0; /////////////////////////////////////////////////////////////////////////////////////////////// // Initialization ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void debuginit(bool infoSet, bool debugSet, bool deepdebugSet, bool deepdeepdebugSet) { info = infoSet; debug = debugSet; deepdebug = deepdebugSet; deepdeepdebug = deepdeepdebugSet; } /////////////////////////////////////////////////////////////////////////////////////////////// // Debug and output functions ///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// __attribute__((__format__ (__printf__, 1, 0))) void debugf(const char* format, ...) { assert(format != 0); if (debug) { va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_DEBUGPREFIX; std::cerr << buf; std::cerr << "\n"; std::cerr.flush(); } } __attribute__((__format__ (__printf__, 1, 0))) void deepdebugf(const char* format, ...) { assert(format != 0); if (deepdebug) { va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_DEBUGPREFIX; std::cerr << buf; std::cerr << "\n"; std::cerr.flush(); } } __attribute__((__format__ (__printf__, 1, 0))) void deepdeepdebugf(const char* format, ...) { assert(format != 0); if (deepdeepdebug) { va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_DEBUGPREFIX; std::cerr << buf; std::cerr << "\n"; std::cerr.flush(); } } __attribute__((__format__ (__printf__, 1, 0))) void warnf(const char* format, ...) { assert(format != 0); va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_WARNPREFIX; std::cerr << buf; std::cerr << " -- exit\n"; std::cerr.flush(); } __attribute__((__format__ (__printf__, 1, 0))) void errf(const char* format, ...) { assert(format != 0); va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_ERRPREFIX; std::cerr << buf; std::cerr << " -- exit\n"; std::cerr.flush(); } __attribute__((__format__ (__printf__, 1, 0))) void fatalf(const char* format, ...) { assert(format != 0); va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cerr << OUTLINER_ERRPREFIX; std::cerr << buf; std::cerr << " -- exit\n"; std::cerr.flush(); exit(1); } __attribute__((__format__ (__printf__, 1, 0))) void infof(const char* format, ...) { assert(format != 0); if (info) { va_list args; char buf[500]; memset(buf,0,sizeof(buf)); va_start (args, format); vsnprintf(buf,sizeof(buf)-1,format,args); va_end (args); std::cout << OUTLINER_INFOPREFIX; std::cout << buf; std::cout << "\n"; std::cout.flush(); } }
27.120192
95
0.423329
5aad100adabbe634edb18b10d83f62667ad7bed0
478
cpp
C++
tests/memory_resource/memory_resource_mini.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/memory_resource/memory_resource_mini.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/memory_resource/memory_resource_mini.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#include "tests/memory_resource/memory_resource_mini.hpp" #include "tests/memory_resource/memory_resource_fwd.hpp" //------------------------------------------------------------------------------ namespace memory_resource_tests { //------------------------------------------------------------------------------ void run_mini() { TestClass testObj; int i = testObj.getInt(); (void)i; } //------------------------------------------------------------------------------ }
22.761905
80
0.374477
5ab002f951bce3ed0377049fe0cc750d48f79d99
4,303
ipp
C++
src/lib/diagrams/bdd_manager_creator.ipp
MichalMrena/DecisionDiagrams
e2e9b949405bd2c1c93ba32c151b60a78620afec
[ "MIT" ]
1
2022-03-17T12:55:30.000Z
2022-03-17T12:55:30.000Z
src/lib/diagrams/bdd_manager_creator.ipp
MichalMrena/DecisionDiagrams
e2e9b949405bd2c1c93ba32c151b60a78620afec
[ "MIT" ]
null
null
null
src/lib/diagrams/bdd_manager_creator.ipp
MichalMrena/DecisionDiagrams
e2e9b949405bd2c1c93ba32c151b60a78620afec
[ "MIT" ]
null
null
null
#ifndef MIX_DD_bdd_manager_HPP #include "../bdd_manager.hpp" #endif namespace teddy { template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::variable_not (index_t const i) -> bdd_t { return this->negate(this->variable(i)); } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::operator() (index_t const i, NOT) -> bdd_t { return this->variable_not(i); } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::variables (std::vector<bool_var> const& vars) -> std::vector<bdd_t> { return utils::fmap(vars, [this](auto const var) { return var.complemented ? this->variable_not(var.index) : this->variable(var.index); }); } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::product (std::vector<bool_var> const& vars) -> bdd_t { return this->product(std::begin(vars), std::end(vars)); } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::product (bool_cube const& cube) -> bdd_t { auto const varCount = cube.size(); auto const falseLeaf = base::manager_.terminal_vertex(0); auto const trueLeaf = base::manager_.terminal_vertex(1); auto index = static_cast<index_t>(varCount - 1); while (index != static_cast<index_t>(-1) && cube.get(index) > 1) { --index; } if (index == static_cast<index_t>(-1)) { return this->constant(0); } auto prevVertex = 0 == cube.get(index) ? base::manager_.internal_vertex(index, {trueLeaf, falseLeaf}) : base::manager_.internal_vertex(index, {falseLeaf, trueLeaf}); while (index > 0) { --index; auto const val = cube.get(index); if (val > 1) { continue; } prevVertex = 0 == val ? base::manager_.internal_vertex(index, {prevVertex, falseLeaf}) : base::manager_.internal_vertex(index, {falseLeaf, prevVertex}); } return bdd_t {prevVertex}; } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::from_pla (pla_file const& file, fold_e const mm) -> std::vector<bdd_t> { auto const& plaLines = file.get_lines(); auto const lineCount = file.line_count(); auto const functionCount = file.function_count(); // Create a diagram for each function. auto functionDiagrams = utils::vector<bdd_t>(functionCount); for (auto fi = 0u; fi < functionCount; ++fi) { // First create a diagram for each product. auto productDiagrams = utils::vector<bdd_t>(lineCount); for (auto li = 0u; li < lineCount; ++li) { // We are doing SOP so we are only interested in functions with value 1. if (plaLines[li].fVals.get(fi) == 1) { productDiagrams.emplace_back(this->product(plaLines[li].cube)); } } // In this case we just have a constant function. if (productDiagrams.empty()) { productDiagrams.emplace_back(this->constant(0)); } // Then merge products using OR. functionDiagrams.emplace_back(this->or_merge(productDiagrams, mm)); } return functionDiagrams; } template<class VertexData, class ArcData> auto bdd_manager<VertexData, ArcData>::or_merge (std::vector<bdd_t>& diagrams, fold_e mm) -> bdd_t { switch (mm) { case fold_e::tree: return this->template tree_fold<OR>(std::begin(diagrams), std::end(diagrams)); case fold_e::left: return this->template left_fold<OR>(std::begin(diagrams), std::end(diagrams)); default: throw std::runtime_error("Non-exhaustive enum switch."); } } }
33.617188
94
0.558912
5ab31ae91b7618b6ae521ea0638acdea9cb15ef3
34,408
cpp
C++
OpenHome/Net/Bindings/Cpp/ControlPoint/Proxies/CpAvOpenhomeOrgMediaServer1Std.cpp
kmuellerjones/ohNetGenerated
2bb32625c9ab49e17ba84ec40cc4046ec09182f3
[ "MIT" ]
1
2017-01-06T15:34:03.000Z
2017-01-06T15:34:03.000Z
OpenHome/Net/Bindings/Cpp/ControlPoint/Proxies/CpAvOpenhomeOrgMediaServer1Std.cpp
kmuellerjones/ohNetGenerated
2bb32625c9ab49e17ba84ec40cc4046ec09182f3
[ "MIT" ]
5
2016-01-05T09:47:15.000Z
2018-12-16T14:07:35.000Z
OpenHome/Net/Bindings/Cpp/ControlPoint/Proxies/CpAvOpenhomeOrgMediaServer1Std.cpp
kmuellerjones/ohNetGenerated
2bb32625c9ab49e17ba84ec40cc4046ec09182f3
[ "MIT" ]
6
2015-04-08T18:50:36.000Z
2021-04-14T13:41:15.000Z
#include "CpAvOpenhomeOrgMediaServer1.h" #include <OpenHome/Net/Core/CpProxy.h> #include <OpenHome/Net/Private/CpiService.h> #include <OpenHome/Private/Thread.h> #include <OpenHome/Net/Private/AsyncPrivate.h> #include <OpenHome/Buffer.h> #include <OpenHome/Net/Cpp/CpDevice.h> #include <OpenHome/Net/Private/CpiDevice.h> #include <string> using namespace OpenHome; using namespace OpenHome::Net; class SyncManufacturerAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncManufacturerAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncManufacturerAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; std::string& iName; std::string& iInfo; std::string& iUrl; std::string& iImageUri; }; SyncManufacturerAvOpenhomeOrgMediaServer1Cpp::SyncManufacturerAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) : iService(aProxy) , iName(aName) , iInfo(aInfo) , iUrl(aUrl) , iImageUri(aImageUri) { } void SyncManufacturerAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndManufacturer(aAsync, iName, iInfo, iUrl, iImageUri); } class SyncModelAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncModelAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncModelAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; std::string& iName; std::string& iInfo; std::string& iUrl; std::string& iImageUri; }; SyncModelAvOpenhomeOrgMediaServer1Cpp::SyncModelAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) : iService(aProxy) , iName(aName) , iInfo(aInfo) , iUrl(aUrl) , iImageUri(aImageUri) { } void SyncModelAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndModel(aAsync, iName, iInfo, iUrl, iImageUri); } class SyncProductAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncProductAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncProductAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; std::string& iName; std::string& iInfo; std::string& iUrl; std::string& iImageUri; }; SyncProductAvOpenhomeOrgMediaServer1Cpp::SyncProductAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) : iService(aProxy) , iName(aName) , iInfo(aInfo) , iUrl(aUrl) , iImageUri(aImageUri) { } void SyncProductAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndProduct(aAsync, iName, iInfo, iUrl, iImageUri); } class SyncAttributesAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncAttributesAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aValue); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncAttributesAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; std::string& iValue; }; SyncAttributesAvOpenhomeOrgMediaServer1Cpp::SyncAttributesAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, std::string& aValue) : iService(aProxy) , iValue(aValue) { } void SyncAttributesAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndAttributes(aAsync, iValue); } class SyncQueryPortAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncQueryPortAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncQueryPortAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; uint32_t& iValue; }; SyncQueryPortAvOpenhomeOrgMediaServer1Cpp::SyncQueryPortAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue) : iService(aProxy) , iValue(aValue) { } void SyncQueryPortAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndQueryPort(aAsync, iValue); } class SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; uint32_t& iValue; }; SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp::SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue) : iService(aProxy) , iValue(aValue) { } void SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndBrowsePort(aAsync, iValue); } class SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp : public SyncProxyAction { public: SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp() {} private: CpProxyAvOpenhomeOrgMediaServer1Cpp& iService; uint32_t& iValue; }; SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp::SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp(CpProxyAvOpenhomeOrgMediaServer1Cpp& aProxy, uint32_t& aValue) : iService(aProxy) , iValue(aValue) { } void SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp::CompleteRequest(IAsync& aAsync) { iService.EndUpdateCount(aAsync, iValue); } CpProxyAvOpenhomeOrgMediaServer1Cpp::CpProxyAvOpenhomeOrgMediaServer1Cpp(CpDeviceCpp& aDevice) : iCpProxy("av-openhome-org", "MediaServer", 1, aDevice.Device()) { OpenHome::Net::Parameter* param; iActionManufacturer = new Action("Manufacturer"); param = new OpenHome::Net::ParameterString("Name"); iActionManufacturer->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Info"); iActionManufacturer->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Url"); iActionManufacturer->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("ImageUri"); iActionManufacturer->AddOutputParameter(param); iActionModel = new Action("Model"); param = new OpenHome::Net::ParameterString("Name"); iActionModel->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Info"); iActionModel->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Url"); iActionModel->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("ImageUri"); iActionModel->AddOutputParameter(param); iActionProduct = new Action("Product"); param = new OpenHome::Net::ParameterString("Name"); iActionProduct->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Info"); iActionProduct->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("Url"); iActionProduct->AddOutputParameter(param); param = new OpenHome::Net::ParameterString("ImageUri"); iActionProduct->AddOutputParameter(param); iActionAttributes = new Action("Attributes"); param = new OpenHome::Net::ParameterString("Value"); iActionAttributes->AddOutputParameter(param); iActionQueryPort = new Action("QueryPort"); param = new OpenHome::Net::ParameterUint("Value"); iActionQueryPort->AddOutputParameter(param); iActionBrowsePort = new Action("BrowsePort"); param = new OpenHome::Net::ParameterUint("Value"); iActionBrowsePort->AddOutputParameter(param); iActionUpdateCount = new Action("UpdateCount"); param = new OpenHome::Net::ParameterUint("Value"); iActionUpdateCount->AddOutputParameter(param); Functor functor; functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerNamePropertyChanged); iManufacturerName = new PropertyString("ManufacturerName", functor); AddProperty(iManufacturerName); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerInfoPropertyChanged); iManufacturerInfo = new PropertyString("ManufacturerInfo", functor); AddProperty(iManufacturerInfo); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerUrlPropertyChanged); iManufacturerUrl = new PropertyString("ManufacturerUrl", functor); AddProperty(iManufacturerUrl); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerImageUriPropertyChanged); iManufacturerImageUri = new PropertyString("ManufacturerImageUri", functor); AddProperty(iManufacturerImageUri); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelNamePropertyChanged); iModelName = new PropertyString("ModelName", functor); AddProperty(iModelName); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelInfoPropertyChanged); iModelInfo = new PropertyString("ModelInfo", functor); AddProperty(iModelInfo); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelUrlPropertyChanged); iModelUrl = new PropertyString("ModelUrl", functor); AddProperty(iModelUrl); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelImageUriPropertyChanged); iModelImageUri = new PropertyString("ModelImageUri", functor); AddProperty(iModelImageUri); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductNamePropertyChanged); iProductName = new PropertyString("ProductName", functor); AddProperty(iProductName); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductInfoPropertyChanged); iProductInfo = new PropertyString("ProductInfo", functor); AddProperty(iProductInfo); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductUrlPropertyChanged); iProductUrl = new PropertyString("ProductUrl", functor); AddProperty(iProductUrl); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductImageUriPropertyChanged); iProductImageUri = new PropertyString("ProductImageUri", functor); AddProperty(iProductImageUri); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::AttributesPropertyChanged); iAttributes = new PropertyString("Attributes", functor); AddProperty(iAttributes); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::QueryPortPropertyChanged); iQueryPort = new PropertyUint("QueryPort", functor); AddProperty(iQueryPort); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::BrowsePortPropertyChanged); iBrowsePort = new PropertyUint("BrowsePort", functor); AddProperty(iBrowsePort); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgMediaServer1Cpp::UpdateCountPropertyChanged); iUpdateCount = new PropertyUint("UpdateCount", functor); AddProperty(iUpdateCount); } CpProxyAvOpenhomeOrgMediaServer1Cpp::~CpProxyAvOpenhomeOrgMediaServer1Cpp() { DestroyService(); delete iActionManufacturer; delete iActionModel; delete iActionProduct; delete iActionAttributes; delete iActionQueryPort; delete iActionBrowsePort; delete iActionUpdateCount; } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncManufacturer(std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { SyncManufacturerAvOpenhomeOrgMediaServer1Cpp sync(*this, aName, aInfo, aUrl, aImageUri); BeginManufacturer(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginManufacturer(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionManufacturer, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionManufacturer->OutputParameters(); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndManufacturer(IAsync& aAsync, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("Manufacturer")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aName.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aInfo.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aUrl.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aImageUri.assign((const char*)val.Ptr(), val.Bytes()); } } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncModel(std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { SyncModelAvOpenhomeOrgMediaServer1Cpp sync(*this, aName, aInfo, aUrl, aImageUri); BeginModel(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginModel(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionModel, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionModel->OutputParameters(); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndModel(IAsync& aAsync, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("Model")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aName.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aInfo.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aUrl.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aImageUri.assign((const char*)val.Ptr(), val.Bytes()); } } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncProduct(std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { SyncProductAvOpenhomeOrgMediaServer1Cpp sync(*this, aName, aInfo, aUrl, aImageUri); BeginProduct(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginProduct(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionProduct, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionProduct->OutputParameters(); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndProduct(IAsync& aAsync, std::string& aName, std::string& aInfo, std::string& aUrl, std::string& aImageUri) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("Product")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aName.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aInfo.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aUrl.assign((const char*)val.Ptr(), val.Bytes()); } { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aImageUri.assign((const char*)val.Ptr(), val.Bytes()); } } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncAttributes(std::string& aValue) { SyncAttributesAvOpenhomeOrgMediaServer1Cpp sync(*this, aValue); BeginAttributes(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginAttributes(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionAttributes, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionAttributes->OutputParameters(); invocation->AddOutput(new ArgumentString(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndAttributes(IAsync& aAsync, std::string& aValue) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("Attributes")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; { const Brx& val = ((ArgumentString*)invocation.OutputArguments()[index++])->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncQueryPort(uint32_t& aValue) { SyncQueryPortAvOpenhomeOrgMediaServer1Cpp sync(*this, aValue); BeginQueryPort(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginQueryPort(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionQueryPort, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionQueryPort->OutputParameters(); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndQueryPort(IAsync& aAsync, uint32_t& aValue) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("QueryPort")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; aValue = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncBrowsePort(uint32_t& aValue) { SyncBrowsePortAvOpenhomeOrgMediaServer1Cpp sync(*this, aValue); BeginBrowsePort(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginBrowsePort(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionBrowsePort, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionBrowsePort->OutputParameters(); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndBrowsePort(IAsync& aAsync, uint32_t& aValue) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("BrowsePort")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; aValue = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SyncUpdateCount(uint32_t& aValue) { SyncUpdateCountAvOpenhomeOrgMediaServer1Cpp sync(*this, aValue); BeginUpdateCount(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BeginUpdateCount(FunctorAsync& aFunctor) { Invocation* invocation = iCpProxy.GetService().Invocation(*iActionUpdateCount, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionUpdateCount->OutputParameters(); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); iCpProxy.GetInvocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::EndUpdateCount(IAsync& aAsync, uint32_t& aValue) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("UpdateCount")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; aValue = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyManufacturerNameChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iManufacturerNameChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyManufacturerInfoChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iManufacturerInfoChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyManufacturerUrlChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iManufacturerUrlChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyManufacturerImageUriChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iManufacturerImageUriChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyModelNameChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iModelNameChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyModelInfoChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iModelInfoChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyModelUrlChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iModelUrlChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyModelImageUriChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iModelImageUriChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyProductNameChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iProductNameChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyProductInfoChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iProductInfoChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyProductUrlChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iProductUrlChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyProductImageUriChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iProductImageUriChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyAttributesChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iAttributesChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyQueryPortChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iQueryPortChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyBrowsePortChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iBrowsePortChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyUpdateCountChanged(Functor& aFunctor) { iCpProxy.GetLock().Wait(); iUpdateCountChanged = aFunctor; iCpProxy.GetLock().Signal(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyManufacturerName(std::string& aManufacturerName) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iManufacturerName->Value(); aManufacturerName.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyManufacturerInfo(std::string& aManufacturerInfo) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iManufacturerInfo->Value(); aManufacturerInfo.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyManufacturerUrl(std::string& aManufacturerUrl) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iManufacturerUrl->Value(); aManufacturerUrl.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyManufacturerImageUri(std::string& aManufacturerImageUri) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iManufacturerImageUri->Value(); aManufacturerImageUri.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyModelName(std::string& aModelName) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iModelName->Value(); aModelName.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyModelInfo(std::string& aModelInfo) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iModelInfo->Value(); aModelInfo.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyModelUrl(std::string& aModelUrl) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iModelUrl->Value(); aModelUrl.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyModelImageUri(std::string& aModelImageUri) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iModelImageUri->Value(); aModelImageUri.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyProductName(std::string& aProductName) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iProductName->Value(); aProductName.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyProductInfo(std::string& aProductInfo) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iProductInfo->Value(); aProductInfo.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyProductUrl(std::string& aProductUrl) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iProductUrl->Value(); aProductUrl.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyProductImageUri(std::string& aProductImageUri) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iProductImageUri->Value(); aProductImageUri.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyAttributes(std::string& aAttributes) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } const Brx& val = iAttributes->Value(); aAttributes.assign((const char*)val.Ptr(), val.Bytes()); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyQueryPort(uint32_t& aQueryPort) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } aQueryPort = iQueryPort->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyBrowsePort(uint32_t& aBrowsePort) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } aBrowsePort = iBrowsePort->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::PropertyUpdateCount(uint32_t& aUpdateCount) const { AutoMutex a(iCpProxy.PropertyReadLock()); if (iCpProxy.GetSubscriptionStatus() != CpProxy::eSubscribed) { THROW(ProxyNotSubscribed); } aUpdateCount = iUpdateCount->Value(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerNamePropertyChanged() { ReportEvent(iManufacturerNameChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerInfoPropertyChanged() { ReportEvent(iManufacturerInfoChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerUrlPropertyChanged() { ReportEvent(iManufacturerUrlChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ManufacturerImageUriPropertyChanged() { ReportEvent(iManufacturerImageUriChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelNamePropertyChanged() { ReportEvent(iModelNameChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelInfoPropertyChanged() { ReportEvent(iModelInfoChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelUrlPropertyChanged() { ReportEvent(iModelUrlChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ModelImageUriPropertyChanged() { ReportEvent(iModelImageUriChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductNamePropertyChanged() { ReportEvent(iProductNameChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductInfoPropertyChanged() { ReportEvent(iProductInfoChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductUrlPropertyChanged() { ReportEvent(iProductUrlChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ProductImageUriPropertyChanged() { ReportEvent(iProductImageUriChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::AttributesPropertyChanged() { ReportEvent(iAttributesChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::QueryPortPropertyChanged() { ReportEvent(iQueryPortChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::BrowsePortPropertyChanged() { ReportEvent(iBrowsePortChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::UpdateCountPropertyChanged() { ReportEvent(iUpdateCountChanged); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::Subscribe() { iCpProxy.Subscribe(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::Unsubscribe() { iCpProxy.Unsubscribe(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyChanged(Functor& aFunctor) { iCpProxy.SetPropertyChanged(aFunctor); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::SetPropertyInitialEvent(Functor& aFunctor) { iCpProxy.SetPropertyInitialEvent(aFunctor); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::AddProperty(Property* aProperty) { iCpProxy.AddProperty(aProperty); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::DestroyService() { iCpProxy.DestroyService(); } void CpProxyAvOpenhomeOrgMediaServer1Cpp::ReportEvent(Functor aFunctor) { iCpProxy.ReportEvent(aFunctor); } TUint CpProxyAvOpenhomeOrgMediaServer1Cpp::Version() const { return iCpProxy.Version(); }
35.182004
218
0.748372
5ab40cad403f3d645ee6c48b5684403204a488ff
2,178
cpp
C++
ModernCpp-11-14-17/cppFacilities/inlineFunctions.cpp
eduardorasgado/Cpp-AdvancedTopics
b025845e97f794be857ec5893999a5b2a18c1939
[ "MIT" ]
1
2019-06-20T17:51:11.000Z
2019-06-20T17:51:11.000Z
ModernCpp-11-14-17/cppFacilities/inlineFunctions.cpp
eduardorasgado/Cpp-AdvancedTopics
b025845e97f794be857ec5893999a5b2a18c1939
[ "MIT" ]
null
null
null
ModernCpp-11-14-17/cppFacilities/inlineFunctions.cpp
eduardorasgado/Cpp-AdvancedTopics
b025845e97f794be857ec5893999a5b2a18c1939
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <memory> // inline function through a macro // if it is not handling correctly it will create bugs //#define Square(A) (A*A) // In c++ instead a macro we use inline functions // inline keyword tells the compiler to substitute the caller of the function in // where inline function is been using(e.g int result = Square(val) ) // and replace it with the body of the function(in compiler time) inline int Square(int x) { return x * x; } // new name for type pair: type definition typedef std::pair<int, std::string> par; int main() { // creating a map using a smart pointer auto myMap = std::make_shared<std::map<int, std::string>>(); // inserting elements to map myMap->insert(par(0, "0x200")); myMap->insert(par(1, "0x420")); //showing the map // creating an iterator for stl map object std::map<int, std::string>::iterator i = myMap->begin(); for(i; i != myMap->end();++i) std::cout << "map[" << i->first <<"]: " << i->second << "\n"; // inline functions int val = 5; // with inline function, the arguments passed here are firstly evaluated and then // passed to the function int result = Square(val + 1); std::cout << result << std::endl; int result2 = Square((val * 2) +1); // 11 and 11*11 = 121 std::cout << result2 << std::endl; /* INLINE FUNCTIONS: -Only a request to the compiler -Certain functions may nto be inlined large functions functions having too many conditional statements recursive functions functions invoked through pointers etc -Diferent compilers have different rules - Modern compilers may automatically inline even non-inline functions -Excessive inlining may increase binary size MACROS VS INLINE macro is text substitution | the call is replaced with the body error prone due to substitution | safe to use as it has func semantics does not have an address | has an address difficult to use with multiple lines of code | can have multiple line of codes */ return 0; }
32.029412
95
0.646006
5ab5452484bd28924f5702f898a4fabeb8873687
1,590
cpp
C++
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <stdio.h> #include <iostream> #include <string.h> #include <stdlib.h> #include <time.h> #define abs(a) (((a)>0)?(a):(-(a))) #define max(a, b) (((a)>(b))?(a):(b)) #define min(a, b) (((a)<(b))?(a):(b)) #define N 303 #define oo int(1e9) #define eps 1e-8 using namespace std; bool g[N][N], cl[N]; int main() { // freopen("input.txt", "r", stdin); int n, m, k, i, j, c, u, v, v1, v2; cin >> n >> m >> k; for(i=0; i<N; ++i) cl[i] = 0; for(i=0; i<N; ++i) for(j=0; j<N; ++j) g[i][j] = 0; v1 = v2 = -1; for(i=0; i<k; ++i) { cin >> c; cl[--c] = 1; if(v1 == -1) v1 = c; else if(v2 == -1) v2 = c; } v = 0; while(v<n && cl[v]) ++v; if(v == n) { cout << -1 << endl; return 0; } g[v][v2] = g[v2][v] = 1; --m; for(i=0; i<n; ++i) { if((i == v1) || (i == v2)) continue; g[v1][i] = g[i][v1] = 1; --m; } if(m<0) { cout << -1 << endl; return 0; } for(i=0; (i<n) && m; ++i) for(j=i+1; (j<n) && m; ++j) { if(cl[i] && cl[j] && ( (v2 == i) || (v2 == j))) continue; if(g[i][j]) continue; g[i][j] = 1; --m; } if(m) { cout << -1 << endl; return 0; } for(i=0; i<n; ++i) for(j=i+1; j<n; ++j) if(g[i][j]) cout << i+1 << " " << j+1 << endl; return 0; }
15.588235
59
0.330189
5ab7c41752f47e96c7046a5f0bef21e0a5476634
3,475
cpp
C++
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
2
2018-01-11T13:00:14.000Z
2018-01-12T02:02:16.000Z
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
#include <iterator> #include "AnimationPlayer.h" namespace nest { using namespace std; void AnimationPlayer::advanceTime(float dt) { time += dt; int i, j = poses.size(); PoseData *pose = NULL; AnimationChannel *channel = NULL; vector<QuatKeyFrame>::iterator k; QuatKeyFrame *quatFirst = NULL, *quatSecond = NULL; vector<Vec3KeyFrame>::iterator l; Vec3KeyFrame *vec3First = NULL, *vec3Second = NULL; Quaternion q0, q1; Vector4 v0, v1; float current = 0.0f, ratio = 0.0f, size = 0.0f; current = time * clip->ticksPerSecond * speed; size = clip->duration; if(clip->loop || current <= size) { // calculate the right time. while(current > size) current -= size; // trigger events AnimationEvent event(current); dispatch(&event); // traverse the clip. for(i = 0; i < j; i++) { pose = &poses[i]; channel = clip->channels[i]; // position keyframes if(channel->positionKeys.size() == 1) { vec3First = &channel->positionKeys[channel->positionKeys.size() - 1]; pose->position.x = vec3First->x; pose->position.y = vec3First->y; pose->position.z = vec3First->z; } else { l = channel->positionKeys.begin(); while(true) { if(l == channel->positionKeys.end()) break; vec3First = &*l++; vec3Second = &*l; if(vec3First-> t <= current && vec3Second->t >= current) { ratio = (current - vec3First->t) / (vec3Second->t - vec3First->t); v0.x = vec3First->x; v0.y = vec3First->y; v0.z = vec3First->z; v1.x = vec3Second->x; v1.y = vec3Second->y; v1.z = vec3Second->z; v0 = v0 + (v1 - v0) * ratio; pose->position = v0; break; } } } // rotation keyframes if(channel->rotationKeys.size() == 1) { quatFirst = &channel->rotationKeys[channel->rotationKeys.size() - 1]; pose->rotation.x = quatFirst->x; pose->rotation.y = quatFirst->y; pose->rotation.z = quatFirst->z; pose->rotation.w = quatFirst->w; } else { k = channel->rotationKeys.begin(); while(true) { if(k == channel->rotationKeys.end()) break; quatFirst = &*k++; quatSecond = &*k; if(quatFirst->t <= current && quatSecond->t >= current) { ratio = (current - quatFirst->t) / (quatSecond->t - quatFirst->t); q0.x = quatFirst->x; q0.y = quatFirst->y; q0.z = quatFirst->z; q0.w = quatFirst->w; q1.x = quatSecond->x; q1.y = quatSecond->y; q1.z = quatSecond->z; q1.w = quatSecond->w; pose->rotation = Quaternion::slerp(q0, q1, ratio); break; } } } // scaling keyframes if(channel->scalingKeys.size() == 1) { vec3First = &channel->scalingKeys[channel->scalingKeys.size() - 1]; pose->scaling.x = vec3First->x; pose->scaling.y = vec3First->y; pose->scaling.z = vec3First->z; } else { l = channel->scalingKeys.begin(); while(true) { if(l == channel->scalingKeys.end()) break; vec3First = &*l++; vec3Second = &*l; if(vec3First-> t <= current && vec3Second->t >= current) { ratio = (current - vec3First->t) / (vec3Second->t - vec3First->t); v0.x = vec3First->x; v0.y = vec3First->y; v0.z = vec3First->z; v1.x = vec3Second->x; v1.y = vec3Second->y; v1.z = vec3Second->z; v0 = v0 + (v1 - v0) * ratio; pose->scaling = v0; break; } } } } } } }
27.579365
94
0.565755
5ac1966d89b74921ae7bb5dd06b0c9535749dd78
12,743
cpp
C++
src/SpLog.cpp
RedLeavesSun/unisoc-dloader
e9c24086d1e27da7b9c52747682fd324c5a8bdab
[ "Apache-2.0" ]
1
2021-08-22T03:22:04.000Z
2021-08-22T03:22:04.000Z
src/SpLog.cpp
RedLeavesSun/unisoc-dloader
e9c24086d1e27da7b9c52747682fd324c5a8bdab
[ "Apache-2.0" ]
null
null
null
src/SpLog.cpp
RedLeavesSun/unisoc-dloader
e9c24086d1e27da7b9c52747682fd324c5a8bdab
[ "Apache-2.0" ]
null
null
null
#include "SpLog.h" #include "ExePathHelper.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> #define LOG_DIRECTORY ( "Log") #define BINARY_EXTENSION (".bin") #define TEXT_EXTENSION (".log") #define GetFileNameWithoutExtension(_fn) { \ char* pPos = strrchr((_fn), '.'); \ if (NULL != pPos) { \ *pPos = '\0'; \ } \ } char * PathFindExtension(char * path) { char * pFileExt = strrchr(path,'.'); if(pFileExt != NULL) pFileExt += 1; return pFileExt; } char * PathFindFileName(char * path) { char * pFileName = strrchr(path,'/'); if(pFileName == NULL) pFileName = path; else pFileName += 1; return pFileName; } char * PathRemoveFileSpec(char * path) { char * pFileDir = strrchr(path,'/'); if(pFileDir != NULL) *pFileDir = 0; else pFileDir = path; return pFileDir; } CSpLog::CSpLog() { //ctor m_pTxtFile = NULL; m_uLogLevel = 0; m_nLineMaxChars = 16; memset(m_szModuleName,0,sizeof(m_szModuleName)); memset(m_szLogDirPath,0,sizeof(m_szLogDirPath)); memset(m_szDefLogName,0,sizeof(m_szDefLogName)); memset(m_szLgFilePath,0,sizeof(m_szLgFilePath)); memset(m_szLocalTime,0,sizeof(m_szLocalTime)); memset(m_szLogBuffer,0,sizeof(m_szLogBuffer)); m_mutex = PTHREAD_MUTEX_INITIALIZER; GetExePath helper; std::string strModuleName = helper.getExeName(); std::string strModuleDir = helper.getExeDir(); strcpy(m_szModuleName, strModuleName.c_str()); strcpy(m_szDefLogName, m_szModuleName); snprintf(m_szLogDirPath, (_MAX_PATH-1), "/%s%s/", strModuleDir.c_str(), LOG_DIRECTORY); m_nLogNum = 0; memset(m_szUserLogName,0,sizeof(m_szUserLogName)); } CSpLog::~CSpLog() { //dtor Close(); m_pTxtFile = NULL; } void CSpLog::AutoLock() { if(m_uLogLevel == SPLOGLV_SPLIT) { CAutoCS cs( m_mutex ); } } bool CSpLog::Open(char* path, uint32_t uLogLevel/*=SPLOGLV_INFO*/ ) { AutoLock(); Close(); m_uLogLevel = uLogLevel; if(m_uLogLevel == 0) { return true; } if(path || strlen(path)!= 0) { if(strcmp(path,m_szUserLogName) != 0) { strcpy(m_szUserLogName,path); m_nLogNum = 0; } } else { memset(m_szUserLogName,0,sizeof(m_szUserLogName)); } memset(m_szLgFilePath, 0,sizeof(m_szLgFilePath)); GetLogFilePath(m_szUserLogName, m_szLgFilePath, true); if(m_uLogLevel == SPLOGLV_SPLIT) { m_pTxtFile = fopen(m_szLgFilePath,"wb"); } else { m_pTxtFile = fopen(m_szLgFilePath,"a+b"); } if(m_pTxtFile == NULL) { return false; } return true; } bool CSpLog::Close(void) { AutoLock(); if(m_pTxtFile != NULL) { fclose(m_pTxtFile); m_pTxtFile = NULL; } return true; } bool CSpLog::LogRawStr(uint32_t uLogLevel, const char* str) { if(!IsOpen()) return true; if(m_uLogLevel == SPLOGLV_DATA) { if(uLogLevel != SPLOGLV_DATA) { return true; } } else { if( uLogLevel > m_uLogLevel) { return true; } } return LogString(str); } bool CSpLog::LogFmtStr(uint32_t uLogLevel, const char* strFmt, ...) { if(!IsOpen()) return true; if(m_uLogLevel == SPLOGLV_DATA) { if(uLogLevel != SPLOGLV_DATA) { return true; } } else { if( uLogLevel > m_uLogLevel) { return true; } } char szString[MAX_STRING_IN_BYTES] = {0}; va_list args; va_start(args, strFmt); vsnprintf(szString, sizeof(szString), strFmt, args); va_end(args); return LogString(szString); } bool CSpLog::LogBufData(uint32_t uLogLevel, const uint8_t *pBufData, uint32_t dwBufSize, uint32_t uFlag /*=LOG_WRITE*/, const uint32_t * pUserNeedSize /*=NULL*/) { if(!IsOpen()) return true; if(m_uLogLevel == SPLOGLV_DATA) { if(uLogLevel != SPLOGLV_DATA) { return true; } } else { if( uLogLevel > m_uLogLevel) { return true; } } //pthread_mutex_lock(&m_mutex); // Example: [2009-05-27 15:06:47:0453] --> 110625(0x0001b021) Bytes AutoLock(); char szPrefix[50] = {0}; if(pUserNeedSize == NULL) { switch(uFlag) { case LOG_READ: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x) Bytes", "<--", dwBufSize, dwBufSize); break; case LOG_WRITE: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x) Bytes", "-->", dwBufSize, dwBufSize); break; case LOG_ASYNC_READ: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x) Bytes", "<<-", dwBufSize, dwBufSize); break; default: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x) Bytes", "---", dwBufSize, dwBufSize); break; } } else { switch(uFlag) { case LOG_READ: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x)/%d(0x%08x) Bytes", "<--", dwBufSize, dwBufSize,*pUserNeedSize,*pUserNeedSize); break; case LOG_WRITE: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x)/%d(0x%08x) Bytes", "-->", dwBufSize, dwBufSize,*pUserNeedSize,*pUserNeedSize); break; case LOG_ASYNC_READ: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x)/%d(0x%08x) Bytes", "<<-", dwBufSize, dwBufSize,*pUserNeedSize,*pUserNeedSize); break; default: snprintf(szPrefix, sizeof(szPrefix)-1, "%s %d(0x%08x)/%d(0x%08x) Bytes", "---", dwBufSize, dwBufSize,*pUserNeedSize,*pUserNeedSize); break; } } if ( !LogString(szPrefix) ) { //pthread_mutex_unlock(&m_mutex); return false; } if( 0 == dwBufSize) { //pthread_mutex_unlock(&m_mutex); return true; } // Blank alignment char szBlankAlign[50] = {0}; //if (m_bDspTime) { memset(szBlankAlign, 0x20, strlen(m_szLocalTime)+1); } // Line number uint32_t nMaxLine = dwBufSize % m_nLineMaxChars ? (dwBufSize/m_nLineMaxChars+1) : dwBufSize/m_nLineMaxChars; uint32_t nLineNo = 0; const uint8_t *pChar = pBufData; do { // char szLine[MAX_LINE_HEX_BYTES*5+100] = {0}; char szBuff[MAX_LINE_HEX_BYTES*3+20] = {0}; char szAsci[MAX_LINE_HEX_BYTES*2] = {0}; //if (m_bDspIndex) { // Example: 00000010h: snprintf(szBuff, sizeof(szBuff)-1, "%08xh: ", nLineNo*m_nLineMaxChars); } for (uint32_t n=0; n<m_nLineMaxChars; n++, pChar++) { char szHex[5] = {0}; sprintf(szHex, "%02X ", *pChar); strcat(szBuff, szHex); //if (m_bDspAscii) { // ASCII szAsci[n] = isprint(*pChar) ? *pChar : '.'; } if (dwBufSize == (nLineNo*m_nLineMaxChars+n+1)) { // Reaching the last byte if (n < m_nLineMaxChars) { // Last line for (uint32_t j=n+1; j<m_nLineMaxChars; j++) { strcat(szBuff, " "); } } break; } } snprintf(szLine, sizeof(szLine)-1, "%s%s; %s\r\n", szBlankAlign, szBuff, szAsci); // Writing uint32_t nLen = strlen(szLine); if( fwrite(szLine,1,nLen,m_pTxtFile) != nLen) { fflush(m_pTxtFile); //pthread_mutex_unlock(&m_mutex); return false; } fflush(m_pTxtFile); } while(++nLineNo < nMaxLine); //pthread_mutex_unlock(&m_mutex); if(m_uLogLevel == SPLOGLV_SPLIT && ftell(m_pTxtFile)>10*1024*1024) { Open(m_szUserLogName,m_uLogLevel); } return true; } bool CSpLog::LogString(const char* str) { AutoLock(); if(m_pTxtFile == NULL || str == NULL) return false; char szLogBuffer[MAX_STRING_IN_BYTES+LOCALTIME_STRING_MAX_LEN] = {0}; // Log local time as "[2009-05-25 12:30:52:0136]... #ifdef __WIN32__ snprintf(szLogBuffer, sizeof(szLogBuffer)-1, "%s %s\r\n", GetLocalTime(), str); #else snprintf(szLogBuffer, sizeof(szLogBuffer)-1, "%s %s\n", GetLocalTime(), str); #endif uint32_t nLen = strlen(szLogBuffer); if (m_uLogLevel < SPLOGLV_SPLIT) { printf(szLogBuffer); return true; } if( fwrite(szLogBuffer,1,nLen,m_pTxtFile) == nLen) { fflush(m_pTxtFile); if(m_uLogLevel == SPLOGLV_SPLIT && ftell(m_pTxtFile)>10*1024*1024) { Open(m_szUserLogName,m_uLogLevel); } return true; } else return false; } // -------------------------------------------------------------------------------- // Get the log file path // void CSpLog::GetLogFilePath(const char * lpszOrgFilePath, char* lpszDstFilePath, bool bIsTxtLogFile) { char szLogFileName[_MAX_PATH] = {0}; char szOrgFilePath[_MAX_PATH] = {0}; //char szFileExtName[_MAX_PATH] = {0}; if ( 0 == strlen(lpszOrgFilePath )) { snprintf(szOrgFilePath, (_MAX_PATH-1), "%s", m_szDefLogName); } else { snprintf(szOrgFilePath, (_MAX_PATH-1), "%s", lpszOrgFilePath); } // get file name without extension name strcpy(szLogFileName, PathFindFileName(szOrgFilePath)); GetFileNameWithoutExtension(szLogFileName); // get file extension name // GetLogExtension(szOrgFilePath, szFileExtName, bIsTxtLogFile); if ( strrchr(szOrgFilePath,'/') == NULL ) { // relative path... // create directories CreateMultiDirectory(m_szLogDirPath); // append date & time suffix /* time_t now; timeval tpTime; gettimeofday(&tpTime,0); now = time(0); tm *t= localtime(&now); snprintf(lpszDstFilePath, (_MAX_PATH-1), "%s%s_%04d_%02d_%02d_%02d_%02d_%02d_%03d%s", \ m_szLogDirPath, szLogFileName, \ t->tm_year, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, (int)(tpTime.tv_usec/1000), \ ".log"); */ time_t now; now = time(0); tm *t= localtime(&now); //here added by wei.zhang to put the month adding 1. snprintf(lpszDstFilePath, (_MAX_PATH-1), "%s%s_%04d_%02d_%02d_[%d].log", \ m_szLogDirPath, szLogFileName, \ t->tm_year+1900, t->tm_mon+1, t->tm_mday,\ m_nLogNum); } else { // absolute path... PathRemoveFileSpec(szOrgFilePath); snprintf(lpszDstFilePath, (_MAX_PATH-1), "%s/%s_[%d].log", szOrgFilePath, szLogFileName, m_nLogNum); } m_nLogNum++; } bool CSpLog::CreateMultiDirectory(const char* lpszPathName) { if (NULL == lpszPathName) { return false; } int nLen = strlen(lpszPathName); if (nLen < 2) { return false; } char szPathName[_MAX_PATH] = {0}; strncpy(szPathName, lpszPathName, _MAX_PATH-1); #ifdef _WIN32 if ( _T('\\') == szPathName[_tcslen(szPathName)-1] ) { // Removes the trailing backslash szPathName[_tcslen(szPathName)-1] = _T('\0'); } DWORD dwFileAttr = GetFileAttributes(szPathName); if ( (dwFileAttr != (DWORD)-1) && (dwFileAttr&FILE_ATTRIBUTE_DIRECTORY) ) { return true; } #else if ( '/' == szPathName[strlen(szPathName)-1] ) { // Removes the trailing backslash szPathName[strlen(szPathName)-1] = '\0'; } struct stat buf = {0}; if(lstat(szPathName, &buf) == 0 ) { if(S_ISDIR(buf.st_mode)) return true; } #endif char szTmpPath[_MAX_PATH] = {0}; char* lpDest = strrchr(szPathName, '/'); if (NULL != lpDest) { strncpy(szTmpPath, szPathName, lpDest-szPathName); } else { return false; } if ( CreateMultiDirectory(szTmpPath) ) { // Create directory ... // @hongliang.xin 2010-10-15 enhance the code #ifdef _WIN32 if(!CreateDirectory(szPathName, NULL)) { if(GetLastError() != ERROR_ALREADY_EXISTS) { return FALSE; } } #else if(access(szPathName, NULL)!=0 ) { if(mkdir(szPathName, 0755)==-1) { return false; } } #endif return true; } else { return false; } } bool CSpLog::IsOpen() { AutoLock(); return (m_pTxtFile!= NULL); }
22.919065
112
0.558503
5ac1a14ceb5b36616b777529e204a4532891459e
13,823
cpp
C++
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2019-12-24T04:00:36.000Z
2022-01-26T02:44:04.000Z
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
null
null
null
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2020-09-26T04:19:40.000Z
2021-02-19T07:24:57.000Z
#include "graphics/bloomFFT.h" #include "utils/loadshader.h" BloomFFT::BloomFFT(vks::VulkanDevice * vulkanDevice) { this->vulkanDevice = vulkanDevice; this->device = vulkanDevice->logicalDevice; } BloomFFT::~BloomFFT() { } // Find and create a compute capable device queue void BloomFFT::getComputeQueue() { uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(vulkanDevice->physicalDevice, &queueFamilyCount, NULL); assert(queueFamilyCount >= 1); std::vector<VkQueueFamilyProperties> queueFamilyProperties; queueFamilyProperties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(vulkanDevice->physicalDevice, &queueFamilyCount, queueFamilyProperties.data()); // Some devices have dedicated compute queues, so we first try to find a queue that supports compute and not graphics bool computeQueueFound = false; for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++) { if ((queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) && ((queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) { compute.queueFamilyIndex = i; computeQueueFound = true; break; } } // If there is no dedicated compute queue, just find the first queue family that supports compute if (!computeQueueFound) { for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++) { if (queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { compute.queueFamilyIndex = i; computeQueueFound = true; break; } } } // Compute is mandatory in Vulkan, so there must be at least one queue family that supports compute assert(computeQueueFound); // Get a compute queue from the device vkGetDeviceQueue(device, compute.queueFamilyIndex, 0, &compute.queue); } // Prepare a texture target that is used to store compute shader calculations void BloomFFT::prepareTextureTarget( uint32_t width, uint32_t height, VkCommandPool &cmdPool,VkQueue queue) { createUniformBuffers(queue); // Prepare blit target texture textureComputeTarget.width = width; textureComputeTarget.height = height; VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; imageCreateInfo.extent = { width, height, 1 }; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = 1; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; // Image will be sampled in the fragment shader and used as storage target in the compute shader imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT; imageCreateInfo.flags = 0; // Sharing mode exclusive means that ownership of the image does not need to be explicitly transferred between the compute and graphics queue imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkMemoryAllocateInfo memAllocInfo = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &textureComputeTarget.image)); vkGetImageMemoryRequirements(device, textureComputeTarget.image, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr, &textureComputeTarget.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textureComputeTarget.image, textureComputeTarget.deviceMemory, 0)); VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true, cmdPool); textureComputeTarget.imageLayout = VK_IMAGE_LAYOUT_GENERAL; vks::tools::setImageLayout( layoutCmd, textureComputeTarget.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, textureComputeTarget.imageLayout); flushCommandBuffer(layoutCmd, queue, true, cmdPool); // Create sampler VkSamplerCreateInfo sampler = vks::initializers::samplerCreateInfo(); sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; sampler.addressModeV = sampler.addressModeU; sampler.addressModeW = sampler.addressModeU; sampler.mipLodBias = 0.0f; sampler.maxAnisotropy = 1.0f; sampler.compareOp = VK_COMPARE_OP_NEVER; sampler.minLod = 0.0f; sampler.maxLod =static_cast<float>(textureComputeTarget.mipLevels); sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &textureComputeTarget.sampler)); // Create image view VkImageViewCreateInfo view = vks::initializers::imageViewCreateInfo(); view.image = VK_NULL_HANDLE; view.viewType = VK_IMAGE_VIEW_TYPE_2D; view.format = VK_FORMAT_R8G8B8A8_UNORM; view.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }; view.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; view.image = textureComputeTarget.image; VK_CHECK_RESULT(vkCreateImageView(device, &view, nullptr, &textureComputeTarget.view)); // Initialize a descriptor for later use textureComputeTarget.descriptor.imageLayout = textureComputeTarget.imageLayout; textureComputeTarget.descriptor.imageView = textureComputeTarget.view; textureComputeTarget.descriptor.sampler = textureComputeTarget.sampler; textureComputeTarget.device = vulkanDevice; // Prepare blit target texture textureComputeTargetOut.width = width; textureComputeTargetOut.height = height; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &textureComputeTargetOut.image)); vkGetImageMemoryRequirements(device, textureComputeTargetOut.image, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr, &textureComputeTargetOut.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textureComputeTargetOut.image, textureComputeTargetOut.deviceMemory, 0)); layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true, cmdPool); textureComputeTargetOut.imageLayout = VK_IMAGE_LAYOUT_GENERAL; vks::tools::setImageLayout( layoutCmd, textureComputeTargetOut.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, textureComputeTargetOut.imageLayout); flushCommandBuffer(layoutCmd, queue, true, cmdPool); sampler.maxLod = static_cast<float>(textureComputeTargetOut.mipLevels); VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &textureComputeTargetOut.sampler)); view.image = textureComputeTargetOut.image; VK_CHECK_RESULT(vkCreateImageView(device, &view, nullptr, &textureComputeTargetOut.view)); // Initialize a descriptor for later use textureComputeTargetOut.descriptor.imageLayout = textureComputeTargetOut.imageLayout; textureComputeTargetOut.descriptor.imageView = textureComputeTargetOut.view; textureComputeTargetOut.descriptor.sampler = textureComputeTargetOut.sampler; textureComputeTarget.device = vulkanDevice; } void BloomFFT::createUniformBuffers(VkQueue queue) { // Scene matrices vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers, sizeof(uboParams)); updateUniformBuffer(1); }void BloomFFT::updateUniformBuffer(int direction) { uboParams.direction = 1; uboParams.scale = 2.5; uboParams.strength = 1.0; VK_CHECK_RESULT(uniformBuffers.map()); uniformBuffers.copyTo(&uboParams, sizeof(uboParams)); uniformBuffers.unmap(); } void BloomFFT::prepareCompute(VkDescriptorPool &descriptorPool, VkDescriptorImageInfo &texDescriptor) { getComputeQueue(); // Create compute pipeline // Compute pipelines are created separate from graphics pipelines even if they use the same queue std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0: Input image (read-only) vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 0), // Binding 1: Output image (write) vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 1), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 2), }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &compute.descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&compute.descriptorSetLayout, 1); VkPushConstantRange pushConstantRange = vks::initializers::pushConstantRange( VK_SHADER_STAGE_VERTEX_BIT, sizeof(uboParams), 0); pPipelineLayoutCreateInfo.pushConstantRangeCount = 1; pPipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange; VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &compute.pipelineLayout)); VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &compute.descriptorSetLayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &compute.descriptorSet)); std::vector<VkWriteDescriptorSet> computeWriteDescriptorSets = { vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &texDescriptor), vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &textureComputeTarget.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformBuffers.descriptor) }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(computeWriteDescriptorSets.size()), computeWriteDescriptorSets.data(), 0, NULL); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &compute.descriptorSetOut)); std::vector<VkWriteDescriptorSet> computeWriteDescriptorSetsOut = { vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &textureComputeTarget.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &textureComputeTargetOut.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformBuffers.descriptor) }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(computeWriteDescriptorSetsOut.size()), computeWriteDescriptorSetsOut.data(), 0, NULL); // Create compute shader pipelines VkComputePipelineCreateInfo computePipelineCreateInfo = vks::initializers::computePipelineCreateInfo(compute.pipelineLayout, 0); std::string fileName = getAssetPath + "computeshader/gaussianBlur.comp.spv"; computePipelineCreateInfo.stage = loadShader(fileName, VK_SHADER_STAGE_COMPUTE_BIT, device, shaderModules); VkPipeline pipeline; VK_CHECK_RESULT(vkCreateComputePipelines(device, 0, 1, &computePipelineCreateInfo, nullptr, &pipeline)); compute.pipelines.push_back(pipeline); // Separate command pool as queue family for compute may be different than graphics VkCommandPoolCreateInfo cmdPoolInfo = {}; cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmdPoolInfo.queueFamilyIndex = compute.queueFamilyIndex; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VK_CHECK_RESULT(vkCreateCommandPool(device, &cmdPoolInfo, nullptr, &compute.commandPool)); // Create a command buffer for compute operations VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo( compute.commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &compute.commandBuffer)); // Fence for compute CB sync VkFenceCreateInfo fenceCreateInfo = vks::initializers::fenceCreateInfo(VK_FENCE_CREATE_SIGNALED_BIT); VK_CHECK_RESULT(vkCreateFence(device, &fenceCreateInfo, nullptr, &compute.fence)); // Build a single command buffer containing the compute dispatch commands //buildComputeCommandBuffer(); } void BloomFFT::buildComputeCommandBuffer() { // Flush the queue if we're rebuilding the command buffer after a pipeline change to ensure it's not currently in use vkQueueWaitIdle(compute.queue); VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VK_CHECK_RESULT(vkBeginCommandBuffer(compute.commandBuffer, &cmdBufInfo)); uboParams.direction = 1; uboParams.scale = 4.5; uboParams.strength = 1.0; vkCmdPushConstants( compute.commandBuffer, compute.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uboParams), &uboParams); vkCmdBindPipeline(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelines[compute.pipelineIndex]); vkCmdBindDescriptorSets(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelineLayout, 0, 1, &compute.descriptorSet, 0, 0); vkCmdDispatch(compute.commandBuffer, textureComputeTarget.width / 16, textureComputeTarget.height / 16, 1); uboParams.direction = 0; vkCmdPushConstants( compute.commandBuffer, compute.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uboParams), &uboParams); vkCmdBindDescriptorSets(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelineLayout, 0, 1, &compute.descriptorSetOut, 0, 0); vkCmdDispatch(compute.commandBuffer, textureComputeTarget.width / 16, textureComputeTarget.height / 16, 1); vkEndCommandBuffer(compute.commandBuffer); }
43.196875
143
0.818419
5ac3f2e8ad5d7b8f0836af365f2c48061ba84948
604
cpp
C++
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ void inorder(TreeNode *root, vector<int> &arr) { if (root == NULL) { return; } inorder(root->left, arr); arr.push_back(root->val); inorder(root->right, arr); } int Solution::t2Sum(TreeNode *root, int k) { vector<int> arr; inorder(root, arr); int lo = 0, hi = arr.size() - 1; while (lo < hi) { int curr = arr[lo] + arr[hi]; if (curr == k) { return 1; } curr < k ? lo++ : hi--; } return 0; }
18.30303
59
0.559603
5ac525f8af8438fdc1a9aa2dfa5bfd4d703a8344
4,474
cpp
C++
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
// // FaseMontanha.cpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 11/10/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #include "FaseMontanha.hpp" namespace Game { namespace Fases { // Const const string FaseMontanha::CONFIG_FILE("Resources/config/fase_b_config.json"); // Constructor && Destructor FaseMontanha::FaseMontanha(Jogador* jogador_a, Jogador* jogador_b): Fase(ID::fase_montanha, FaseMontanha::CONFIG_FILE, jogador_a, jogador_b) { } FaseMontanha::~FaseMontanha(){ this->l_entidades.clear(); } // Init Methods void FaseMontanha::initInimigos() { Inimigo* desmatador = nullptr; const vector<Vector2f>& lista = this->parametros.getListaPosInimigos(); for (Vector2f pos : lista){ if (rand() % 10 > 3){ desmatador = new Narcotraficante(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this); this->l_entidades += desmatador; this->g_colisoes += desmatador; } } } void FaseMontanha::initObstaculos() { Obstaculo* obstaculo = nullptr; const vector<Vector2f>& lista = this->parametros.getListaPosObstaculos(); for (Vector2f pos : lista){ if (rand() % 10 > 3) { if (rand() % 2 == 1) obstaculo = new Pedra(pos, &this->textures.get(Resources::Textures::pedra)); else obstaculo = new Espinho(pos, &this->textures.get(Resources::Textures::espinhos)); Vector2f ppos = obstaculo->getPosition(); ppos.y -= obstaculo->getGlobalBounds().height; obstaculo->setPosition(ppos); this->l_entidades+= obstaculo; this->g_colisoes += obstaculo; } } } void FaseMontanha::initBoss(){ Inimigo* inimigo = new NarcotraficanteDesmatador(this->parametros.getPosBoss(), &this->textures.get(Resources::Textures::narcotraficante_desmatador), this->jogador_a, this->jogador_b, this); this->l_entidades+= inimigo; this->g_colisoes += inimigo; } void FaseMontanha::onSavedFase() { // Inicia posicao jogadores vector<Vector2f> l_pos = this->salvadora.getPositions(Entidades::ID::jogador); this->jogador_a->setPosition(l_pos[0]); this->jogador_a->setNumVidas(this->salvadora.getVidaJogador(1)); if (this->jogador_b && l_pos.size() > 1){ this->jogador_b->setPosition(l_pos[1]); this->jogador_b->setNumVidas(this->salvadora.getVidaJogador(2)); } l_pos = this->salvadora.getPositions(Entidades::ID::boss); for(Vector2f pos : l_pos) this->addEntidade(new NarcotraficanteDesmatador(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this)); l_pos = this->salvadora.getPositions(Entidades::ID::narcotraficante); for(Vector2f pos : l_pos) this->addEntidade(new Narcotraficante(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this)); l_pos = this->salvadora.getPositions(Entidades::ID::espinhos); for(Vector2f pos : l_pos) this->addEntidade(new Espinho(pos, &this->textures.get(Resources::Textures::espinhos))); l_pos = this->salvadora.getPositions(Entidades::ID::pedra); for(Vector2f pos : l_pos) this->addEntidade(new Pedra(pos, &this->textures.get(Resources::Textures::planta_venenosa))); } // Methods void FaseMontanha::onInitFase(Jogador* jogador_a, Jogador* jogador_b, FaseEventHandler* event_handler){ // Agrega mapa this->l_entidades.add(&mapa); // Atualiza ponteiros de jogadores this->jogador_a = jogador_a; this->jogador_b = jogador_b; // Inicia jogadores this->initJogadores(); // Carrega salvadora this->salvadora.load(); if (!this->salvadora.isSavedFase()){ // Inicia boss this->initBoss(); // Inicia Obstaculos this->initObstaculos(); // Inicia Inimigos this->initInimigos(); // Muda estado this->salvadora.setSavedFase(true); } else { this->onSavedFase(); } // Retorna o mapa a sua posicao inicial this->mapa.reset(); // Atualiza EventHandler this->setEventHandler(event_handler); // Adapta View para resolucoes maiores GerenciadorGrafico::getInstance()->moveView(0, - (GerenciadorGrafico::getInstance()->getView()->getSize().y - this->mapa.getHeight())); } }}
35.507937
194
0.660483
5ac62f82592e415ee827d5189293c7f3233b15a7
165
cpp
C++
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; int ans = 0; if(n % 5 != 0) ans++; printf("%d\n", (n / 5) + ans); return 0; }
15
32
0.50303
5acc4ab4d9834f6261945e202b17ad0eaa29e43f
394
cpp
C++
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
3
2021-03-31T03:42:42.000Z
2021-12-13T03:03:03.000Z
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
null
null
null
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
1
2021-12-13T03:02:55.000Z
2021-12-13T03:02:55.000Z
#include "State.h" State::State() { bankPosition = Vector2D(208, 624); homePosition = Vector2D(624, 624); minePosition = Vector2D(272, 112); saloonPosition = Vector2D(1040, 624); } State::~State() { delete agent; } void State::Init(Agent * agent, Uint32 delayTime) { this->agent = agent; this->delayTime = delayTime; } void State::Quit(State * state) { agent->SwitchState(state); }
17.909091
51
0.682741
5ace0782dec3b99ee0a5f4f46b0d1c899d9277ad
2,326
cpp
C++
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <climits> #include <vector> #include <queue> #include <cstdlib> #include <string> #include <set> #include <stack> #define LL long long #define pii pair<int,int> #define INF 0x3f3f3f3f using namespace std; const int maxn = 110; struct arc { int to,flow,cost,next; arc(int x = 0,int y = 0,int z = 0,int nxt = -1) { to = x; flow = y; cost = z; next = nxt; } }; arc e[10000]; int head[maxn],d[maxn],p[maxn],S,T,n,k,tot; bool in[maxn]; void add(int u,int v,int flow,int cost) { e[tot] = arc(v,flow,cost,head[u]); head[u] = tot++; e[tot] = arc(u,0,-cost,head[v]); head[v] = tot++; } bool spfa() { queue<int>q; for(int i = 0; i <= n; ++i) { d[i] = INF; p[i] = -1; in[i] = false; } d[S] = 0; q.push(S); while(!q.empty()) { int u = q.front(); q.pop(); in[u] = false; for(int i = head[u]; ~i; i = e[i].next) { if(e[i].flow && d[e[i].to] > d[u] + e[i].cost) { d[e[i].to] = d[u] + e[i].cost; p[e[i].to] = i; if(!in[e[i].to]){ in[e[i].to] = true; q.push(e[i].to); } } } } return p[T] > -1; } int solve() { int cost = 0,flow = 0; while(spfa()) { int theMin = INF; for(int i = p[T]; ~i; i = p[e[i^1].to]) theMin = min(theMin,e[i].flow); if(cost + d[T]*theMin > k) return flow + (k - cost)/d[T]; flow += theMin; cost += d[T]*theMin; for(int i = p[T]; ~i; i = p[e[i^1].to]) { e[i].flow -= theMin; e[i^1].flow += theMin; } } return flow; } int main() { while(~scanf("%d %d",&n,&k)) { memset(head,-1,sizeof(head)); S = 0; T = n-1; int tmp; for(int i = tot = 0; i < n; ++i) for(int j = 0; j < n; ++j) { scanf("%d",&tmp); if(tmp) { add(i,j,tmp,0); add(i,j,k,1); } } printf("%d\n",solve()); } return 0; }
23.029703
65
0.410146
5ace2172fa2ef85d29199534b22ab9249c590b0d
1,792
hpp
C++
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
63
2016-02-06T21:06:40.000Z
2021-11-16T19:58:27.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
11
2019-05-23T20:55:12.000Z
2021-12-08T22:18:01.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
14
2016-02-21T17:12:36.000Z
2021-09-26T02:48:41.000Z
#ifndef JSON_UTILS_HPP__ #define JSON_UTILS_HPP__ #include <string> #include <clang-c/Index.h> #include <jsoncons/json.hpp> namespace cclyzer { namespace ast_exporter { namespace jsonexport { typedef jsoncons::json json_t; // Recording routines void record_extent( json_t &, CXCursor ); void record_extent(json_t &, CXSourceRange ); void record_kind( json_t &, CXCursor ); void record_spelling( json_t &, CXCursor ); void record_tokens( json_t &, CXCursor, CXTranslationUnit ); void record_token( json_t & , CXToken, CXTranslationUnit ); // AST Node properties namespace node { const std::string FILE = "file"; const std::string KIND = "kind"; const std::string DATA = "data"; const std::string START_LINE = "start_line"; const std::string START_COLUMN = "start_column"; const std::string START_OFFSET = "start_offset"; const std::string END_LINE = "end_line"; const std::string END_COLUMN = "end_column"; const std::string END_OFFSET = "end_offset"; const std::string TOKENS = "tokens"; const std::string TREE = "ast"; } // Lexical Token Properties namespace lex_token { const std::string KIND = "kind"; const std::string DATA = "data"; const std::string FILE = "file"; const std::string LINE = "line"; const std::string COLUMN = "column"; const std::string OFFSET = "offset"; } } } } #endif /* JSON_UTILS_HPP__ */
32
72
0.541853
62c26d2c087b23d3802b9a3ea8eeba0faf253fea
601
cpp
C++
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int p=1; int ctr=0; int zp=1; for(int i:nums) { p*=i; if(i==0) ++ctr; if(ctr>1){ vector<int>ans(nums.size(),0); return ans; } if(i!=0) zp*=i; } vector<int>res; for(int i:nums) { if(i==0) res.push_back(zp); else res.push_back(p/i); } return res; } };
20.724138
54
0.344426
62c349af6daabc492e41738d9210e08562d02708
1,499
cpp
C++
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
null
null
null
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
null
null
null
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
1
2020-03-09T22:18:40.000Z
2020-03-09T22:18:40.000Z
#include<bits/stdc++.h> #include <iostream> using namespace std; bool prime(long long n) { if (n <= 3) { return (n > 1); } if (((n % 2) == 0) || ((n % 3) == 0)) { return false; } long i = 5; while ((i * i) <= n) { if (((n % i) == 0) || ((n % (i + 2)) == 0)) { return false; } i += 6; } return true; } int main() { long long n; cin >> n; if (prime(n + 1)) { for(long long i = 1; i <= n; i++) { cout << i << " "; } cout << "\n"; for(long long j = n; j > 0; j--) { cout << j << " "; } } else { long long r; long long s; vector<long long> second; long long i = n; //asked number while(i > 0) { for(long long a = (i - 1); a >= 1; a--) { if (prime(a + i)) { r = a; } } s = i - r; for (long long a = 0; a <= s; a++) { second.push_back(r + a); } i = (r - 1); if (i == 3) { second.push_back(2); second.push_back(3); second.push_back(1); break; } else if (i == 2) { second.push_back(1); second.push_back(2); break; } else if (i == 1) { second.push_back(1); break; } } for(long long j = n; j > 0; j--){ cout << j << " "; } cout << "\n"; for(long long j = 0; j < n; j++) { long long number = second[j]; cout << number << " "; } } return 0; }
16.293478
51
0.378252
62c790184658f7c66222caea3cbe2b63dff7990d
4,673
cpp
C++
version Serial/BackgroundSubstractor.cpp
texsmv/background_substraction
89fbe98186524efb5303e819bc2d83a360298a04
[ "FTL" ]
null
null
null
version Serial/BackgroundSubstractor.cpp
texsmv/background_substraction
89fbe98186524efb5303e819bc2d83a360298a04
[ "FTL" ]
null
null
null
version Serial/BackgroundSubstractor.cpp
texsmv/background_substraction
89fbe98186524efb5303e819bc2d83a360298a04
[ "FTL" ]
null
null
null
#include "BackgroundSubstractor.h" BackgroundSubstractor::BackgroundSubstractor(){ vector<string> files = globVector("input/*"); sort(files.begin(), files.end()); for (int i = 0 ; i < files.size(); i++){ cout<<files[i]<<endl; Frame f(files[i]); frames.push_back(f); } h = frames[0].mat.rows; w = frames[0].mat.cols; // Inicializacion de arrays B_int = new float**[h]; B_lsbp = new int**[h]; D = new float**[h]; d = new float*[h]; R = new float*[h]; T = new float*[h]; for(int i = 0; i < h; i++){ B_int[i] = new float*[w]; B_lsbp[i] = new int*[w]; D[i] = new float*[w]; d[i] = new float[w]; R[i] = new float[w]; T[i] = new float[w]; for(int j = 0; j < w; j++){ B_int[i][j] = new float[S]; B_lsbp[i][j] = new int[S]; D[i][j] = new float[S]; d[i][j] = 0.1; R[i][j] = 18; T[i][j] = 0.05; for(int k = 0; k < S; k ++){ B_int[i][j][k] = 0; B_lsbp[i][j][k] = 0; D[i][j][k] = 0.2; } } } dmin(); } void BackgroundSubstractor::init(){ cout<<"Init"<<endl; int r = S / 2; float** intensidad = frames[0].intensidad; float** SVD = svd(intensidad, h, w); int** lbp = lsbp(SVD, h, w); for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ int i0 = clip(i, r, h - r - 1); int j0 = clip(j, r, w - r - 1); B_int[i][j][0] = intensidad[i][j]; B_lsbp[i][j][0] = lbp[i][j]; for(int k = 1; k < S; k++){ int i1 = i0 + random(-r, r + 1); int j1 = j0 + random(-r, r + 1); B_int[i][j][k] = intensidad[i1][j1]; B_lsbp[i][j][k] = lbp[i1][j1]; } } } cout<<"End init"<<endl; } void BackgroundSubstractor::step(int pos){ float** intensidad = frames[pos].intensidad; float** SVD = svd(intensidad, h, w); int** lbp = lsbp(SVD, h, w); bool** mask = new bool*[h]; for(int i = 0; i < h; i++){ mask[i] = new bool[w]; for(int j = 0; j < w; j++){ int count = 0; for(int k = 0; k < S; k++){ if(fabs(intensidad[i][j] - B_int[i][j][k]) < R[i][j] && HammingDist(lbp[i][j], B_lsbp[i][j][k]) < HR){ count++; } } if(count < threshold){ frames[pos].mat.at<uchar>(i, j) = 255; mask[i][j] = true; } else{ frames[pos].mat.at<uchar>(i, j) = 0; mask[i][j] = false; } } } update_R(); update_T(mask); update_models(mask, intensidad, lbp); cout<<pos<<endl; imwrite("output/" + to_string(pos) + ".jpg" , frames[pos].mat); } void BackgroundSubstractor::dmin(){ for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ d[i][j] = 0; for(int k = 0; k < S; k++){ d[i][j] += D[i][j][k]; } d[i][j] /= S; } } } void BackgroundSubstractor::update_R(){ for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(R[i][j] > d[i][j] * Rscale) R[i][j] = (1 - Rlr) * R[i][j]; else R[i][j] = (1 + Rlr) * R[i][j]; R[i][j] = clip(R[i][j], Rlower, 255); } } } void BackgroundSubstractor::update_T(bool** mask){ for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(mask[i][j] == true){ T[i][j] = T[i][j] + Tinc / d[i][j]; } else{ T[i][j] = T[i][j] - Tdec / d[i][j]; } T[i][j] = clip(T[i][j], Tlower, Tupper); } } } void BackgroundSubstractor::update_models(bool** mask, float** intensidad, int** lbp){ for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(mask[i][j] == false){ if(random(0, 100) < (1 / T[i][j])){ // cout<<"Actualizacion modelo"<<endl; int p = random(0, S); int min = fabs(B_int[i][j][0] - intensidad[i][j]); for(int k = 1; k < S; k++){ float temp = fabs(B_int[i][j][k] - intensidad[i][j]); if(temp < min && p != k) min = temp; } B_int[i][j][p] = intensidad[i][j]; B_lsbp[i][j][p] = lbp[i][j]; D[i][j][p] = min; } if(random(0, 100) < (1 / T[i][j])){ int i0 = clip(i + random(-1, 2), 0, h - 1); int j0 = clip(j + random(-1, 2), 0, w - 1); int p = random(0, S); int min = fabs(B_int[i0][j0][0] - intensidad[i0][j0]); for(int k = 1; k < S; k++){ float temp = fabs(B_int[i0][j0][k] - intensidad[i0][j0]); if(temp < min && p != k) min = temp; } B_int[i0][j0][p] = intensidad[i0][j0]; B_lsbp[i0][j0][p] = lbp[i0][j0]; D[i0][j0][p] = min; } } } } } // fin
21.734884
110
0.439332
62c7c24a915b70d87ec6da0b51c9364ddca01ca9
1,290
hpp
C++
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
5
2019-02-12T07:23:55.000Z
2020-06-22T15:03:36.000Z
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
null
null
null
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
2
2019-06-17T05:04:21.000Z
2020-04-22T09:05:57.000Z
#ifndef _ENGINE_COLLISION_LISTENER_HPP #define _ENGINE_COLLISION_LISTENER_HPP #include "Collision_listener.hpp" #include <cstdint> namespace physics_2d { class Body_2d; } namespace gom { class Game_object; } class Engine_collision_listener final : public physics_2d::Collision_listener { public: Engine_collision_listener(); void begin_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void in_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void end_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; private: void send_collision_event(gom::Game_object * pfrom_object, gom::Game_object * pto_object, std::uint32_t event_type) const; std::uint32_t m_begin_collision_id; std::uint32_t m_in_collision_id; std::uint32_t m_end_collision_id; std::uint32_t m_game_object_id; std::uint32_t m_game_object_handle_index; }; #endif // !_ENGINE_COLLISION_LISTENER_HPP
40.3125
80
0.633333
62c7e782f8700e161b39a4ace2cd24b8cd5f4582
8,218
hpp
C++
include/just/test.hpp
r0mai/just
81e0b95cfc6da1ba8b54c92974055a140cdf2694
[ "BSL-1.0" ]
1
2016-05-21T17:15:12.000Z
2016-05-21T17:15:12.000Z
include/just/test.hpp
r0mai/just
81e0b95cfc6da1ba8b54c92974055a140cdf2694
[ "BSL-1.0" ]
null
null
null
include/just/test.hpp
r0mai/just
81e0b95cfc6da1ba8b54c92974055a140cdf2694
[ "BSL-1.0" ]
null
null
null
#ifndef JUST_TEST_HPP #define JUST_TEST_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2014. // 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 <string> #include <vector> #include <iostream> #include <sstream> #include <stdexcept> namespace just { namespace test { /* * assertion_failed */ class assertion_failed { public: assertion_failed( const std::string& msg_, const std::string& filename_, int line_ ) : _msg(msg_), _filename(filename_), _line(line_) {} const std::string& msg() const { return _msg; } const std::string& filename() const { return _filename; } int line() const { return _line; } private: std::string _msg; std::string _filename; int _line; }; /* * test_case */ class test_case { public: test_case(const std::string& name_, void (*f_)()) : _f(f_), _name(name_) {} bool run(std::ostream& report_) const { report_ << "Running " << _name << std::endl; try { _f(); return true; } catch (const assertion_failed& e_) { report_ << " Assertion failed" << std::endl << " " << e_.msg() << std::endl << " Test case: " << _name << std::endl << " Location: " << e_.filename() << ":" << e_.line() <<std::endl ; } catch (const std::exception& e_) { report_ << " std::exception thrown" << std::endl << " what: " << e_.what() << std::endl << " Test case: " << _name << std::endl; } catch (...) { report_ << " Exception thrown" << std::endl << " Test case: " << _name << std::endl; } return false; } private: void (*_f)(); std::string _name; }; /* * test_manager */ class test_manager { public: void add(const std::string& name_, void (*f_)()) { _cases.push_back(test_case(name_, f_)); } bool run(std::ostream& report_) const { int failures = 0; for ( std::vector<test_case>::const_iterator i = _cases.begin(), e = _cases.end(); i != e; ++i ) { if (!i->run(report_)) { ++failures; } } report_ << _cases.size() << " test cases finished." << std::endl; if (failures > 0) { report_ << " " << failures << " failed." << std::endl; } else { report_ << " All succeeded." << std::endl; } return failures == 0; } private: std::vector<test_case> _cases; }; /* * singleton */ // This assumes, that pointers are 0 initialised at startup // It never destroys the object template <class T> class singleton { public: static T& get() { if (!_t) { _t = new T(); } return *_t; } private: static T* _t; }; template <class T> T* singleton<T>::_t = 0; /* * run */ inline int run(int, char *[]) { return singleton<test_manager>::get().run(std::cerr) ? 0 : 1; } /* * assert_msg */ class assert_msg { public: assert_msg(const std::string& filename_, int line_) : _filename(filename_), _line(line_) {} void operator()(const std::string& msg_, bool v_) const { if (!v_) { throw assertion_failed(msg_, _filename, _line); } } void operator()(bool v_) const { operator()("Assertion failed", v_); } private: std::string _filename; int _line; }; /* * assert operations */ #ifdef JUST_TEST_ASSERT_OP # error JUST_TEST_ASSERT_OP already defined #endif #define JUST_TEST_ASSERT_OP(name, pred) \ class name \ { \ public: \ name(const std::string& filename_, int line_) : \ _assert_msg(filename_, line_) \ {} \ \ template <class A, class B> \ void operator()(A a_, B b_) const \ { \ std::ostringstream s; \ s << "Expected: " << a_ << " " #pred " " << b_; \ _assert_msg(s.str(), a_ pred b_); \ } \ private: \ assert_msg _assert_msg; \ } JUST_TEST_ASSERT_OP(assert_equal, ==); JUST_TEST_ASSERT_OP(assert_not_equal, !=); JUST_TEST_ASSERT_OP(assert_less, <); JUST_TEST_ASSERT_OP(assert_less_equal, <=); JUST_TEST_ASSERT_OP(assert_greater, >); JUST_TEST_ASSERT_OP(assert_greater_equal, >=); #undef JUST_TEST_ASSERT_OP } } /* * Test case definition */ #ifdef JUST_TEST_CASE # error JUST_TEST_CASE already defined #endif #define JUST_TEST_CASE(name) \ void just_test_test_case_f_ ## name(); \ \ struct just_test_test_case_ ## name \ { \ just_test_test_case_ ## name() \ { \ ::just::test::singleton< ::just::test::test_manager >::get().add( \ #name, &just_test_test_case_f_ ## name \ ); \ } \ }; \ just_test_test_case_ ## name just_test_test_case_instance_ ## name; \ \ void just_test_test_case_f_ ## name() /* * Assertion macros */ #ifdef JUST_ASSERT # error JUST_ASSERT already defined #endif #define JUST_ASSERT ::just::test::assert_msg(__FILE__, __LINE__) #ifdef JUST_ASSERT_EQUAL # error JUST_ASSERT_EQUAL already defined #endif #define JUST_ASSERT_EQUAL ::just::test::assert_equal(__FILE__, __LINE__) #ifdef JUST_ASSERT_NOT_EQUAL # error JUST_ASSERT_NOT_EQUAL already defined #endif #define JUST_ASSERT_NOT_EQUAL ::just::test::assert_not_equal(__FILE__, __LINE__) #ifdef JUST_ASSERT_LESS # error JUST_ASSERT_LESS already defined #endif #define JUST_ASSERT_LESS ::just::test::assert_less(__FILE__, __LINE__) #ifdef JUST_ASSERT_LESS_EQUAL # error JUST_ASSERT_LESS_EQUAL already defined #endif #define JUST_ASSERT_LESS_EQUAL \ ::just::test::assert_less_equal(__FILE__, __LINE__) #ifdef JUST_ASSERT_GREATER # error JUST_ASSERT_GREATER already defined #endif #define JUST_ASSERT_GREATER ::just::test::assert_greater(__FILE__, __LINE__) #ifdef JUST_ASSERT_GREATER_EQUAL # error JUST_ASSERT_GREATER_EQUAL already defined #endif #define JUST_ASSERT_GREATER_EQUAL \ ::just::test::assert_greater_equal(__FILE__, __LINE__) #ifdef JUST_ASSERT_THROWS # error JUST_ASSERT_THROWS #endif #define JUST_ASSERT_THROWS(exc, expr) \ { \ bool __just_test_expression_threw = false; \ try \ { \ (expr); \ } \ catch (const exc&) \ { \ __just_test_expression_threw = true; \ } \ catch (...) \ { \ throw ::just::test::assertion_failed( \ "Expected to throw " #exc " but threw something else.", \ __FILE__, \ __LINE__ \ ); \ } \ if (!__just_test_expression_threw) \ { \ throw \ ::just::test::assertion_failed( \ "Expected to throw " #exc, \ __FILE__, \ __LINE__ \ ); \ } \ } #ifdef JUST_ASSERT_THROWS_SOMETHING # error JUST_ASSERT_THROWS_SOMETHING #endif #define JUST_ASSERT_THROWS_SOMETHING(expr) \ { \ bool __just_test_expression_threw = false; \ try \ { \ (expr); \ } \ catch (...) { \ __just_test_expression_threw = true; \ } \ if (!__just_test_expression_threw) \ { \ throw \ ::just::test::assertion_failed( \ "Expected to throw ", \ __FILE__, \ __LINE__ \ ); \ } \ } /* * Macro for defining a main function */ #ifdef JUST_TEST_DEFINE_MAIN # error JUST_TEST_DEFINE_MAIN already defined #endif #define JUST_TEST_DEFINE_MAIN \ int main(int argc_, char* argv_[]) \ { \ return ::just::test::run(argc_, argv_); \ } #endif
21.973262
80
0.553784
62d2ddf952e573be0f198c825ffdbc27578ee2d0
2,023
cpp
C++
libhpx/scheduler/events.cpp
luglio/hpx5
6cbeebb8e730ee9faa4487dba31a38e3139e1ce7
[ "BSD-3-Clause" ]
1
2021-05-21T16:54:43.000Z
2021-05-21T16:54:43.000Z
libhpx/scheduler/events.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
null
null
null
libhpx/scheduler/events.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
3
2019-06-21T07:05:43.000Z
2020-11-21T15:24:04.000Z
// ============================================================================= // High Performance ParalleX Library (libhpx) // // Copyright (c) 2013-2017, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "libhpx/Worker.h" #include "libhpx/events.h" #include "libhpx/parcel.h" #include "hpx/hpx.h" namespace { using libhpx::Worker; } void Worker::EVENT_THREAD_RUN(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX // if this is NOT a null or lightweight action, send a "start" event to APEX if (p->action != hpx_lco_set_action) { CHECK_ACTION(p->action); void* handler = (void*)actions[p->action].handler; profiler_ = (void*)(apex_start(APEX_FUNCTION_ADDRESS, handler)); } #endif EVENT_PARCEL_RUN(p->id, p->action, p->size); } void Worker::EVENT_THREAD_END(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (profiler_ != NULL) { apex_stop((apex_profiler_handle)(profiler_)); profiler_ = NULL; } #endif EVENT_PARCEL_END(p->id, p->action); } void Worker::EVENT_THREAD_SUSPEND(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (profiler_ != NULL) { apex_stop((apex_profiler_handle)(profiler_)); profiler_ = NULL; } #endif EVENT_PARCEL_SUSPEND(p->id, p->action); } void Worker::EVENT_THREAD_RESUME(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (p->action != hpx_lco_set_action) { void* handler = (void*)actions[p->action].handler; profiler_ = (void*)(apex_resume(APEX_FUNCTION_ADDRESS, handler)); } #endif EVENT_PARCEL_RESUME(p->id, p->action); }
23.8
80
0.630746
62d8c6581a358517d4a8e20777178ac28fc2767c
16,104
cpp
C++
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
1,323
2015-01-02T08:33:08.000Z
2022-03-31T22:57:08.000Z
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
267
2015-01-21T05:34:55.000Z
2022-03-29T18:38:21.000Z
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
610
2015-01-02T08:33:38.000Z
2022-03-31T03:04:06.000Z
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg 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 <dynamicEDT3D/dynamicEDT3D.h> #include <math.h> #include <stdlib.h> #define FOR_EACH_NEIGHBOR_WITH_CHECK(function, p, ...) \ int x=p.x;\ int y=p.y;\ int z=p.z;\ int xp1 = x+1;\ int xm1 = x-1;\ int yp1 = y+1;\ int ym1 = y-1;\ int zp1 = z+1;\ int zm1 = z-1;\ \ if(z<sizeZm1) function(x, y, zp1, ##__VA_ARGS__);\ if(z>0) function(x, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(x, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(x, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, ym1, zm1, ##__VA_ARGS__);\ }\ \ \ if(x<sizeXm1){\ function(xp1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xp1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xp1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, ym1, zm1, ##__VA_ARGS__);\ }\ }\ \ if(x>0){\ function(xm1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xm1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xm1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, ym1, zm1, ##__VA_ARGS__);\ }\ } float DynamicEDT3D::distanceValue_Error = -1.0; int DynamicEDT3D::distanceInCellsValue_Error = -1; DynamicEDT3D::DynamicEDT3D(int _maxdist_squared) { sqrt2 = sqrt(2.0); maxDist_squared = _maxdist_squared; maxDist = sqrt((double) maxDist_squared); data = NULL; gridMap = NULL; } DynamicEDT3D::~DynamicEDT3D() { if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } } void DynamicEDT3D::initializeEmpty(int _sizeX, int _sizeY, int _sizeZ, bool initGridMap) { sizeX = _sizeX; sizeY = _sizeY; sizeZ = _sizeZ; sizeXm1 = sizeX-1; sizeYm1 = sizeY-1; sizeZm1 = sizeZ-1; if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } data = new dataCell**[sizeX]; for (int x=0; x<sizeX; x++){ data[x] = new dataCell*[sizeY]; for(int y=0; y<sizeY; y++) data[x][y] = new dataCell[sizeZ]; } if (initGridMap) { if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } gridMap = new bool**[sizeX]; for (int x=0; x<sizeX; x++){ gridMap[x] = new bool*[sizeY]; for (int y=0; y<sizeY; y++) gridMap[x][y] = new bool[sizeZ]; } } dataCell c; c.dist = maxDist; c.sqdist = maxDist_squared; c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = fwNotQueued; c.needsRaise = false; for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++){ for (int z=0; z<sizeZ; z++){ data[x][y][z] = c; } } } if (initGridMap) { for (int x=0; x<sizeX; x++) for (int y=0; y<sizeY; y++) for (int z=0; z<sizeZ; z++) gridMap[x][y][z] = 0; } } void DynamicEDT3D::initializeMap(int _sizeX, int _sizeY, int _sizeZ, bool*** _gridMap) { gridMap = _gridMap; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); for (int x=0; x<sizeX; x++) { for (int y=0; y<sizeY; y++) { for (int z=0; z<sizeZ; z++) { if (gridMap[x][y][z]) { dataCell c = data[x][y][z]; if (!isOccupied(x,y,z,c)) { bool isSurrounded = true; for (int dx=-1; dx<=1; dx++) { int nx = x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = z+dz; if (nz<0 || nz>sizeZ-1) continue; if (!gridMap[nx][ny][nz]) { isSurrounded = false; break; } } } } if (isSurrounded) { c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0; c.queueing = fwProcessed; data[x][y][z] = c; } else setObstacle(x,y,z); } } } } } } void DynamicEDT3D::occupyCell(int x, int y, int z) { gridMap[x][y][z] = 1; setObstacle(x,y,z); } void DynamicEDT3D::clearCell(int x, int y, int z) { gridMap[x][y][z] = 0; removeObstacle(x,y,z); } void DynamicEDT3D::setObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c)) return; addList.push_back(INTPOINT3D(x,y,z)); c.obstX = x; c.obstY = y; c.obstZ = z; data[x][y][z] = c; } void DynamicEDT3D::removeObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c) == false) return; removeList.push_back(INTPOINT3D(x,y,z)); c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = bwQueued; data[x][y][z] = c; } void DynamicEDT3D::exchangeObstacles(std::vector<INTPOINT3D> points) { for (unsigned int i=0; i<lastObstacles.size(); i++) { int x = lastObstacles[i].x; int y = lastObstacles[i].y; int z = lastObstacles[i].z; bool v = gridMap[x][y][z]; if (v) continue; removeObstacle(x,y,z); } lastObstacles.clear(); for (unsigned int i=0; i<points.size(); i++) { int x = points[i].x; int y = points[i].y; int z = points[i].z; bool v = gridMap[x][y][z]; if (v) continue; setObstacle(x,y,z); lastObstacles.push_back(points[i]); } } void DynamicEDT3D::update(bool updateRealDist) { commitAndColorize(updateRealDist); while (!open.empty()) { INTPOINT3D p = open.pop(); int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing==fwProcessed) continue; if (c.needsRaise) { // RAISE raiseCell(p, c, updateRealDist); data[x][y][z] = c; } else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,c.obstZ,data[c.obstX][c.obstY][c.obstZ])) { // LOWER propagateCell(p, c, updateRealDist); data[x][y][z] = c; } } } void DynamicEDT3D::raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellRaise(nx,ny,nz, updateRealDist); } } } */ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellRaise,p, updateRealDist) c.needsRaise = false; c.queueing = bwProcessed; } void DynamicEDT3D::inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if (nc.obstX!=invalidObstData && !nc.needsRaise) { if(!isOccupied(nc.obstX,nc.obstY,nc.obstZ,data[nc.obstX][nc.obstY][nc.obstZ])) { open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; nc.needsRaise = true; nc.obstX = invalidObstData; nc.obstY = invalidObstData; nc.obstZ = invalidObstData; if (updateRealDist) nc.dist = maxDist; nc.sqdist = maxDist_squared; data[nx][ny][nz] = nc; } else { if(nc.queueing != fwQueued){ open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; data[nx][ny][nz] = nc; } } } } void DynamicEDT3D::propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ c.queueing = fwProcessed; /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellPropagate(nx, ny, nz, c, updateRealDist); } } } */ if(c.sqdist==0){ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellPropagate, p, c, updateRealDist) } else { int x=p.x; int y=p.y; int z=p.z; int xp1 = x+1; int xm1 = x-1; int yp1 = y+1; int ym1 = y-1; int zp1 = z+1; int zm1 = z-1; int dpx = (x - c.obstX); int dpy = (y - c.obstY); int dpz = (z - c.obstZ); // dpy=0; // dpz=0; if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(x, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(x, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, ym1, zm1, c, updateRealDist); } if(dpx>=0 && x<sizeXm1){ inspectCellPropagate(xp1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xp1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xp1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, ym1, zm1, c, updateRealDist); } } if(dpx<=0 && x>0){ inspectCellPropagate(xm1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xm1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xm1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, ym1, zm1, c, updateRealDist); } } } } void DynamicEDT3D::inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if(!nc.needsRaise) { int distx = nx-c.obstX; int disty = ny-c.obstY; int distz = nz-c.obstZ; int newSqDistance = distx*distx + disty*disty + distz*distz; if(newSqDistance > maxDist_squared) newSqDistance = maxDist_squared; bool overwrite = (newSqDistance < nc.sqdist); if(!overwrite && newSqDistance==nc.sqdist) { //the neighbor cell is marked to be raised, has no valid source obstacle if (nc.obstX == invalidObstData){ overwrite = true; } else { //the neighbor has no valid source obstacle but the raise wave has not yet reached it dataCell tmp = data[nc.obstX][nc.obstY][nc.obstZ]; if((tmp.obstX==nc.obstX && tmp.obstY==nc.obstY && tmp.obstZ==nc.obstZ)==false) overwrite = true; } } if (overwrite) { if(newSqDistance < maxDist_squared){ open.push(newSqDistance, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; } if (updateRealDist) { nc.dist = sqrt((double) newSqDistance); } nc.sqdist = newSqDistance; nc.obstX = c.obstX; nc.obstY = c.obstY; nc.obstZ = c.obstZ; } data[nx][ny][nz] = nc; } } float DynamicEDT3D::getDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].dist; } else return distanceValue_Error; } INTPOINT3D DynamicEDT3D::getClosestObstacle( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ dataCell c = data[x][y][z]; return INTPOINT3D(c.obstX, c.obstY, c.obstZ); } else return INTPOINT3D(invalidObstData, invalidObstData, invalidObstData); } int DynamicEDT3D::getSQCellDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].sqdist; } else return distanceInCellsValue_Error; } void DynamicEDT3D::commitAndColorize(bool updateRealDist) { // ADD NEW OBSTACLES for (unsigned int i=0; i<addList.size(); i++) { INTPOINT3D p = addList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing != fwQueued){ if (updateRealDist) c.dist = 0; c.sqdist = 0; c.obstX = x; c.obstY = y; c.obstZ = z; c.queueing = fwQueued; data[x][y][z] = c; open.push(0, INTPOINT3D(x,y,z)); } } // REMOVE OLD OBSTACLES for (unsigned int i=0; i<removeList.size(); i++) { INTPOINT3D p = removeList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if (isOccupied(x,y,z,c)==true) continue; // obstacle was removed and reinserted open.push(0, INTPOINT3D(x,y,z)); if (updateRealDist) c.dist = maxDist; c.sqdist = maxDist_squared; c.needsRaise = true; data[x][y][z] = c; } removeList.clear(); addList.clear(); } bool DynamicEDT3D::isOccupied(int x, int y, int z) const { dataCell c = data[x][y][z]; return (c.obstX==x && c.obstY==y && c.obstZ==z); } bool DynamicEDT3D::isOccupied(int &x, int &y, int &z, dataCell &c) { return (c.obstX==x && c.obstY==y && c.obstZ==z); }
27.202703
112
0.613885
62e0aa2965d32d1d3c12ecf9565dca58fe324e95
4,543
hpp
C++
server/drivers/laser.hpp
Koheron/koheron-sdk
82b732635f1adf5dd0b04b9290b589c1fc091f29
[ "MIT" ]
77
2016-09-20T18:44:14.000Z
2022-03-30T16:04:09.000Z
server/drivers/laser.hpp
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
101
2016-09-05T15:44:25.000Z
2022-03-29T09:22:09.000Z
server/drivers/laser.hpp
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
34
2016-12-12T07:21:57.000Z
2022-01-12T21:00:52.000Z
/// Laser controller /// /// (c) Koheron #ifndef __DRIVERS_LASER_CONTROLLER_HPP__ #define __DRIVERS_LASER_CONTROLLER_HPP__ #include <context.hpp> #include <xadc.hpp> #include <eeprom.hpp> #include <chrono> namespace Laser_params { constexpr uint32_t power_channel = 1; //xadc channel constexpr uint32_t current_channel = 8; //xadc channel constexpr float max_laser_current = 50.0; // mA constexpr float current_gain = 47.7; // mA/V constexpr float pwm_max_voltage = 1.8; // V constexpr float pwm_max_value = (1 << prm::pwm_width); constexpr float current_to_pwm = pwm_max_value / ( current_gain * pwm_max_voltage); constexpr float measured_current_gain = current_gain * 1E-7F; } class Laser { public: Laser(Context& ctx_) : ctx(ctx_) , ctl(ctx.mm.get<mem::control>()) , sts(ctx.mm.get<mem::status>()) , xadc(ctx.get<Xadc>()) , eeprom(ctx.get<Eeprom>()) { stop(); current = 0; set_current(current); read_calibration(); } void start() { ctl.clear_bit<reg::laser_control, 0>(); laser_on = true; } void stop() { ctl.set_bit<reg::laser_control, 0>(); laser_on = false; } void set_current(float current_value) { if (constant_power_on == true) { // Switch to constant current mode ctl.clear_bit<reg::laser_control, 2>(); constant_power_on = false; } current = std::min(current_value, Laser_params::max_laser_current); ctl.write<reg::laser_current>(uint32_t(current * Laser_params::current_to_pwm)); } void set_power(float power_value) { if (constant_power_on == false) { // Switch to constant power_mode ctl.set_bit<reg::laser_control, 2>(); constant_power_on = true; } power = power_value; ctl.write<reg::power_setpoint>(uint32_t((power_1mW - power_0mW) / 1000.0F * power_value + power_0mW)); } float get_measured_current() { return Laser_params::measured_current_gain * float(xadc.read(Laser_params::current_channel)); } float get_measured_power() { return 1000 * (float(xadc.read(Laser_params::power_channel)) - power_0mW) / (power_1mW - power_0mW); } void switch_mode() { if (!constant_power_on) { if (laser_on) { // integral reset stop(); start(); } set_power(get_measured_power()); } else { set_current(sts.read<reg::pid_control>() / Laser_params::current_to_pwm); } } auto get_status() { float measured_current = get_measured_current(); float measured_power = get_measured_power(); return std::make_tuple( laser_on, constant_power_on, is_calibrated, current, power, measured_current, measured_power ); } void read_calibration() { if (eeprom.read(0) == 1) { is_calibrated = true; power_0mW = eeprom.read(1); power_1mW = eeprom.read(2); } else { is_calibrated = false; power_0mW = 300; power_1mW = 1850; } } void calibrate_0mW() { using namespace std::chrono_literals; stop(); std::this_thread::sleep_for(200ms); uint32_t sum = 0; for (auto i = 0; i<100; i++) { sum += xadc.read(Laser_params::power_channel); } eeprom.write(1, sum/100); std::this_thread::sleep_for(5ms); ctx.log<INFO>("Power 0mW = %u\n", eeprom.read(1)); set_current(15.0); start(); } void calibrate_1mW() { using namespace std::chrono_literals; uint32_t sum = 0; for (auto i = 0; i<100; i++) { sum += xadc.read(Laser_params::power_channel); } eeprom.write(2, sum/100); std::this_thread::sleep_for(5ms); eeprom.write(0, 1); std::this_thread::sleep_for(5ms); ctx.log<INFO>("Power 1mW = %u\n", eeprom.read(2)); read_calibration(); } private: float current; float power; bool laser_on; bool constant_power_on; bool is_calibrated; Context& ctx; Memory<mem::control>& ctl; Memory<mem::status>& sts; Xadc& xadc; // Calibration Eeprom& eeprom; uint32_t power_0mW; uint32_t power_1mW; }; #endif // __DRIVERS_LASER_HPP__
27.70122
110
0.580233
62e10d8a12b4458cb11b750206a6dd865e96bda7
1,409
cpp
C++
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
#include "mps.h" #include <chrono> #include <iostream> #include <thread> using namespace mps; constexpr auto MessageCount = 100; constexpr auto MessageInterval = std::chrono::seconds(1); int main(int argc, char* argv[]) { // sanity check to check that we have enough arguments. if (argc != 3) { std::cout << "Usage: <executable> <broadcast-ip> <broadcast-port>" << std::endl; return -1; } try { // parse host and port from the commandline arguments. auto host = std::string(argv[1]); auto port = std::stoi(argv[2]); auto broadcastAddr = Address(host, port); // build and bind a new UDP socket and enable broadcasting. UDPSocket socket(broadcastAddr.getFamily()); socket.setBroadcasting(true); // broadcast messages N-times with the provided interval. std::cout << "Starting UDP broadcast to "; std::cout << broadcastAddr.getAddress(); std::cout << ":"; std::cout << broadcastAddr.getPort(); std::cout << std::endl; for (auto i = MessageCount; i > 0; i--) { socket.send(UDPPacket{ broadcastAddr, {'p','i','n','g','\0'} }); std::cout << "[ping]" << std::endl; std::this_thread::sleep_for(MessageInterval); } } catch (const AddressException& e){ std::cerr << "Error: " << e.what() << std::endl; } catch (const SocketException& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
29.978723
84
0.623847
62e129e1a0700bd08da225c5523b2a8f02826b91
1,259
cpp
C++
ArchiveOldCode/Examples/VideoCapture/videoCapture.cpp
SahSih/seniorProject
48c9d5463f47b1dadd6e6407be9ec97d0dcb9f6d
[ "MIT" ]
null
null
null
ArchiveOldCode/Examples/VideoCapture/videoCapture.cpp
SahSih/seniorProject
48c9d5463f47b1dadd6e6407be9ec97d0dcb9f6d
[ "MIT" ]
6
2017-05-11T05:06:35.000Z
2017-08-09T08:04:19.000Z
ArchiveOldCode/Examples/VideoCapture/videoCapture.cpp
SahSih/seniorProject
48c9d5463f47b1dadd6e6407be9ec97d0dcb9f6d
[ "MIT" ]
5
2017-05-11T05:16:35.000Z
2017-10-19T19:13:54.000Z
#include "opencv2/highgui/highgui.hpp" #include <iostream> using namespace cv; using namespace std; int main(int argc, char* argv[]) { VideoCapture cap(0); // open the video camera no. 0 if (!cap.isOpened()) // if not success, exit program { cout << "Cannot open the video cam" << endl; return -1; } double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout << "Frame size : " << dWidth << " x " << dHeight << endl; namedWindow("Camera1_stream",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo" while (1) { Mat frame; bool bSuccess = cap.read(frame); // read a new frame from video if (!bSuccess) //if not success, break loop { cout << "Cannot read a frame from video stream" << endl; break; } imshow("Camera1_stream", frame); //show the frame in "MyVideo" window if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop { cout << "esc key is pressed by user" << endl; break; } } return 0; }
27.369565
103
0.591739
62e13304ec181f0310e516012ce590692c08d901
816
cpp
C++
src/core/hooks/vmt.cpp
Metaphysical1/gamesneeze
59d31ee232bbcc80d29329e0f64ebdde599c37df
[ "MIT" ]
1,056
2020-11-17T11:49:12.000Z
2022-03-23T12:32:42.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
102
2021-01-15T12:05:18.000Z
2022-02-26T00:19:58.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
121
2020-11-18T12:08:21.000Z
2022-03-31T07:14:32.000Z
#include "vmt.hpp" #include <stdint.h> #include <unistd.h> #include <sys/mman.h> int pagesize = sysconf(_SC_PAGE_SIZE); int pagemask = ~(pagesize-1); int unprotect(void* region) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, PROT_READ|PROT_WRITE|PROT_EXEC); return PROT_READ|PROT_EXEC; } void protect(void* region, int protection) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, protection); } void* VMT::hook(void* instance, void* hook, int offset) { intptr_t vtable = *((intptr_t*)instance); intptr_t entry = vtable + sizeof(intptr_t) * offset; intptr_t original = *((intptr_t*) entry); int originalProtection = unprotect((void*)entry); *((intptr_t*)entry) = (intptr_t)hook; protect((void*)entry, originalProtection); return (void*)original; }
29.142857
94
0.689951
62e3bd7300b6b02046f63cfc9a9f10f1fd142005
335
cpp
C++
flatland_plugins/src/simple.cpp
alanhesu/flatland
dcd9e913060daf50d5bcd0a4ee5fec7179fd85e8
[ "BSD-3-Clause" ]
null
null
null
flatland_plugins/src/simple.cpp
alanhesu/flatland
dcd9e913060daf50d5bcd0a4ee5fec7179fd85e8
[ "BSD-3-Clause" ]
null
null
null
flatland_plugins/src/simple.cpp
alanhesu/flatland
dcd9e913060daf50d5bcd0a4ee5fec7179fd85e8
[ "BSD-3-Clause" ]
null
null
null
#include <flatland_plugins/simple.h> #include <pluginlib/class_list_macros.h> #include <ros/ros.h> using namespace flatland_server; namespace flatland_plugins { void Simple::OnInitialize(const YAML::Node &config) { ROS_ERROR_STREAM("Hello world"); } }; PLUGINLIB_EXPORT_CLASS(flatland_plugins::Simple, flatland_server::ModelPlugin)
23.928571
78
0.802985
62e4dfb00af1391c38f7a90a6cc2ef23b2be0d67
10,425
cpp
C++
loop-functions/moca/TuttiFrLoopFunc.cpp
AmmarHsn/loop_functions
b8978d33242065bd100219d9a934f2281153d521
[ "MIT" ]
null
null
null
loop-functions/moca/TuttiFrLoopFunc.cpp
AmmarHsn/loop_functions
b8978d33242065bd100219d9a934f2281153d521
[ "MIT" ]
null
null
null
loop-functions/moca/TuttiFrLoopFunc.cpp
AmmarHsn/loop_functions
b8978d33242065bd100219d9a934f2281153d521
[ "MIT" ]
null
null
null
/** * @file <loop-functions/IcraLoopFunc.cpp> * * @author Antoine Ligot - <aligot@ulb.ac.be> * * @license MIT License */ #include "TuttiFrLoopFunc.h" /****************************************/ /****************************************/ TuttiFrLoopFunction::TuttiFrLoopFunction() { m_unClock = 0; m_fObjectiveFunction = 0; } /****************************************/ /****************************************/ TuttiFrLoopFunction::TuttiFrLoopFunction(const TuttiFrLoopFunction& orig) { } /****************************************/ /****************************************/ TuttiFrLoopFunction::~TuttiFrLoopFunction() {} /****************************************/ /****************************************/ void TuttiFrLoopFunction::Destroy() { m_tRobotStates.clear(); RemoveArena(); } /****************************************/ /****************************************/ void TuttiFrLoopFunction::Init(TConfigurationNode& t_tree) { CoreLoopFunctions::Init(t_tree); TConfigurationNode cParametersNode; try { cParametersNode = GetNode(t_tree, "params"); GetNodeAttributeOrDefault(cParametersNode, "build_arena", m_bBuildArena, (bool) false); GetNodeAttributeOrDefault(cParametersNode, "number_edges", m_unNumberEdges, (UInt32) 3); GetNodeAttributeOrDefault(cParametersNode, "number_boxes_per_edge", m_unNumberBoxes, (UInt32) 1); GetNodeAttributeOrDefault(cParametersNode, "lenght_boxes", m_fLenghtBoxes, (Real) 0.25); GetNodeAttributeOrDefault(cParametersNode, "maximization", m_bMaximization, (bool) false); } catch(std::exception e) { } if (m_bBuildArena == true) { m_fDistributionRadius = GetArenaRadious(); PositionArena(); } InitRobotStates(); } /****************************************/ /****************************************/ void TuttiFrLoopFunction::Reset() { CoreLoopFunctions::Reset(); m_unClock = 0; m_fObjectiveFunction = 0; m_tRobotStates.clear(); InitRobotStates(); } /****************************************/ /****************************************/ void TuttiFrLoopFunction::PostStep() { m_unClock = GetSpace().GetSimulationClock(); ScoreControl(); ArenaControl(); } /****************************************/ /****************************************/ void TuttiFrLoopFunction::PostExperiment() { if (m_bMaximization == true){ LOG << -m_fObjectiveFunction << std::endl; } else { LOG << m_fObjectiveFunction << std::endl; } } /****************************************/ /****************************************/ Real TuttiFrLoopFunction::GetObjectiveFunction() { if (m_bMaximization == true){ return -m_fObjectiveFunction; } else { return m_fObjectiveFunction; } } /****************************************/ /****************************************/ void TuttiFrLoopFunction::ArenaControl() { if (m_unClock == 1) { m_pcArena->SetBoxColor(1,4,CColor::BLUE); m_pcArena->SetBoxColor(2,4,CColor::BLUE); m_pcArena->SetBoxColor(3,4,CColor::BLUE); m_pcArena->SetBoxColor(4,4,CColor::GREEN); m_pcArena->SetBoxColor(5,4,CColor::GREEN); m_pcArena->SetBoxColor(6,4,CColor::GREEN); m_pcArena->SetWallColor(2,CColor::RED); } return; } /****************************************/ /****************************************/ void TuttiFrLoopFunction::ScoreControl(){ m_fObjectiveFunction += -GetForageScore(); } /****************************************/ /****************************************/ Real TuttiFrLoopFunction::GetForageScore() { UpdateRobotPositions(); bool bInNest; UInt32 unInSource; Real unScore = 0; TRobotStateMap::iterator it; for (it = m_tRobotStates.begin(); it != m_tRobotStates.end(); ++it) { if (it->second.unItem != 0){ unInSource = IsRobotInSourceID(it->second.cPosition); if (unInSource == 1) { it->second.unItem = 1; } else if (unInSource == 2) { it->second.unItem = 2; } else { bInNest = IsRobotInNest(it->second.cPosition); if (bInNest) { if (it->second.unItem == 1) { unScore-=1; } else if (it->second.unItem == 2) { unScore+=1; } it->second.unItem = 0; } } } else { unInSource = IsRobotInSourceID(it->second.cPosition); if (unInSource == 1) { it->second.unItem = 1; } else if (unInSource == 2) { it->second.unItem = 2; } } } return unScore; } /****************************************/ /****************************************/ argos::CColor TuttiFrLoopFunction::GetFloorColor(const argos::CVector2& c_position_on_plane) { if (c_position_on_plane.GetX() <= -0.60){ return CColor::WHITE; } else if (c_position_on_plane.GetX() >= 0.60){ return CColor::BLACK; } return CColor::GRAY50; } /****************************************/ /****************************************/ bool TuttiFrLoopFunction::IsRobotInNest (CVector2 tRobotPosition) { if (tRobotPosition.GetX() <= -0.565) return true; return false; } /****************************************/ /****************************************/ UInt32 TuttiFrLoopFunction::IsRobotInSourceID (CVector2 tRobotPosition){ UInt32 unSourceId = 0; if (tRobotPosition.GetX() >= 0.565) { if (tRobotPosition.GetY() <= -0.006) unSourceId = 1; else if (tRobotPosition.GetY() >= 0.006) unSourceId = 2; } return unSourceId; } /****************************************/ /****************************************/ void TuttiFrLoopFunction::UpdateRobotPositions() { CSpace::TMapPerType& tEpuckMap = GetSpace().GetEntitiesByType("epuck"); CVector2 cEpuckPosition(0,0); for (CSpace::TMapPerType::iterator it = tEpuckMap.begin(); it != tEpuckMap.end(); ++it) { CEPuckEntity* pcEpuck = any_cast<CEPuckEntity*>(it->second); cEpuckPosition.Set(pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetX(), pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetY()); m_tRobotStates[pcEpuck].cLastPosition = m_tRobotStates[pcEpuck].cPosition; m_tRobotStates[pcEpuck].cPosition = cEpuckPosition; } } /****************************************/ /****************************************/ void TuttiFrLoopFunction::InitRobotStates() { CSpace::TMapPerType& tEpuckMap = GetSpace().GetEntitiesByType("epuck"); CVector2 cEpuckPosition(0,0); for (CSpace::TMapPerType::iterator it = tEpuckMap.begin(); it != tEpuckMap.end(); ++it) { CEPuckEntity* pcEpuck = any_cast<CEPuckEntity*>(it->second); cEpuckPosition.Set(pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetX(), pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetY()); m_tRobotStates[pcEpuck].cLastPosition = cEpuckPosition; m_tRobotStates[pcEpuck].cPosition = cEpuckPosition; m_tRobotStates[pcEpuck].unItem = 0; } } /****************************************/ /****************************************/ CVector3 TuttiFrLoopFunction::GetRandomPosition() { Real temp; Real a = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f)); Real b = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f)); Real c = m_pcRng->Uniform(CRange<Real>(-1.0f, 1.0f)); Real d = m_pcRng->Uniform(CRange<Real>(-1.0f, 1.0f)); // If b < a, swap them if (b < a) { temp = a; a = b; b = temp; } m_fDistributionRadius = 0.4; Real fPosX = (c * m_fDistributionRadius / 2) + m_fDistributionRadius * cos(2 * CRadians::PI.GetValue() * (a/b)); Real fPosY = (d * m_fDistributionRadius / 2) + m_fDistributionRadius * sin(2 * CRadians::PI.GetValue() * (a/b)); return CVector3(fPosX, fPosY, 0); } /****************************************/ /****************************************/ void TuttiFrLoopFunction::PositionArena() { CArenaEntity* pcArena; /* pcArena = new CArenaEntity("arena", CVector3(0,0,0), CQuaternion().FromEulerAngles(CRadians::ZERO,CRadians::ZERO,CRadians::ZERO), // TODO CVector3(0.01,m_fLenghtBoxes,0.1), "leds", m_unNumberBoxes, m_unNumberEdges, 0.017f, 1.0f); */ // arena with 12 leds per block pcArena = new CArenaEntity("arena", CVector3(0,0,0), CQuaternion().FromEulerAngles(CRadians::ZERO,CRadians::ZERO,CRadians::ZERO), // TODO CVector3(0.01,m_fLenghtBoxes,0.1), "leds", m_unNumberBoxes, m_unNumberEdges, 0.125f, 1.0f); AddEntity(*pcArena); m_pcArena = pcArena; } /****************************************/ /****************************************/ void TuttiFrLoopFunction::RemoveArena() { std::ostringstream id; id << "arena"; RemoveEntity(id.str().c_str()); } /****************************************/ /****************************************/ Real TuttiFrLoopFunction::GetArenaRadious() { Real fRadious; fRadious = (m_fLenghtBoxes*m_unNumberBoxes) / (2 * Tan(CRadians::PI / m_unNumberEdges)); //fRadious = fRadious - 0.10; // Avoids to place robots close the walls. fRadious = fRadious - 0.65; // Reduced cluster at the begining return fRadious; } /****************************************/ /****************************************/ bool TuttiFrLoopFunction::IsEven(UInt32 unNumber) { bool even; if((unNumber%2)==0) even = true; else even = false; return even; } /****************************************/ /****************************************/ REGISTER_LOOP_FUNCTIONS(TuttiFrLoopFunction, "tutti_fr_loop_function");
28.798343
115
0.483453
62e8b82ae340868a4bdd8ab29df1733b2677d8a7
6,723
hpp
C++
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
6
2015-01-07T17:29:40.000Z
2019-03-28T15:18:27.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2017-04-12T19:01:21.000Z
2017-04-14T16:18:38.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2018-01-15T07:32:24.000Z
2020-10-14T02:55:55.000Z
/** * $Id$ * * Copyright (C) * 2014 - $Date$ * Martin Wolf <boostnumpy@martin-wolf.org> * This file has been adopted from <boost/python/detail/caller.hpp>. * * @file boost/numpy/dstream/detail/caller.hpp * @version $Revision$ * @date $Date$ * @author Martin Wolf <boostnumpy@martin-wolf.org> * * @brief This file defines the caller template that is used as the caller * implementation for boost::python of boost::numpy generalized universal * functions. * * This file is 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). */ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #define BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/preprocessor/if.hpp> #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/facilities/intercept.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/size.hpp> // For this dedicated caller, we use function templates from the boost::python // caller. #include <boost/python/detail/caller.hpp> #include <boost/numpy/limits.hpp> namespace boost { namespace numpy { namespace dstream { namespace detail { template <unsigned> struct invoke_arity; template <unsigned> struct caller_arity; // The +1 is for the class instance and the +2 is for the possible automatically // added extra arguments ("out" and "nthreads"). // The minimum input arity is forced to be 1 instead of 0 because a vectorized // function with no input is just non-sense. #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (1, BOOST_NUMPY_LIMIT_INPUT_ARITY + 1 + 2, <boost/numpy/dstream/detail/caller.hpp>)) #include BOOST_PP_ITERATE() template <class Callable> struct caller_base_select { // Note: arity includes the class type if Callable::f_t is a member function // pointer. BOOST_STATIC_CONSTANT(unsigned, arity = boost::mpl::size<typename Callable::signature_t>::value - 1); typedef typename caller_arity<arity>::template impl<Callable> type; }; template <class Callable> struct caller : caller_base_select<Callable>::type { typedef typename caller_base_select<Callable>::type base; caller(Callable ca) : base(ca) {} }; }// namespace detail }// namespace dstream }// namespace numpy }// namespace boost #endif // ! BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #else #define N BOOST_PP_ITERATION() template <> struct invoke_arity<N> { template <class RC, class Callable BOOST_PP_ENUM_TRAILING_PARAMS_Z(1, N, class AC)> inline static PyObject* invoke(RC const& rc, Callable const & ca BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(1, N, AC, & ac)) { return rc( ca(BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, ac, () BOOST_PP_INTERCEPT)) ); } }; template <> struct caller_arity<N> { template <class Callable> struct impl { // Since we will always take Python objects as arguments and return // Python objects, we will always use the default_call_policies as call // policies. typedef python::default_call_policies call_policies_t; impl(Callable ca) : m_callable(ca) {} PyObject* operator()(PyObject* args_, PyObject*) // eliminate // this // trailing // keyword dict { call_policies_t call_policies; typedef typename boost::mpl::begin<typename Callable::signature_t>::type first; //typedef typename first::type result_t; typedef typename python::detail::select_result_converter<call_policies_t, python::object>::type result_converter_t; typedef typename call_policies_t::argument_package argument_package_t; // Create argument from_python converter objects c#. argument_package_t inner_args(args_); #define BOOST_NUMPY_NEXT(init, name, n) \ typedef BOOST_PP_IF(n,typename boost::mpl::next< BOOST_PP_CAT(name,BOOST_PP_DEC(n)) >::type, init) name##n; #define BOOST_NUMPY_ARG_CONVERTER(n) \ BOOST_NUMPY_NEXT(typename boost::mpl::next<first>::type, arg_iter,n) \ typedef python::arg_from_python<BOOST_DEDUCED_TYPENAME BOOST_PP_CAT(arg_iter,n)::type> BOOST_PP_CAT(c_t,n); \ BOOST_PP_CAT(c_t,n) BOOST_PP_CAT(c,n)(python::detail::get(boost::mpl::int_<n>(), inner_args)); \ if(!BOOST_PP_CAT(c,n).convertible()) { \ return 0; \ } #define BOOST_NUMPY_DEF(z, n, data) \ BOOST_NUMPY_ARG_CONVERTER(n) BOOST_PP_REPEAT(N, BOOST_NUMPY_DEF, ~) #undef BOOST_NUMPY_DEF #undef BOOST_NUMPY_ARG_CONVERTER #undef BOOST_NUMPY_NEXT // All converters have been checked. Now we can do the // precall part of the policy. // Note: The precall of default_call_policies does nothing at all as // of boost::python <=1.55 but we keep this call for forward // compatibility and to follow the interface definition. if(!call_policies.precall(inner_args)) return 0; PyObject* result = invoke_arity<N>::invoke( python::detail::create_result_converter(args_, (result_converter_t*)0, (result_converter_t*)0) , m_callable BOOST_PP_ENUM_TRAILING_PARAMS(N, c) ); // Note: the postcall of default_call_policies does nothing at all // as of boost::python <=1.55 but we keep this call for // forward compatibility and to follow the interface // definition. return call_policies.postcall(inner_args, result); } static unsigned min_arity() { return N; } private: Callable m_callable; }; }; #undef N #endif // BOOST_PP_IS_ITERATING
34.834197
125
0.62844
62ecbe261582bd004825d91639ba33c012f6258a
2,604
cpp
C++
SysLib/Demand/Files/Matrix_File.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Matrix_File.cpp - Matrix File Input/Output //********************************************************* #include "Matrix_File.hpp" //----------------------------------------------------------- // Matrix_File constructors //----------------------------------------------------------- Matrix_File::Matrix_File (Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); } Matrix_File::Matrix_File (char *filename, Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); Open (filename); } //----------------------------------------------------------- // Matrix_File destructor //----------------------------------------------------------- Matrix_File::~Matrix_File (void) { } //----------------------------------------------------------- // Setup //----------------------------------------------------------- void Matrix_File::Setup (void) { File_Type ("Matrix File"); File_ID ("Matrix"); Period_Flag (false); org = des = period = data = 0; } //--------------------------------------------------------- // Create_Fields //--------------------------------------------------------- bool Matrix_File::Create_Fields (void) { if (Dbase_Format () == VERSION3) { Header_Lines (0); } Add_Field ("ORG", INTEGER, 5); Add_Field ("DES", INTEGER, 5); if (Period_Flag ()) { Add_Field ("PERIOD", INTEGER, 3); } Add_Field ("DATA", INTEGER, 10); return (Set_Field_Numbers ()); } //----------------------------------------------------------- // Set_Field_Numbers //----------------------------------------------------------- bool Matrix_File::Set_Field_Numbers (void) { //---- required fields ---- org = Required_Field ("ORG", "ORIGIN", "FROM", "FROM_ZONE", "I"); des = Required_Field ("DES", "DESTINATION", "TO", "TO_ZONE", "J"); if (!org || !des) return (false); //---- optional fields ---- period = Optional_Field ("PERIOD", "INTERVAL"); period_flag = (period != 0); data = Optional_Field ("DATA", "TRIPS"); if (data == 0) { if (Num_Fields () > 2 && org == 1 && des == 2) { if (period == 3) { data = 4; } else { data = 3; } } else { Required_Field ("DATA", "TRIPS"); return (false); } } return (true); } //----------------------------------------------------------- // Default_Definition //----------------------------------------------------------- bool Matrix_File::Default_Definition (void) { if (Dbase_Format () == VERSION3) { Create_Fields (); return (Write_Def_Header (NULL)); } else { return (false); } }
22.448276
84
0.422043
62eed194e14ec20219bfcc92913587fb6ffc1fd7
9,451
cc
C++
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2015-2018, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation are maintained by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: * classes: DSRIncludedTemplateTreeNode * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmsr/dsrtypes.h" #include "dcmtk/dcmsr/dsrtpltn.h" #include "dcmtk/dcmsr/dsrstpl.h" #include "dcmtk/dcmsr/dsrxmld.h" DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRSharedSubTemplate &referencedTemplate, const E_RelationshipType defaultRelType) : DSRDocumentTreeNode(defaultRelType, VT_includedTemplate), ReferencedTemplate(referencedTemplate) { if (ReferencedTemplate) { /* store template identification of the referenced template */ DSRDocumentTreeNode::setTemplateIdentification(ReferencedTemplate->getTemplateIdentifier(), ReferencedTemplate->getMappingResource(), ReferencedTemplate->getMappingResourceUID()); } } DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRIncludedTemplateTreeNode &node) : DSRDocumentTreeNode(node), ReferencedTemplate(node.ReferencedTemplate) { } DSRIncludedTemplateTreeNode::~DSRIncludedTemplateTreeNode() { } OFBool DSRIncludedTemplateTreeNode::operator==(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator==(node); if (result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() == OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } OFBool DSRIncludedTemplateTreeNode::operator!=(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator!=(node); if (!result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() != OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } DSRIncludedTemplateTreeNode *DSRIncludedTemplateTreeNode::clone() const { return new DSRIncludedTemplateTreeNode(*this); } void DSRIncludedTemplateTreeNode::clear() { DSRDocumentTreeNode::clear(); ReferencedTemplate.reset(); } OFBool DSRIncludedTemplateTreeNode::isValid() const { return DSRDocumentTreeNode::isValid() && hasValidValue(); } OFBool DSRIncludedTemplateTreeNode::hasValidValue() const { /* check whether the reference to the included template is valid */ return ReferencedTemplate ? OFTrue : OFFalse; } OFBool DSRIncludedTemplateTreeNode::isShort(const size_t /*flags*/) const { return !hasValidValue(); } OFCondition DSRIncludedTemplateTreeNode::print(STD_NAMESPACE ostream &stream, const size_t flags) const { stream << "# INCLUDE "; /* check whether template identification is set */ if (hasTemplateIdentification()) { OFString templateIdentifier, mappingResource; getTemplateIdentification(templateIdentifier, mappingResource); stream << "TID " << templateIdentifier << " (" << mappingResource << ")"; } else { /* no details on the template available */ stream << "<unknown template>"; } /* check whether default relationship type is specified */ if (getRelationshipType() != RT_unknown) stream << " with default relationship type " << relationshipTypeToDefinedTerm(getRelationshipType()); /* print annotation (optional) */ if (hasAnnotation() && (flags & PF_printAnnotation)) stream << " \"" << getAnnotation().getText() << "\""; return EC_Normal; } OFCondition DSRIncludedTemplateTreeNode::writeXML(STD_NAMESPACE ostream &stream, const size_t flags) const { OFCondition result = EC_Normal; /* write content of included template in XML format (if non-empty) */ if (hasValidValue() && !ReferencedTemplate->isEmpty()) { OFString templateIdentifier, mappingResource; /* output details on beginning of included template (if enabled) */ if (hasTemplateIdentification() && (flags & XF_addCommentsForIncludedTemplate)) { getTemplateIdentification(templateIdentifier, mappingResource); stream << "<!-- BEGIN: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } /* write content of referenced document subtree */ result = ReferencedTemplate->writeXML(stream, flags); /* output details on end of included template (if available, see above) */ if (!templateIdentifier.empty() && !mappingResource.empty()) stream << "<!-- END: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } return result; } OFCondition DSRIncludedTemplateTreeNode::setValue(const DSRSharedSubTemplate &referencedTemplate) { ReferencedTemplate = referencedTemplate; /* currently, no checks are performed */ return EC_Normal; } // protected methods OFCondition DSRIncludedTemplateTreeNode::read(DcmItem & /*dataset*/, const DSRIODConstraintChecker * /*constraintChecker*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::write(DcmItem & /*dataset*/, DcmStack * /*markedItems*/) { /* invalid: cannot write document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::readXML(const DSRXMLDocument & /*doc*/, DSRXMLCursor /*cursor*/, const E_DocumentType /*documentType*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::renderHTML(STD_NAMESPACE ostream & /*docStream*/, STD_NAMESPACE ostream & /*annexStream*/, const size_t /*nestingLevel*/, size_t & /*annexNumber*/, const size_t /*flags*/) const { /* invalid: cannot render document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::setConceptName(const DSRCodedEntryValue & /*conceptName*/, const OFBool /*check*/) { /* invalid: no concept name allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const OFString & /*observationDateTime*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const DcmElement & /*delem*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(DcmItem & /*dataset*/, const DcmTagKey & /*tagKey*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationUID(const OFString & /*observationUID*/, const OFBool /*check*/) { /* invalid: no observation unique identifier allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setTemplateIdentification(const OFString & /*templateIdentifier*/, const OFString & /*mappingResource*/, const OFString & /*mappingResourceUID*/, const OFBool /*check*/) { /* invalid: no manual setting of template identification allowed */ return EC_IllegalCall; }
35.799242
129
0.611575
62f634551b97e38323aebd4169816d37be6f3994
5,049
cc
C++
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
/* * ----------------------------------------------------------------------------- * Created by Ulysses Carlos on 03/25/2020 at 10:57 PM * * Chapter20_08.cc * * Define a function that counts the number of characters in a Document. * ----------------------------------------------------------------------------- */ #include <iostream> #include <list> #include <vector> #include <algorithm> #include <iterator> #include <cstdint> #include <experimental/filesystem> #include <fstream> #include <memory> using namespace std; using Line = vector<char>; string file_name = "../Navy Seals Copypasta.txt"; string alt_file_name = "./Navy Seals Copypasta.txt"; void handle_file(ifstream &is){ // If file_name exists, then open it. if (experimental::filesystem::exists(file_name)) is.open(file_name, ios_base::in); else if (experimental::filesystem::exists(alt_file_name)) is.open(alt_file_name, ios_base::in); else{ string error = "Could not find " + file_name + " or " + alt_file_name + " . Exiting."; throw runtime_error(error); } } //------------------------------------------------------------------------------ // Text_iterator //------------------------------------------------------------------------------ class Text_iterator : public std::iterator<std::bidirectional_iterator_tag, char, char, const long*, long>{ list<Line>::iterator ln; Line::iterator pos; public: Text_iterator(list<Line>::iterator ll, Line::iterator pp) : ln{ll}, pos{pp} { } char& operator*() { return *pos; } Line::iterator get_position() { return pos;} Line& getLine() { return *ln; } Text_iterator& operator++(); Text_iterator& operator--(); bool operator==(const Text_iterator &other) const { return ln == other.ln && pos == other.pos; } bool operator!=(const Text_iterator &other) const { return !(*this == other); } }; Text_iterator& Text_iterator::operator++(){ ++pos; if (pos == (*ln).end()){ ++ln; pos = (*ln).begin(); } return *this; } Text_iterator& Text_iterator::operator--(){ if (pos == (*ln).begin()){ --ln; pos = (*ln).end(); } else --pos; return *this; } template<typename Iter> void my_advance(Iter &p, int n){ if (!n) return; if (n < 0){ for (int i = 0; i > n; i--) --p; } else{ for (int i = 0; i < n; i++) ++p; } } //------------------------------------------------------------------------------ // Document //------------------------------------------------------------------------------ struct Document{ list<Line> line; Document() { line.push_back(Line{}); } Text_iterator begin() { return Text_iterator(line.begin(), line.begin()->begin()); } Text_iterator end(){ auto last = line.end(); --last; return Text_iterator(last, last->end()); } }; istream& operator>>(istream &is, Document &d){ char stop = '~'; for (char ch; is.get(ch);){ if (ch == stop) // Break if null character is inputted. break; d.line.back().push_back(ch); // Add the character if (ch == '\n') d.line.push_back(Line{}); // Add another line. } if (d.line.back().size()) d.line.push_back(Line{}); // Add final empty line. return is; } bool match(Text_iterator p, Text_iterator &last, const string &s){ if (p == last) return false; for (auto i = 0; i < s.length() && p != last; i++){ if (*p == s[i]) ++p; else return false; } return true; } Text_iterator find_txt(Text_iterator first, Text_iterator last, const string& s){ if (s.size()==0) return last; // can’t find an empty string char first_char = s[0]; while (true) { auto p = find(first,last,first_char); if (p==last || match(p,last,s)) return p; first = ++p; // look at the next character } } Text_iterator find_and_replace_txt(Text_iterator first, Text_iterator last, const string &search, const string &replace){ Text_iterator result = find_txt(first, last, search); if (result == last) return last; else{ auto start = result.get_position(); my_advance(start, 1); auto stop = result.get_position(); my_advance(stop, search.length()); result.getLine().erase(start, stop); *result = replace[0]; for (int i = 1; i < replace.size(); i++) result.getLine().push_back(replace[i]); return result; } } uint64_t count_characters(Text_iterator first, Text_iterator last){ uint64_t count = 0; while (first != last){ count++; ++first; } return count; } void print(Document &d){ for (char & p : d){ cout << p; } } int main(void){ Document d; ifstream is; handle_file(is); is >> d; // find_and_replace_txt(d.begin(), d.end(), "little bitch?", "miserable pile of secrets?"); // find_and_replace_txt(d.begin(), d.end(), "bitch?", "HARLOT?"); is.close(); uint64_t value = count_characters(d.begin(), d.end()); cout << "Number of characters in Document: " << value << endl; }
23.375
107
0.55199
62f8a945d1122a19d6a5aba08b02631a769d9347
2,742
cpp
C++
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
#include "texture_handler.h" TextureHandler* TextureHandler::mInstance = nullptr; bool TextureHandler::add_texture(const std::string& filePath, texture_t& id, SDL_Renderer* renderer) { id = std::hash<std::string>()(filePath); if (mTextures.find(id) != mTextures.end()) { return true; } SDL_Surface* sur = IMG_Load(filePath.c_str()); LOG(sur, "load surface " + filePath); SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, sur); LOG(tex, "create texture " + filePath); mTextures[id] = tex; int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); //mSizes[id] = Vector2<float>(w, h); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(w, h))); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(0, 0))); return true; } SDL_Texture* TextureHandler::get_texture(texture_t id) { if (mTextures.find(id) != mTextures.end()) { return mTextures[id]; } std::cerr << "Unable to load " << std::to_string(id) << std::endl; return nullptr; } void TextureHandler::render(SDL_Renderer* renderer, texture_t id, const Vector2<float>& position, const Vector2<float>& scale, float rotation, const Vector2<float>& center, SDL_RendererFlip flip) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } SDL_Rect src; src.x = mPositions[id].x; src.y = mPositions[id].y; src.w = mSizes[id].x; src.h = mSizes[id].y; SDL_Rect dst; dst.x = position.x; dst.y = position.y; dst.w = mSizes[id].x * scale.x; dst.h = mSizes[id].y * scale.y; SDL_Point cen; cen.x = center.x; cen.y = center.y; SDL_RenderCopyEx(renderer, mTextures[id], &src, &dst, rotation, &cen, flip); } void TextureHandler::set_src_rect(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mSizes[id] = src; } void TextureHandler::set_src_position(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mPositions[id] = src; } bool TextureHandler::point_in_texture(const Vector2<float>& point, const Vector2<float>& position, texture_t id) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return false; } int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); return point_in_rectangle(point, position, Vector2<float>(static_cast<float>(w), static_cast<float>(h))); }
30.808989
197
0.659373
62fbaca3bfaa78e541b1665b57744139a23cba24
1,223
cpp
C++
318. Maximum Product of Word Lengths.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
// Solution 1. Straight forward, 165ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++){ if(words[i].size() * words[j].size() <= maxlen) continue; if(noCommon(words[i], words[j])) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); } return maxlen; } bool noCommon(string& a, string& b){ for(auto x: a) for(auto y: b) if(x == y) return false; return true; } }; // Solution 2. Bit Manipulation, 43ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; vector<int>val(words.size()); for(int i = 0; i < words.size(); i++) for(auto c: words[i]) val[i] |= (1 << (c - 'a')); for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++) if((val[i] & val[j]) == 0 && words[i].size() * words[j].size() > maxlen) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); return maxlen; } };
32.184211
112
0.472608
62fdd32bf4578aadeef43d6531ee0cdb52538338
2,264
hh
C++
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
#pragma once #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/tcp.hpp> namespace io { namespace asio = boost::asio; namespace ssl = asio::ssl; typedef asio::ip::tcp tcp; typedef boost::system::error_code error_code; static const error_code Success = boost::system::errc::make_error_code( boost::system::errc::success); class Timer { private: asio::deadline_timer timer; std::function<void(Timer*)> timer_cb; public: void *data; Timer(asio::io_service& service); void cancel(); void async(const long ms, const std::function<void(Timer*)> &cb); }; class Service { private: std::shared_ptr<tcp::resolver> resolver; std::shared_ptr<ssl::context> ssl_ctx; std::shared_ptr<asio::io_service> loop; public: Service(); void Run(); ssl::context& getContext(); asio::io_service& getService(); Timer* createTimer(); Timer* spawn(const long ms, void *data, const std::function<void(Timer*)> &cb); void Resolve(const std::string &host, int port, std::function<void(const error_code&, tcp::resolver::iterator)> cb); }; class SSLClient { private: Service &service; bool connected = false; std::vector<char> builder; std::array<char, 8192> buffer; std::shared_ptr<ssl::stream<tcp::socket>> sock; std::function<void(const error_code&)> on_close; std::function<void(const error_code&)> on_connect; std::function<void(const std::vector<char>&)> on_read; void _read_handler(const error_code&, std::size_t); void _connect_handler(const error_code&, tcp::resolver::iterator, std::function<void(const error_code&)> callback); void _connect(const tcp::endpoint&, tcp::resolver::iterator&, std::function<void(const error_code&)> callback); public: SSLClient(Service& loop); void Connect(const std::string& host, int port); void Send(const char* data, const std::size_t len); void Close(const error_code& err, bool callback = true); const bool isConnected() const; void onClose(std::function<void(const error_code&)>); void onConnect(std::function<void(const error_code&)>); void onRead(std::function<void(const std::vector<char>&)>); }; }
28.3
83
0.673587
1a00460bc973876f44572786544f572a32f203f7
103,251
cpp
C++
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
1
2019-05-04T02:30:08.000Z
2019-05-04T02:30:08.000Z
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <malloc.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <sys/mman.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <unwind.h> #include <atomic> #include <future> #include <vector> #include <android-base/macros.h> #include <android-base/parseint.h> #include <android-base/scopeguard.h> #include <android-base/silent_death_test.h> #include <android-base/strings.h> #include "private/bionic_constants.h" #include "SignalUtils.h" #include "utils.h" using pthread_DeathTest = SilentDeathTest; TEST(pthread, pthread_key_create) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_key_delete(key)); // Can't delete a key that's already been deleted. ASSERT_EQ(EINVAL, pthread_key_delete(key)); } TEST(pthread, pthread_keys_max) { // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX. ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX); } TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) { int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX); ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX); } TEST(pthread, pthread_key_many_distinct) { // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX // pthread keys, but We should be able to allocate at least this many keys. int nkeys = PTHREAD_KEYS_MAX / 2; std::vector<pthread_key_t> keys; auto scope_guard = android::base::make_scope_guard([&keys] { for (const auto& key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } }); for (int i = 0; i < nkeys; ++i) { pthread_key_t key; // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong. ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys; keys.push_back(key); ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i))); } for (int i = keys.size() - 1; i >= 0; --i) { ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back())); pthread_key_t key = keys.back(); keys.pop_back(); ASSERT_EQ(0, pthread_key_delete(key)); } } TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) { std::vector<pthread_key_t> keys; int rv = 0; // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should // be more than we are allowed to allocate now. for (int i = 0; i < PTHREAD_KEYS_MAX; i++) { pthread_key_t key; rv = pthread_key_create(&key, nullptr); if (rv == EAGAIN) { break; } EXPECT_EQ(0, rv); keys.push_back(key); } // Don't leak keys. for (const auto& key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } keys.clear(); // We should have eventually reached the maximum number of keys and received // EAGAIN. ASSERT_EQ(EAGAIN, rv); } TEST(pthread, pthread_key_delete) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); // After deletion, pthread_getspecific returns nullptr. ASSERT_EQ(nullptr, pthread_getspecific(key)); // And you can't use pthread_setspecific with the deleted key. ASSERT_EQ(EINVAL, pthread_setspecific(key, expected)); } TEST(pthread, pthread_key_fork) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); pid_t pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); if (pid == 0) { // The surviving thread inherits all the forking thread's TLS values... ASSERT_EQ(expected, pthread_getspecific(key)); _exit(99); } AssertChildExited(pid, 99); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); } static void* DirtyKeyFn(void* key) { return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key)); } TEST(pthread, pthread_key_dirty) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); size_t stack_size = 640 * 1024; void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, stack); memset(stack, 0xff, stack_size); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key)); void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(nullptr, result); // Not ~0! ASSERT_EQ(0, munmap(stack, stack_size)); ASSERT_EQ(0, pthread_key_delete(key)); } TEST(pthread, static_pthread_key_used_before_creation) { #if defined(__BIONIC__) // See http://b/19625804. The bug is about a static/global pthread key being used before creation. // So here tests if the static/global default value 0 can be detected as invalid key. static pthread_key_t key; ASSERT_EQ(nullptr, pthread_getspecific(key)); ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr)); ASSERT_EQ(EINVAL, pthread_key_delete(key)); #else GTEST_SKIP() << "bionic-only test"; #endif } static void* IdFn(void* arg) { return arg; } class SpinFunctionHelper { public: SpinFunctionHelper() { SpinFunctionHelper::spin_flag_ = true; } ~SpinFunctionHelper() { UnSpin(); } auto GetFunction() -> void* (*)(void*) { return SpinFunctionHelper::SpinFn; } void UnSpin() { SpinFunctionHelper::spin_flag_ = false; } private: static void* SpinFn(void*) { while (spin_flag_) {} return nullptr; } static std::atomic<bool> spin_flag_; }; // It doesn't matter if spin_flag_ is used in several tests, // because it is always set to false after each test. Each thread // loops on spin_flag_ can find it becomes false at some time. std::atomic<bool> SpinFunctionHelper::spin_flag_; static void* JoinFn(void* arg) { return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr)); } static void AssertDetached(pthread_t t, bool is_detached) { pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(t, &attr)); int detach_state; ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state)); pthread_attr_destroy(&attr); ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED)); } static void MakeDeadThread(pthread_t& t) { ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_create) { void* expected_result = reinterpret_cast<void*>(123); // Can we create a thread? pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result)); // If we join, do we get the expected value back? void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(expected_result, result); } TEST(pthread, pthread_create_EAGAIN) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1))); pthread_t t; ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr)); } TEST(pthread, pthread_no_join_after_detach) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); // After a pthread_detach... ASSERT_EQ(0, pthread_detach(t1)); AssertDetached(t1, true); // ...pthread_join should fail. ASSERT_EQ(EINVAL, pthread_join(t1, nullptr)); } TEST(pthread, pthread_no_op_detach_after_join) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); // If thread 2 is already waiting to join thread 1... pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) #if defined(__BIONIC__) ASSERT_EQ(EINVAL, pthread_detach(t1)); #else ASSERT_EQ(0, pthread_detach(t1)); #endif AssertDetached(t1, false); spin_helper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join_self) { ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr)); } struct TestBug37410 { pthread_t main_thread; pthread_mutex_t mutex; static void main() { TestBug37410 data; data.main_thread = pthread_self(); ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr)); ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data))); // Wait for the thread to be running... ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex)); // ...and exit. pthread_exit(nullptr); } private: static void* thread_fn(void* arg) { TestBug37410* data = reinterpret_cast<TestBug37410*>(arg); // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle. pthread_t main_thread = data->main_thread; // Let the main thread know we're running. pthread_mutex_unlock(&data->mutex); // And wait for the main thread to exit. pthread_join(main_thread, nullptr); return nullptr; } }; // Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to // run this test (which exits normally) in its own process. TEST_F(pthread_DeathTest, pthread_bug_37410) { // http://code.google.com/p/android/issues/detail?id=37410 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), ""); } static void* SignalHandlerFn(void* arg) { sigset64_t wait_set; sigfillset64(&wait_set); return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg))); } TEST(pthread, pthread_sigmask) { // Check that SIGUSR1 isn't blocked. sigset_t original_set; sigemptyset(&original_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set)); ASSERT_FALSE(sigismember(&original_set, SIGUSR1)); // Block SIGUSR1. sigset_t set; sigemptyset(&set); sigaddset(&set, SIGUSR1); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr)); // Check that SIGUSR1 is blocked. sigset_t final_set; sigemptyset(&final_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // ...and that sigprocmask agrees with pthread_sigmask. sigemptyset(&final_set); ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // Spawn a thread that calls sigwait and tells us what it received. pthread_t signal_thread; int received_signal = -1; ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal)); // Send that thread SIGUSR1. pthread_kill(signal_thread, SIGUSR1); // See what it got. void* join_result; ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); ASSERT_EQ(SIGUSR1, received_signal); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); // Restore the original signal mask. ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr)); } TEST(pthread, pthread_sigmask64_SIGTRMIN) { // Check that SIGRTMIN isn't blocked. sigset64_t original_set; sigemptyset64(&original_set); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set)); ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN)); // Block SIGRTMIN. sigset64_t set; sigemptyset64(&set); sigaddset64(&set, SIGRTMIN); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr)); // Check that SIGRTMIN is blocked. sigset64_t final_set; sigemptyset64(&final_set); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); // ...and that sigprocmask64 agrees with pthread_sigmask64. sigemptyset64(&final_set); ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); // Spawn a thread that calls sigwait64 and tells us what it received. pthread_t signal_thread; int received_signal = -1; ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal)); // Send that thread SIGRTMIN. pthread_kill(signal_thread, SIGRTMIN); // See what it got. void* join_result; ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); ASSERT_EQ(SIGRTMIN, received_signal); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); // Restore the original signal mask. ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr)); } static void test_pthread_setname_np__pthread_getname_np(pthread_t t) { ASSERT_EQ(0, pthread_setname_np(t, "short")); char name[32]; ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); ASSERT_STREQ("short", name); // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL. ASSERT_EQ(0, pthread_setname_np(t, "123456789012345")); ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); ASSERT_STREQ("123456789012345", name); ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456")); // The passed-in buffer should be at least 16 bytes. ASSERT_EQ(0, pthread_getname_np(t, name, 16)); ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15)); } TEST(pthread, pthread_setname_np__pthread_getname_np__self) { test_pthread_setname_np__pthread_getname_np(pthread_self()); } TEST(pthread, pthread_setname_np__pthread_getname_np__other) { SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); test_pthread_setname_np__pthread_getname_np(t); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } // http://b/28051133: a kernel misfeature means that you can't change the // name of another thread if you've set PR_SET_DUMPABLE to 0. TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) { ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); test_pthread_setname_np__pthread_getname_np(t); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t (.*) passed to pthread_setname_np"); } TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3")); } TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); char name[64]; EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t (.*) passed to pthread_getname_np"); } TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) { pthread_t null_thread = 0; char name[64]; EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name))); } TEST(pthread, pthread_kill__0) { // Signal 0 just tests that the thread exists, so it's safe to call on ourselves. ASSERT_EQ(0, pthread_kill(pthread_self(), 0)); } TEST(pthread, pthread_kill__invalid_signal) { ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); } static void pthread_kill__in_signal_handler_helper(int signal_number) { static int count = 0; ASSERT_EQ(SIGALRM, signal_number); if (++count == 1) { // Can we call pthread_kill from a signal handler? ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } } TEST(pthread, pthread_kill__in_signal_handler) { ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } TEST(pthread, pthread_kill__exited_thread) { static std::promise<pid_t> tid_promise; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, [](void*) -> void* { tid_promise.set_value(gettid()); return nullptr; }, nullptr)); pid_t tid = tid_promise.get_future().get(); while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) { continue; } ASSERT_EQ(ESRCH, errno); ASSERT_EQ(ESRCH, pthread_kill(thread, 0)); } TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t (.*) passed to pthread_detach"); } TEST_F(pthread_DeathTest, pthread_detach__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_detach(null_thread)); } TEST(pthread, pthread_getcpuclockid__clock_gettime) { SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); clockid_t c; ASSERT_EQ(0, pthread_getcpuclockid(t, &c)); timespec ts; ASSERT_EQ(0, clock_gettime(c, &ts)); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); clockid_t c; EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t (.*) passed to pthread_getcpuclockid"); } TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) { pthread_t null_thread = 0; clockid_t c; EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c)); } TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy; sched_param param; EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param), "invalid pthread_t (.*) passed to pthread_getschedparam"); } TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) { pthread_t null_thread = 0; int policy; sched_param param; EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param)); } TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy = 0; sched_param param; EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param), "invalid pthread_t (.*) passed to pthread_setschedparam"); } TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) { pthread_t null_thread = 0; int policy = 0; sched_param param; EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param)); } TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_setschedprio(dead_thread, 123), "invalid pthread_t (.*) passed to pthread_setschedprio"); } TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123)); } TEST_F(pthread_DeathTest, pthread_join__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_join(dead_thread, nullptr), "invalid pthread_t (.*) passed to pthread_join"); } TEST_F(pthread_DeathTest, pthread_join__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr)); } TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t (.*) passed to pthread_kill"); } TEST_F(pthread_DeathTest, pthread_kill__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0)); } TEST(pthread, pthread_join__multijoin) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) // Multiple joins to the same thread should fail. ASSERT_EQ(EINVAL, pthread_join(t1, nullptr)); spin_helper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join__race) { // http://b/11693195 --- pthread_join could return before the thread had actually exited. // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread. for (size_t i = 0; i < 1024; ++i) { size_t stack_size = 640*1024; void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstack(&a, stack, stack_size); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(0, munmap(stack, stack_size)); } } static void* GetActualGuardSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg)); return nullptr; } static size_t GetActualGuardSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualGuardSizeFn, &result); pthread_join(t, nullptr); return result; } static void* GetActualStackSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg)); return nullptr; } static size_t GetActualStackSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualStackSizeFn, &result); pthread_join(t, nullptr); return result; } TEST(pthread, pthread_attr_setguardsize_tiny) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // No such thing as too small: will be rounded up to one page by pthread_create. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(128U, guard_size); ASSERT_EQ(4096U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_reasonable) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Large enough and a multiple of the page size. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U, guard_size); ASSERT_EQ(32*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_needs_rounding) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Large enough but not a multiple of the page size. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U + 1, guard_size); ASSERT_EQ(36*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_enormous) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Larger than the stack itself. (Historically we mistakenly carved // the guard out of the stack itself, rather than adding it after the // end.) ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024*1024U, guard_size); ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setstacksize) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Get the default stack size. size_t default_stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size)); // Too small. ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128)); size_t stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(default_stack_size, stack_size); ASSERT_GE(GetActualStackSize(attributes), default_stack_size); // Large enough and a multiple of the page size; may be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U, stack_size); ASSERT_GE(GetActualStackSize(attributes), 32*1024U); // Large enough but not aligned; will be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U + 1, stack_size); #if defined(__BIONIC__) ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1); #else // __BIONIC__ // glibc rounds down, in violation of POSIX. They document this in their BUGS section. ASSERT_EQ(GetActualStackSize(attributes), 32*1024U); #endif // __BIONIC__ } TEST(pthread, pthread_rwlockattr_smoke) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED}; for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i])); int pshared; ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared)); ASSERT_EQ(pshared_value_array[i], pshared); } int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP}; for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i])); int kind; ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind)); ASSERT_EQ(kind_array[i], kind); } ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) { pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_t lock2; ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr)); ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1))); } TEST(pthread, pthread_rwlock_smoke) { pthread_rwlock_t l; ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr)); // Single read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Multiple read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Write lock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock ASSERT_EQ(0, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try reader lock ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock after unlock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "read after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "write after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_destroy(&l)); } struct RwlockWakeupHelperArg { pthread_rwlock_t lock; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED, LOCK_TIMEDOUT, }; std::atomic<Progress> progress; std::atomic<pid_t> tid; std::function<int (pthread_rwlock_t*)> trylock_function; std::function<int (pthread_rwlock_t*)> lock_function; std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function; clockid_t clock; }; static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); ASSERT_EQ(0, arg->lock_function(&arg->lock)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; } static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; wakeup_arg.lock_function = lock_function; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_reader_wakeup_writer) { test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock); } TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) { timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock(lock, &ts); }); } TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer( [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts); }); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; wakeup_arg.lock_function = lock_function; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_writer_wakeup_reader) { test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock); } TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) { timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock(lock, &ts); }); } TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader( [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts); }); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); timespec ts; ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); ts.tv_sec += 1; ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT; } static void pthread_rwlock_timedrdlock_timeout_helper( clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; wakeup_arg.timed_lock_function = lock_function; wakeup_arg.clock = clock; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_timedrdlock_timeout) { pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock); } TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC, pthread_rwlock_timedrdlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper( CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper( CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_invalid) { #if defined(__BIONIC__) pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } static void pthread_rwlock_timedwrlock_timeout_helper( clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; wakeup_arg.timed_lock_function = lock_function; wakeup_arg.clock = clock; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_timedwrlock_timeout) { pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock); } TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC, pthread_rwlock_timedwrlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper( CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper( CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_invalid) { #if defined(__BIONIC__) pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrwlock not available"; #endif // __BIONIC__ } class RwlockKindTestHelper { private: struct ThreadArg { RwlockKindTestHelper* helper; std::atomic<pid_t>& tid; ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid) : helper(helper), tid(tid) { } }; public: pthread_rwlock_t lock; public: explicit RwlockKindTestHelper(int kind_type) { InitRwlock(kind_type); } ~RwlockKindTestHelper() { DestroyRwlock(); } void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg)); } void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg)); } private: void InitRwlock(int kind_type) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type)); ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr)); ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } void DestroyRwlock() { ASSERT_EQ(0, pthread_rwlock_destroy(&lock)); } static void WriterThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } static void ReaderThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } }; TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); ASSERT_EQ(0, pthread_join(reader_thread, nullptr)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, nullptr)); } TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); WaitUntilThreadSleep(reader_tid); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, nullptr)); ASSERT_EQ(0, pthread_join(reader_thread, nullptr)); } static int g_once_fn_call_count = 0; static void OnceFn() { ++g_once_fn_call_count; } TEST(pthread, pthread_once_smoke) { pthread_once_t once_control = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(1, g_once_fn_call_count); } static std::string pthread_once_1934122_result = ""; static void Routine2() { pthread_once_1934122_result += "2"; } static void Routine1() { pthread_once_t once_control_2 = PTHREAD_ONCE_INIT; pthread_once_1934122_result += "1"; pthread_once(&once_control_2, &Routine2); } TEST(pthread, pthread_once_1934122) { // Very old versions of Android couldn't call pthread_once from a // pthread_once init routine. http://b/1934122. pthread_once_t once_control_1 = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1)); ASSERT_EQ("12", pthread_once_1934122_result); } static int g_atfork_prepare_calls = 0; static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; } static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; } static int g_atfork_parent_calls = 0; static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; } static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; } static int g_atfork_child_calls = 0; static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; } static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; } TEST(pthread, pthread_atfork_smoke) { ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1)); ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2)); pid_t pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); // Child and parent calls are made in the order they were registered. if (pid == 0) { ASSERT_EQ(12, g_atfork_child_calls); _exit(0); } ASSERT_EQ(12, g_atfork_parent_calls); // Prepare calls are made in the reverse order. ASSERT_EQ(21, g_atfork_prepare_calls); AssertChildExited(pid, 0); } TEST(pthread, pthread_attr_getscope) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int scope; ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope)); ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope); } TEST(pthread, pthread_condattr_init) { pthread_condattr_t attr; pthread_condattr_init(&attr); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); } TEST(pthread, pthread_condattr_setclock) { pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID)); } TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) { #if defined(__BIONIC__) pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); pthread_cond_t cond_var; ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr)); ASSERT_EQ(0, pthread_cond_signal(&cond_var)); ASSERT_EQ(0, pthread_cond_broadcast(&cond_var)); attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); #else // !defined(__BIONIC__) GTEST_SKIP() << "bionic-only test"; #endif // !defined(__BIONIC__) } class pthread_CondWakeupTest : public ::testing::Test { protected: pthread_mutex_t mutex; pthread_cond_t cond; enum Progress { INITIALIZED, WAITING, SIGNALED, FINISHED, }; std::atomic<Progress> progress; pthread_t thread; std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function; protected: void SetUp() override { ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); } void InitCond(clockid_t clock=CLOCK_REALTIME) { pthread_condattr_t attr; ASSERT_EQ(0, pthread_condattr_init(&attr)); ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock)); ASSERT_EQ(0, pthread_cond_init(&cond, &attr)); ASSERT_EQ(0, pthread_condattr_destroy(&attr)); } void StartWaitingThread( std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) { progress = INITIALIZED; this->wait_function = wait_function; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this)); while (progress != WAITING) { usleep(5000); } usleep(5000); } void RunTimedTest( clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)> wait_function) { timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ts.tv_sec += 1; StartWaitingThread([&wait_function, &ts](pthread_cond_t* cond, pthread_mutex_t* mutex) { return wait_function(cond, mutex, &ts); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_signal(&cond)); } void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, clockid_t clock, const timespec* timeout)> wait_function) { RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout) { return wait_function(cond, mutex, clock, timeout); }); } void TearDown() override { ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(FINISHED, progress); ASSERT_EQ(0, pthread_cond_destroy(&cond)); ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); } private: static void WaitThreadFn(pthread_CondWakeupTest* test) { ASSERT_EQ(0, pthread_mutex_lock(&test->mutex)); test->progress = WAITING; while (test->progress == WAITING) { ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex)); } ASSERT_EQ(SIGNALED, test->progress); test->progress = FINISHED; ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex)); } }; TEST_F(pthread_CondWakeupTest, signal_wait) { InitCond(); StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { return pthread_cond_wait(cond, mutex); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_signal(&cond)); } TEST_F(pthread_CondWakeupTest, broadcast_wait) { InitCond(); StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { return pthread_cond_wait(cond, mutex); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_broadcast(&cond)); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) { InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) { InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) { #if defined(__BIONIC__) InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) { #if defined(__BIONIC__) InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock, int (*wait_function)(pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout)) { pthread_mutex_t mutex; ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); pthread_cond_t cond; if (init_monotonic) { pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); ASSERT_EQ(0, pthread_cond_init(&cond, &attr)); } else { ASSERT_EQ(0, pthread_cond_init(&cond, nullptr)); } ASSERT_EQ(0, pthread_mutex_lock(&mutex)); timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&mutex)); } TEST(pthread, pthread_cond_timedwait_timeout) { pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait); } TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_cond_clockwait_timeout) { #if defined(__BIONIC__) pthread_cond_timedwait_timeout_helper( false, CLOCK_MONOTONIC, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout); }); pthread_cond_timedwait_timeout_helper( true, CLOCK_MONOTONIC, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout); }); pthread_cond_timedwait_timeout_helper( false, CLOCK_REALTIME, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout); }); pthread_cond_timedwait_timeout_helper( true, CLOCK_REALTIME, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST(pthread, pthread_cond_clockwait_invalid) { #if defined(__BIONIC__) pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST(pthread, pthread_attr_getstack__main_thread) { // This test is only meaningful for the main thread, so make sure we're running on it! ASSERT_EQ(getpid(), syscall(__NR_gettid)); // Get the main thread's attributes. pthread_attr_t attributes; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); // Check that we correctly report that the main thread has no guard page. size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(0U, guard_size); // The main thread has no guard page. // Get the stack base and the stack size (both ways). void* stack_base; size_t stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); size_t stack_size2; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); // The two methods of asking for the stack size should agree. EXPECT_EQ(stack_size, stack_size2); #if defined(__BIONIC__) // Find stack in /proc/self/maps using a pointer to the stack. // // We do not use "[stack]" label because in native-bridge environment it is not // guaranteed to point to the right stack. A native bridge implementation may // keep separate stack for the guest code. void* maps_stack_hi = nullptr; std::vector<map_record> maps; ASSERT_TRUE(Maps::parse_maps(&maps)); uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi)); for (const auto& map : maps) { if (map.addr_start <= stack_address && map.addr_end > stack_address){ maps_stack_hi = reinterpret_cast<void*>(map.addr_end); break; } } // The high address of the /proc/self/maps stack region should equal stack_base + stack_size. // Remember that the stack grows down (and is mapped in on demand), so the low address of the // region isn't very interesting. EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size); // The stack size should correspond to RLIMIT_STACK. rlimit rl; ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl)); uint64_t original_rlim_cur = rl.rlim_cur; if (rl.rlim_cur == RLIM_INFINITY) { rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB. } EXPECT_EQ(rl.rlim_cur, stack_size); auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() { rl.rlim_cur = original_rlim_cur; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); }); // // What if RLIMIT_STACK is smaller than the stack's current extent? // rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(1024U, stack_size); // // What if RLIMIT_STACK isn't a whole number of pages? // rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(6666U, stack_size); #endif } struct GetStackSignalHandlerArg { volatile bool done; void* signal_stack_base; size_t signal_stack_size; void* main_stack_base; size_t main_stack_size; }; static GetStackSignalHandlerArg getstack_signal_handler_arg; static void getstack_signal_handler(int sig) { ASSERT_EQ(SIGUSR1, sig); // Use sleep() to make current thread be switched out by the kernel to provoke the error. sleep(1); pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); void* stack_base; size_t stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size)); // Verify if the stack used by the signal handler is the alternate stack just registered. ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr); ASSERT_LT(static_cast<void*>(untag_address(&attr)), static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) + getstack_signal_handler_arg.signal_stack_size); // Verify if the main thread's stack got in the signal handler is correct. ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base); ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size); getstack_signal_handler_arg.done = true; } // The previous code obtained the main thread's stack by reading the entry in // /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel // relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel // switches a process while the main thread is in an alternate stack, then the kernel will label // the wrong map with [stack]. This test verifies that when the above situation happens, the main // thread's stack is found correctly. TEST(pthread, pthread_attr_getstack_in_signal_handler) { // This test is only meaningful for the main thread, so make sure we're running on it! ASSERT_EQ(getpid(), syscall(__NR_gettid)); const size_t sig_stack_size = 16 * 1024; void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, sig_stack); stack_t ss; ss.ss_sp = sig_stack; ss.ss_size = sig_stack_size; ss.ss_flags = 0; stack_t oss; ASSERT_EQ(0, sigaltstack(&ss, &oss)); pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); void* main_stack_base; size_t main_stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size)); ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK); getstack_signal_handler_arg.done = false; getstack_signal_handler_arg.signal_stack_base = sig_stack; getstack_signal_handler_arg.signal_stack_size = sig_stack_size; getstack_signal_handler_arg.main_stack_base = main_stack_base; getstack_signal_handler_arg.main_stack_size = main_stack_size; kill(getpid(), SIGUSR1); ASSERT_EQ(true, getstack_signal_handler_arg.done); ASSERT_EQ(0, sigaltstack(&oss, nullptr)); ASSERT_EQ(0, munmap(sig_stack, sig_stack_size)); } static void pthread_attr_getstack_18908062_helper(void*) { char local_variable; pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); void* stack_base; size_t stack_size; pthread_attr_getstack(&attributes, &stack_base, &stack_size); // Test whether &local_variable is in [stack_base, stack_base + stack_size). ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable); ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size); } // Check whether something on stack is in the range of // [stack_base, stack_base + stack_size). see b/18908062. TEST(pthread, pthread_attr_getstack_18908062) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper), nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); } #if defined(__BIONIC__) static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER; static void* pthread_gettid_np_helper(void* arg) { *reinterpret_cast<pid_t*>(arg) = gettid(); // Wait for our parent to call pthread_gettid_np on us before exiting. pthread_mutex_lock(&pthread_gettid_np_mutex); pthread_mutex_unlock(&pthread_gettid_np_mutex); return nullptr; } #endif TEST(pthread, pthread_gettid_np) { #if defined(__BIONIC__) ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self())); // Ensure the other thread doesn't exit until after we've called // pthread_gettid_np on it. pthread_mutex_lock(&pthread_gettid_np_mutex); pid_t t_gettid_result; pthread_t t; pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result); pid_t t_pthread_gettid_np_result = pthread_gettid_np(t); // Release the other thread and wait for it to exit. pthread_mutex_unlock(&pthread_gettid_np_mutex); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result); #else GTEST_SKIP() << "pthread_gettid_np not available"; #endif } static size_t cleanup_counter = 0; static void AbortCleanupRoutine(void*) { abort(); } static void CountCleanupRoutine(void*) { ++cleanup_counter; } static void PthreadCleanupTester() { pthread_cleanup_push(CountCleanupRoutine, nullptr); pthread_cleanup_push(CountCleanupRoutine, nullptr); pthread_cleanup_push(AbortCleanupRoutine, nullptr); pthread_cleanup_pop(0); // Pop the abort without executing it. pthread_cleanup_pop(1); // Pop one count while executing it. ASSERT_EQ(1U, cleanup_counter); // Exit while the other count is still on the cleanup stack. pthread_exit(nullptr); // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced. pthread_cleanup_pop(0); } static void* PthreadCleanupStartRoutine(void*) { PthreadCleanupTester(); return nullptr; } TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(2U, cleanup_counter); } TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) { ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT); } TEST(pthread, pthread_mutexattr_gettype) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); int attr_type; ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } TEST(pthread, pthread_mutexattr_protocol) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); int protocol; ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); ASSERT_EQ(PTHREAD_PRIO_NONE, protocol); for (size_t repeat = 0; repeat < 2; ++repeat) { for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) { ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol)); ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); ASSERT_EQ(protocol, set_protocol); } } } struct PthreadMutex { pthread_mutex_t lock; explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) { init(mutex_type, protocol); } ~PthreadMutex() { destroy(); } private: void init(int mutex_type, int protocol) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type)); ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } void destroy() { ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } DISALLOW_COPY_AND_ASSIGN(PthreadMutex); }; static int UnlockFromAnotherThread(pthread_mutex_t* mutex) { pthread_t thread; pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* { pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp); intptr_t result = pthread_mutex_unlock(mutex); return reinterpret_cast<void*>(result); }, mutex); void* result; EXPECT_EQ(0, pthread_join(thread, &result)); return reinterpret_cast<intptr_t>(result); }; static void TestPthreadMutexLockNormal(int protocol) { PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); if (protocol == PTHREAD_PRIO_INHERIT) { ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); } ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); } static void TestPthreadMutexLockErrorCheck(int protocol) { PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); if (protocol == PTHREAD_PRIO_NONE) { ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); } else { ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock)); } ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } static void TestPthreadMutexLockRecursive(int protocol) { PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_lock_NORMAL) { TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_ERRORCHECK) { TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_RECURSIVE) { TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_pi) { TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT); TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT); TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT); } TEST(pthread, pthread_mutex_pi_count_limit) { #if defined(__BIONIC__) && !defined(__LP64__) // Bionic only supports 65536 pi mutexes in 32-bit programs. pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT)); std::vector<pthread_mutex_t> mutexes(65536); // Test if we can use 65536 pi mutexes at the same time. // Run 2 times to check if freed pi mutexes can be recycled. for (int repeat = 0; repeat < 2; ++repeat) { for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_init(&m, &attr)); } pthread_mutex_t m; ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr)); for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_lock(&m)); } for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_unlock(&m)); } for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_destroy(&m)); } } ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); #else GTEST_SKIP() << "pi mutex count not limited to 64Ki"; #endif } TEST(pthread, pthread_mutex_init_same_as_static_initializers) { pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER; PthreadMutex m1(PTHREAD_MUTEX_NORMAL); ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_normal); pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK); ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_errorcheck); pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE); ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t))); ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive)); } class MutexWakeupHelper { private: PthreadMutex m; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED }; std::atomic<Progress> progress; std::atomic<pid_t> tid; static void thread_fn(MutexWakeupHelper* helper) { helper->tid = gettid(); ASSERT_EQ(LOCK_INITIALIZED, helper->progress); helper->progress = LOCK_WAITING; ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); ASSERT_EQ(LOCK_RELEASED, helper->progress); ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); helper->progress = LOCK_ACCESSED; } public: explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) { } void test() { ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); progress = LOCK_INITIALIZED; tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this)); WaitUntilThreadSleep(tid); ASSERT_EQ(LOCK_WAITING, progress); progress = LOCK_RELEASED; ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(LOCK_ACCESSED, progress); } }; TEST(pthread, pthread_mutex_NORMAL_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL); helper.test(); } TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK); helper.test(); } TEST(pthread, pthread_mutex_RECURSIVE_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE); helper.test(); } static int GetThreadPriority(pid_t tid) { // sched_getparam() returns the static priority of a thread, which can't reflect a thread's // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority. std::string filename = android::base::StringPrintf("/proc/%d/stat", tid); std::string content; int result = INT_MAX; if (!android::base::ReadFileToString(filename, &content)) { return result; } std::vector<std::string> strs = android::base::Split(content, " "); if (strs.size() < 18) { return result; } if (!android::base::ParseInt(strs[17], &result)) { return INT_MAX; } return result; } class PIMutexWakeupHelper { private: PthreadMutex m; int protocol; enum Progress { LOCK_INITIALIZED, LOCK_CHILD_READY, LOCK_WAITING, LOCK_RELEASED, }; std::atomic<Progress> progress; std::atomic<pid_t> main_tid; std::atomic<pid_t> child_tid; PthreadMutex start_thread_m; static void thread_fn(PIMutexWakeupHelper* helper) { helper->child_tid = gettid(); ASSERT_EQ(LOCK_INITIALIZED, helper->progress); ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1)); ASSERT_EQ(21, GetThreadPriority(gettid())); ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); helper->progress = LOCK_CHILD_READY; ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock)); WaitUntilThreadSleep(helper->main_tid); ASSERT_EQ(LOCK_WAITING, helper->progress); if (helper->protocol == PTHREAD_PRIO_INHERIT) { ASSERT_EQ(20, GetThreadPriority(gettid())); } else { ASSERT_EQ(21, GetThreadPriority(gettid())); } helper->progress = LOCK_RELEASED; ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); } public: explicit PIMutexWakeupHelper(int mutex_type, int protocol) : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) { } void test() { ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock)); main_tid = gettid(); ASSERT_EQ(20, GetThreadPriority(main_tid)); progress = LOCK_INITIALIZED; child_tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this)); WaitUntilThreadSleep(child_tid); ASSERT_EQ(LOCK_CHILD_READY, progress); ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock)); progress = LOCK_WAITING; ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(LOCK_RELEASED, progress); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); } }; TEST(pthread, pthread_mutex_pi_wakeup) { for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) { for (int protocol : {PTHREAD_PRIO_INHERIT}) { PIMutexWakeupHelper helper(type, protocol); helper.test(); } } } TEST(pthread, pthread_mutex_owner_tid_limit) { #if defined(__BIONIC__) && !defined(__LP64__) FILE* fp = fopen("/proc/sys/kernel/pid_max", "r"); ASSERT_TRUE(fp != nullptr); long pid_max; ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max)); fclose(fp); // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid. ASSERT_LE(pid_max, 65536); #else GTEST_SKIP() << "pthread_mutex supports 32-bit tid"; #endif } static void pthread_mutex_timedlock_helper(clockid_t clock, int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout)) { pthread_mutex_t m; ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); // If the mutex is already locked, pthread_mutex_timedlock should time out. ASSERT_EQ(0, pthread_mutex_lock(&m)); timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, lock_function(&m, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, lock_function(&m, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); // If the mutex is unlocked, pthread_mutex_timedlock should succeed. ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, clock_gettime(clock, &ts)); ts.tv_sec += 1; ASSERT_EQ(0, lock_function(&m, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, pthread_mutex_destroy(&m)); } TEST(pthread, pthread_mutex_timedlock) { pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock); } TEST(pthread, pthread_mutex_timedlock_monotonic_np) { #if defined(__BIONIC__) pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock) { #if defined(__BIONIC__) pthread_mutex_timedlock_helper( CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout); }); pthread_mutex_timedlock_helper( CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } static void pthread_mutex_timedlock_pi_helper(clockid_t clock, int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout)) { PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT); timespec ts; clock_gettime(clock, &ts); ts.tv_sec += 1; ASSERT_EQ(0, lock_function(&m.lock, &ts)); struct ThreadArgs { clockid_t clock; int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout); PthreadMutex& m; }; ThreadArgs thread_args = { .clock = clock, .lock_function = lock_function, .m = m, }; auto ThreadFn = [](void* arg) -> void* { auto args = static_cast<ThreadArgs*>(arg); timespec ts; clock_gettime(args->clock, &ts); ts.tv_sec += 1; intptr_t result = args->lock_function(&args->m.lock, &ts); return reinterpret_cast<void*>(result); }; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args)); void* result; ASSERT_EQ(0, pthread_join(thread, &result)); ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_timedlock_pi) { pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock); } TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) { #if defined(__BIONIC__) pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock_pi) { #if defined(__BIONIC__) pthread_mutex_timedlock_pi_helper( CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout); }); pthread_mutex_timedlock_pi_helper( CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock_invalid) { #if defined(__BIONIC__) pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) { #if defined(__BIONIC__) pthread_mutex_t m; ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); ASSERT_EQ(0, pthread_mutex_destroy(&m)); ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_lock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_unlock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_trylock called on a destroyed mutex"); timespec ts; ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_timedlock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_destroy called on a destroyed mutex"); #else GTEST_SKIP() << "bionic-only test"; #endif } class StrictAlignmentAllocator { public: void* allocate(size_t size, size_t alignment) { char* p = new char[size + alignment * 2]; allocated_array.push_back(p); while (!is_strict_aligned(p, alignment)) { ++p; } return p; } ~StrictAlignmentAllocator() { for (const auto& p : allocated_array) { delete[] p; } } private: bool is_strict_aligned(char* p, size_t alignment) { return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment; } std::vector<char*> allocated_array; }; TEST(pthread, pthread_types_allow_four_bytes_alignment) { #if defined(__BIONIC__) // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types. StrictAlignmentAllocator allocator; pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>( allocator.allocate(sizeof(pthread_mutex_t), 4)); ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr)); ASSERT_EQ(0, pthread_mutex_lock(mutex)); ASSERT_EQ(0, pthread_mutex_unlock(mutex)); ASSERT_EQ(0, pthread_mutex_destroy(mutex)); pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>( allocator.allocate(sizeof(pthread_cond_t), 4)); ASSERT_EQ(0, pthread_cond_init(cond, nullptr)); ASSERT_EQ(0, pthread_cond_signal(cond)); ASSERT_EQ(0, pthread_cond_broadcast(cond)); ASSERT_EQ(0, pthread_cond_destroy(cond)); pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>( allocator.allocate(sizeof(pthread_rwlock_t), 4)); ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_destroy(rwlock)); #else GTEST_SKIP() << "bionic-only test"; #endif } TEST(pthread, pthread_mutex_lock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) // For LP32, the pthread lock/unlock functions allow a NULL mutex and return // EINVAL in that case: http://b/19995172. // // We decorate the public defintion with _Nonnull so that people recompiling // their code with get a warning and might fix their bug, but need to pass // NULL here to test that we remain compatible. pthread_mutex_t* null_value = nullptr; ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value)); #else GTEST_SKIP() << "32-bit bionic-only test"; #endif } TEST(pthread, pthread_mutex_unlock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) // For LP32, the pthread lock/unlock functions allow a NULL mutex and return // EINVAL in that case: http://b/19995172. // // We decorate the public defintion with _Nonnull so that people recompiling // their code with get a warning and might fix their bug, but need to pass // NULL here to test that we remain compatible. pthread_mutex_t* null_value = nullptr; ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value)); #else GTEST_SKIP() << "32-bit bionic-only test"; #endif } TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_SKIP() << "64-bit bionic-only test"; #endif } TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_SKIP() << "64-bit bionic-only test"; #endif } extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg); static volatile bool signal_handler_on_altstack_done; __attribute__((__noinline__)) static void signal_handler_backtrace() { // Check if we have enough stack space for unwinding. int count = 0; _Unwind_Backtrace(FrameCounter, &count); ASSERT_GT(count, 0); } __attribute__((__noinline__)) static void signal_handler_logging() { // Check if we have enough stack space for logging. std::string s(2048, '*'); GTEST_LOG_(INFO) << s; signal_handler_on_altstack_done = true; } __attribute__((__noinline__)) static void signal_handler_snprintf() { // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra. char buf[PATH_MAX + 2048]; ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0); } static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) { ASSERT_EQ(SIGUSR1, signo); signal_handler_backtrace(); signal_handler_logging(); signal_handler_snprintf(); } TEST(pthread, big_enough_signal_stack) { signal_handler_on_altstack_done = false; ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK); kill(getpid(), SIGUSR1); ASSERT_TRUE(signal_handler_on_altstack_done); } TEST(pthread, pthread_barrierattr_smoke) { pthread_barrierattr_t attr; ASSERT_EQ(0, pthread_barrierattr_init(&attr)); int pshared; ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); ASSERT_EQ(0, pthread_barrierattr_destroy(&attr)); } struct BarrierTestHelperData { size_t thread_count; pthread_barrier_t barrier; std::atomic<int> finished_mask; std::atomic<int> serial_thread_count; size_t iteration_count; std::atomic<size_t> finished_iteration_count; BarrierTestHelperData(size_t thread_count, size_t iteration_count) : thread_count(thread_count), finished_mask(0), serial_thread_count(0), iteration_count(iteration_count), finished_iteration_count(0) { } }; struct BarrierTestHelperArg { int id; BarrierTestHelperData* data; }; static void BarrierTestHelper(BarrierTestHelperArg* arg) { for (size_t i = 0; i < arg->data->iteration_count; ++i) { int result = pthread_barrier_wait(&arg->data->barrier); if (result == PTHREAD_BARRIER_SERIAL_THREAD) { arg->data->serial_thread_count++; } else { ASSERT_EQ(0, result); } int mask = arg->data->finished_mask.fetch_or(1 << arg->id); mask |= 1 << arg->id; if (mask == ((1 << arg->data->thread_count) - 1)) { ASSERT_EQ(1, arg->data->serial_thread_count); arg->data->finished_iteration_count++; arg->data->finished_mask = 0; arg->data->serial_thread_count = 0; } } } TEST(pthread, pthread_barrier_smoke) { const size_t BARRIER_ITERATION_COUNT = 10; const size_t BARRIER_THREAD_COUNT = 10; BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT); ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count)); std::vector<pthread_t> threads(data.thread_count); std::vector<BarrierTestHelperArg> args(threads.size()); for (size_t i = 0; i < threads.size(); ++i) { args[i].id = i; args[i].data = &data; ASSERT_EQ(0, pthread_create(&threads[i], nullptr, reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i])); } for (size_t i = 0; i < threads.size(); ++i) { ASSERT_EQ(0, pthread_join(threads[i], nullptr)); } ASSERT_EQ(data.iteration_count, data.finished_iteration_count); ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier)); } struct BarrierDestroyTestArg { std::atomic<int> tid; pthread_barrier_t* barrier; }; static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) { arg->tid = gettid(); ASSERT_EQ(0, pthread_barrier_wait(arg->barrier)); } TEST(pthread, pthread_barrier_destroy) { pthread_barrier_t barrier; ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2)); pthread_t thread; BarrierDestroyTestArg arg; arg.tid = 0; arg.barrier = &barrier; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg)); WaitUntilThreadSleep(arg.tid); ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier)); ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier)); // Verify if the barrier can be destroyed directly after pthread_barrier_wait(). ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); ASSERT_EQ(0, pthread_join(thread, nullptr)); #if defined(__BIONIC__) ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier)); #endif } struct BarrierOrderingTestHelperArg { pthread_barrier_t* barrier; size_t* array; size_t array_length; size_t id; }; void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) { const size_t ITERATION_COUNT = 10000; for (size_t i = 1; i <= ITERATION_COUNT; ++i) { arg->array[arg->id] = i; int result = pthread_barrier_wait(arg->barrier); ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); for (size_t j = 0; j < arg->array_length; ++j) { ASSERT_EQ(i, arg->array[j]); } result = pthread_barrier_wait(arg->barrier); ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); } } TEST(pthread, pthread_barrier_check_ordering) { const size_t THREAD_COUNT = 4; pthread_barrier_t barrier; ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT)); size_t array[THREAD_COUNT]; std::vector<pthread_t> threads(THREAD_COUNT); std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT); for (size_t i = 0; i < THREAD_COUNT; ++i) { args[i].barrier = &barrier; args[i].array = array; args[i].array_length = THREAD_COUNT; args[i].id = i; ASSERT_EQ(0, pthread_create(&threads[i], nullptr, reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper), &args[i])); } for (size_t i = 0; i < THREAD_COUNT; ++i) { ASSERT_EQ(0, pthread_join(threads[i], nullptr)); } } TEST(pthread, pthread_barrier_init_zero_count) { pthread_barrier_t barrier; ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0)); } TEST(pthread, pthread_spinlock_smoke) { pthread_spinlock_t lock; ASSERT_EQ(0, pthread_spin_init(&lock, 0)); ASSERT_EQ(0, pthread_spin_trylock(&lock)); ASSERT_EQ(0, pthread_spin_unlock(&lock)); ASSERT_EQ(0, pthread_spin_lock(&lock)); ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock)); ASSERT_EQ(0, pthread_spin_unlock(&lock)); ASSERT_EQ(0, pthread_spin_destroy(&lock)); } TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int state; ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_DETACHED, state); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); } TEST(pthread, pthread_create__mmap_failures) { // After thread is successfully created, native_bridge might need more memory to run it. SKIP_WITH_NATIVE_BRIDGE; pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); const auto kPageSize = sysconf(_SC_PAGE_SIZE); // Use up all the VMAs. By default this is 64Ki (though some will already be in use). std::vector<void*> pages; pages.reserve(64 * 1024); int prot = PROT_NONE; while (true) { void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0); if (page == MAP_FAILED) break; pages.push_back(page); prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE; } // Try creating threads, freeing up a page each time we fail. size_t EAGAIN_count = 0; size_t i = 0; for (; i < pages.size(); ++i) { pthread_t t; int status = pthread_create(&t, &attr, IdFn, nullptr); if (status != EAGAIN) break; ++EAGAIN_count; ASSERT_EQ(0, munmap(pages[i], kPageSize)); } // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each // side. So we should have seen at least three failures. ASSERT_GE(EAGAIN_count, 3U); for (; i < pages.size(); ++i) { ASSERT_EQ(0, munmap(pages[i], kPageSize)); } } TEST(pthread, pthread_setschedparam) { sched_param p = { .sched_priority = INT_MIN }; ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p)); } TEST(pthread, pthread_setschedprio) { ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN)); } TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int state; ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_INHERIT_SCHED, state); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); } TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); // If we set invalid scheduling attributes but choose to inherit, everything's fine... sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 }; ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param)); ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); #if defined(__LP64__) // If we ask to use them, though, we'll see a failure... ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr)); #else // For backwards compatibility with broken apps, we just ignore failures // to set scheduler attributes on LP32. #endif } TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_FIFO, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_OTHER, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg); TEST(pthread, run_on_all_threads) { #if defined(__BIONIC__) pthread_t t; ASSERT_EQ( 0, pthread_create( &t, nullptr, [](void*) -> void* { pthread_attr_t detached; if (pthread_attr_init(&detached) != 0 || pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) { return reinterpret_cast<void*>(errno); } for (int i = 0; i != 1000; ++i) { pthread_t t1, t2; if (pthread_create( &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 || pthread_create( &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 || pthread_join(t2, nullptr) != 0) { return reinterpret_cast<void*>(errno); } } if (pthread_attr_destroy(&detached) != 0) { return reinterpret_cast<void*>(errno); } return nullptr; }, nullptr)); for (int i = 0; i != 1000; ++i) { ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr)); } void *retval; ASSERT_EQ(0, pthread_join(t, &retval)); ASSERT_EQ(nullptr, retval); #else GTEST_SKIP() << "bionic-only test"; #endif }
34.166446
108
0.737368
1a0125fd4d1dcb013d931218bdfe550dbe2cf45d
282
cpp
C++
ds/queue.cpp
atalhaaydin/c-cpp-codes
a7ccf11c293bd67d72f2848a2da0128e0d3555fa
[ "MIT" ]
null
null
null
ds/queue.cpp
atalhaaydin/c-cpp-codes
a7ccf11c293bd67d72f2848a2da0128e0d3555fa
[ "MIT" ]
null
null
null
ds/queue.cpp
atalhaaydin/c-cpp-codes
a7ccf11c293bd67d72f2848a2da0128e0d3555fa
[ "MIT" ]
null
null
null
#include "QueueNode.h" #include <iostream> int main(void) { Queue<int> q; int temp; q.enqueue(1); q.enqueue(50); q.enqueue(30); q.enqueue(80); q.enqueue(10); q.enqueue(7); q.printQueue(); while(!q.isEmpty()) { q.dequeue(temp); } q.printQueue(); return 0; }
14.1
22
0.606383
1a058f089c816fe656fccfdf5b0d50e4ca781b28
2,870
cpp
C++
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
3
2021-12-23T23:31:42.000Z
2022-02-16T07:17:41.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
2
2021-11-22T05:33:43.000Z
2022-01-23T07:01:47.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
null
null
null
#include "CAN.h" #include "CANMotor.h" #include "CANUtils.h" #include <chrono> #include <cmath> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <vector> extern "C" { #include "../HindsightCAN/CANCommon.h" #include "../HindsightCAN/CANMotorUnit.h" #include "../HindsightCAN/CANPacket.h" } using namespace std::chrono_literals; using std::chrono::milliseconds; namespace can::motor { namespace { using clock = std::chrono::steady_clock; using timepoint_t = std::chrono::time_point<clock>; struct telemschedule_t { timepoint_t nextSendTime; milliseconds telemPeriod; deviceserial_t serial; }; bool operator<(const telemschedule_t& t1, const telemschedule_t& t2) { return t1.nextSendTime < t2.nextSendTime; } std::priority_queue<telemschedule_t> telemetrySchedule; bool startedMotorThread = false; bool newMotorAdded = false; std::condition_variable motorsCV; std::mutex motorsMutex; // protects telemetrySchedule, startedMotorThread, newMotorAdded void motorThreadFn() { while (true) { std::unique_lock lock(motorsMutex); if (telemetrySchedule.empty()) { motorsCV.wait(lock, [] { return newMotorAdded; }); newMotorAdded = false; } else { auto now = clock::now(); auto ts = telemetrySchedule.top(); if (ts.nextSendTime <= now) { telemetrySchedule.pop(); pullMotorPosition(ts.serial); telemetrySchedule.push( {ts.nextSendTime + ts.telemPeriod, ts.telemPeriod, ts.serial}); } else { motorsCV.wait_until(lock, ts.nextSendTime, [] { return newMotorAdded; }); newMotorAdded = false; } } } } void startMonitoringMotor(deviceserial_t motor, std::chrono::milliseconds period) { { std::unique_lock lock(motorsMutex); if (!startedMotorThread) { startedMotorThread = true; std::thread motorThread(motorThreadFn); motorThread.detach(); } telemetrySchedule.push({clock::now(), period, motor}); newMotorAdded = true; } motorsCV.notify_one(); } } // namespace void initEncoder(deviceserial_t serial, bool invertEncoder, bool zeroEncoder, int32_t pulsesPerJointRev, std::optional<std::chrono::milliseconds> telemetryPeriod) { auto motorGroupCode = static_cast<uint8_t>(devicegroup_t::motor); CANPacket p; AssembleEncoderInitializePacket(&p, motorGroupCode, serial, sensor_t::encoder, invertEncoder, zeroEncoder); sendCANPacket(p); std::this_thread::sleep_for(1000us); AssembleEncoderPPJRSetPacket(&p, motorGroupCode, serial, pulsesPerJointRev); sendCANPacket(p); std::this_thread::sleep_for(1000us); if (telemetryPeriod) { startMonitoringMotor(serial, telemetryPeriod.value()); } } void pullMotorPosition(deviceserial_t serial) { CANPacket p; AssembleTelemetryPullPacket(&p, static_cast<uint8_t>(devicegroup_t::motor), serial, static_cast<uint8_t>(telemtype_t::angle)); sendCANPacket(p); } } // namespace can::motor
27.596154
91
0.74216