text
stringlengths
54
60.6k
<commit_before>2d5b1590-2e4e-11e5-9284-b827eb9e62be<commit_msg>2d6028b4-2e4e-11e5-9284-b827eb9e62be<commit_after>2d6028b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>12d7f38c-2e4e-11e5-9284-b827eb9e62be<commit_msg>12dd1c36-2e4e-11e5-9284-b827eb9e62be<commit_after>12dd1c36-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ab29c800-2e4d-11e5-9284-b827eb9e62be<commit_msg>ab2eb676-2e4d-11e5-9284-b827eb9e62be<commit_after>ab2eb676-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dc7df430-2e4d-11e5-9284-b827eb9e62be<commit_msg>dc8302c2-2e4d-11e5-9284-b827eb9e62be<commit_after>dc8302c2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a444fcd4-2e4e-11e5-9284-b827eb9e62be<commit_msg>a44a164c-2e4e-11e5-9284-b827eb9e62be<commit_after>a44a164c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>03325886-2e4f-11e5-9284-b827eb9e62be<commit_msg>033751d8-2e4f-11e5-9284-b827eb9e62be<commit_after>033751d8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>64b5baf4-2e4e-11e5-9284-b827eb9e62be<commit_msg>64babe50-2e4e-11e5-9284-b827eb9e62be<commit_after>64babe50-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>648c6b5a-2e4d-11e5-9284-b827eb9e62be<commit_msg>64917014-2e4d-11e5-9284-b827eb9e62be<commit_after>64917014-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c08e3f6e-2e4d-11e5-9284-b827eb9e62be<commit_msg>c0935404-2e4d-11e5-9284-b827eb9e62be<commit_after>c0935404-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dc6ba75e-2e4c-11e5-9284-b827eb9e62be<commit_msg>dc7097fa-2e4c-11e5-9284-b827eb9e62be<commit_after>dc7097fa-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>292f4544-2e4f-11e5-9284-b827eb9e62be<commit_msg>293436e4-2e4f-11e5-9284-b827eb9e62be<commit_after>293436e4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2ca0353a-2e4f-11e5-9284-b827eb9e62be<commit_msg>2ca52ad6-2e4f-11e5-9284-b827eb9e62be<commit_after>2ca52ad6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8db165e4-2e4d-11e5-9284-b827eb9e62be<commit_msg>8dc4b96e-2e4d-11e5-9284-b827eb9e62be<commit_after>8dc4b96e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d5351140-2e4d-11e5-9284-b827eb9e62be<commit_msg>d53a065a-2e4d-11e5-9284-b827eb9e62be<commit_after>d53a065a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>07691676-2e4d-11e5-9284-b827eb9e62be<commit_msg>076e2198-2e4d-11e5-9284-b827eb9e62be<commit_after>076e2198-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9311d306-2e4e-11e5-9284-b827eb9e62be<commit_msg>9316cab4-2e4e-11e5-9284-b827eb9e62be<commit_after>9316cab4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>82a481fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>82a977e0-2e4d-11e5-9284-b827eb9e62be<commit_after>82a977e0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>997f609c-2e4d-11e5-9284-b827eb9e62be<commit_msg>9984625e-2e4d-11e5-9284-b827eb9e62be<commit_after>9984625e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8724edc6-2e4e-11e5-9284-b827eb9e62be<commit_msg>8729f348-2e4e-11e5-9284-b827eb9e62be<commit_after>8729f348-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>582f110a-2e4d-11e5-9284-b827eb9e62be<commit_msg>5834138a-2e4d-11e5-9284-b827eb9e62be<commit_after>5834138a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>15d58762-2e4d-11e5-9284-b827eb9e62be<commit_msg>15daad0a-2e4d-11e5-9284-b827eb9e62be<commit_after>15daad0a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>690651d2-2e4d-11e5-9284-b827eb9e62be<commit_msg>690b5d08-2e4d-11e5-9284-b827eb9e62be<commit_after>690b5d08-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>57156a94-2e4d-11e5-9284-b827eb9e62be<commit_msg>571a7688-2e4d-11e5-9284-b827eb9e62be<commit_after>571a7688-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>def15528-2e4c-11e5-9284-b827eb9e62be<commit_msg>def646a0-2e4c-11e5-9284-b827eb9e62be<commit_after>def646a0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>98dddf6e-2e4e-11e5-9284-b827eb9e62be<commit_msg>98e31c04-2e4e-11e5-9284-b827eb9e62be<commit_after>98e31c04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>35b4903c-2e4d-11e5-9284-b827eb9e62be<commit_msg>35b99bae-2e4d-11e5-9284-b827eb9e62be<commit_after>35b99bae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a2800db2-2e4e-11e5-9284-b827eb9e62be<commit_msg>a2852144-2e4e-11e5-9284-b827eb9e62be<commit_after>a2852144-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c93df438-2e4d-11e5-9284-b827eb9e62be<commit_msg>c942ecf4-2e4d-11e5-9284-b827eb9e62be<commit_after>c942ecf4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d38d4fb0-2e4d-11e5-9284-b827eb9e62be<commit_msg>d3925082-2e4d-11e5-9284-b827eb9e62be<commit_after>d3925082-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd5b22d0-2e4c-11e5-9284-b827eb9e62be<commit_msg>cd6ec47a-2e4c-11e5-9284-b827eb9e62be<commit_after>cd6ec47a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ad242ac4-2e4d-11e5-9284-b827eb9e62be<commit_msg>ad292a38-2e4d-11e5-9284-b827eb9e62be<commit_after>ad292a38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aabb3da0-2e4c-11e5-9284-b827eb9e62be<commit_msg>aac02b80-2e4c-11e5-9284-b827eb9e62be<commit_after>aac02b80-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1f9d2aac-2e4d-11e5-9284-b827eb9e62be<commit_msg>1fa26e54-2e4d-11e5-9284-b827eb9e62be<commit_after>1fa26e54-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>270e860a-2e4d-11e5-9284-b827eb9e62be<commit_msg>27137f48-2e4d-11e5-9284-b827eb9e62be<commit_after>27137f48-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9c5299b4-2e4e-11e5-9284-b827eb9e62be<commit_msg>9c5791e4-2e4e-11e5-9284-b827eb9e62be<commit_after>9c5791e4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>993b8142-2e4d-11e5-9284-b827eb9e62be<commit_msg>99407b52-2e4d-11e5-9284-b827eb9e62be<commit_after>99407b52-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>93d6f8bc-2e4d-11e5-9284-b827eb9e62be<commit_msg>93dbffe2-2e4d-11e5-9284-b827eb9e62be<commit_after>93dbffe2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34f44308-2e4e-11e5-9284-b827eb9e62be<commit_msg>34f99c04-2e4e-11e5-9284-b827eb9e62be<commit_after>34f99c04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>792285e0-2e4d-11e5-9284-b827eb9e62be<commit_msg>79277924-2e4d-11e5-9284-b827eb9e62be<commit_after>79277924-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5c820ee2-2e4d-11e5-9284-b827eb9e62be<commit_msg>5c87148c-2e4d-11e5-9284-b827eb9e62be<commit_after>5c87148c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f1e2d444-2e4d-11e5-9284-b827eb9e62be<commit_msg>f1e7eae2-2e4d-11e5-9284-b827eb9e62be<commit_after>f1e7eae2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f210a3b0-2e4d-11e5-9284-b827eb9e62be<commit_msg>f215b490-2e4d-11e5-9284-b827eb9e62be<commit_after>f215b490-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>494a5c08-2e4d-11e5-9284-b827eb9e62be<commit_msg>494f67b6-2e4d-11e5-9284-b827eb9e62be<commit_after>494f67b6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a1df7870-2e4e-11e5-9284-b827eb9e62be<commit_msg>a1e46ccc-2e4e-11e5-9284-b827eb9e62be<commit_after>a1e46ccc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>70f9afb0-2e4d-11e5-9284-b827eb9e62be<commit_msg>70fec0c2-2e4d-11e5-9284-b827eb9e62be<commit_after>70fec0c2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b769ae1e-2e4d-11e5-9284-b827eb9e62be<commit_msg>b76ef45a-2e4d-11e5-9284-b827eb9e62be<commit_after>b76ef45a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5b208d1c-2e4d-11e5-9284-b827eb9e62be<commit_msg>5b259a32-2e4d-11e5-9284-b827eb9e62be<commit_after>5b259a32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1758cfac-2e4f-11e5-9284-b827eb9e62be<commit_msg>175dd8e4-2e4f-11e5-9284-b827eb9e62be<commit_after>175dd8e4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a3a71df2-2e4e-11e5-9284-b827eb9e62be<commit_msg>a3ac2f54-2e4e-11e5-9284-b827eb9e62be<commit_after>a3ac2f54-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>22cf071c-2e4e-11e5-9284-b827eb9e62be<commit_msg>22d46cd4-2e4e-11e5-9284-b827eb9e62be<commit_after>22d46cd4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2f9e3fa4-2e4d-11e5-9284-b827eb9e62be<commit_msg>2fa3325c-2e4d-11e5-9284-b827eb9e62be<commit_after>2fa3325c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cc242b6c-2e4e-11e5-9284-b827eb9e62be<commit_msg>cc29304e-2e4e-11e5-9284-b827eb9e62be<commit_after>cc29304e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b2a39e48-2e4e-11e5-9284-b827eb9e62be<commit_msg>b2a89f56-2e4e-11e5-9284-b827eb9e62be<commit_after>b2a89f56-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a6733520-2e4e-11e5-9284-b827eb9e62be<commit_msg>a6784ac4-2e4e-11e5-9284-b827eb9e62be<commit_after>a6784ac4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cc97154c-2e4d-11e5-9284-b827eb9e62be<commit_msg>cc9c1bdc-2e4d-11e5-9284-b827eb9e62be<commit_after>cc9c1bdc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bc9e01f4-2e4e-11e5-9284-b827eb9e62be<commit_msg>bca322c4-2e4e-11e5-9284-b827eb9e62be<commit_after>bca322c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>11835f8e-2e4f-11e5-9284-b827eb9e62be<commit_msg>118854b2-2e4f-11e5-9284-b827eb9e62be<commit_after>118854b2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6c6fc064-2e4e-11e5-9284-b827eb9e62be<commit_msg>6c74cbcc-2e4e-11e5-9284-b827eb9e62be<commit_after>6c74cbcc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>de628d7e-2e4d-11e5-9284-b827eb9e62be<commit_msg>de6799cc-2e4d-11e5-9284-b827eb9e62be<commit_after>de6799cc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3e6f36b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>3e745238-2e4e-11e5-9284-b827eb9e62be<commit_after>3e745238-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>79b18646-2e4d-11e5-9284-b827eb9e62be<commit_msg>79b67994-2e4d-11e5-9284-b827eb9e62be<commit_after>79b67994-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>beeb3f4e-2e4e-11e5-9284-b827eb9e62be<commit_msg>bef04f16-2e4e-11e5-9284-b827eb9e62be<commit_after>bef04f16-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>939055b0-2e4d-11e5-9284-b827eb9e62be<commit_msg>93955682-2e4d-11e5-9284-b827eb9e62be<commit_after>93955682-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aad8d7f2-2e4c-11e5-9284-b827eb9e62be<commit_msg>aaddc668-2e4c-11e5-9284-b827eb9e62be<commit_after>aaddc668-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aebc08f8-2e4c-11e5-9284-b827eb9e62be<commit_msg>aec1018c-2e4c-11e5-9284-b827eb9e62be<commit_after>aec1018c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1ff71330-2e4f-11e5-9284-b827eb9e62be<commit_msg>1ffc0930-2e4f-11e5-9284-b827eb9e62be<commit_after>1ffc0930-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>45698464-2e4e-11e5-9284-b827eb9e62be<commit_msg>456e8ce8-2e4e-11e5-9284-b827eb9e62be<commit_after>456e8ce8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b364664c-2e4d-11e5-9284-b827eb9e62be<commit_msg>b3695f9e-2e4d-11e5-9284-b827eb9e62be<commit_after>b3695f9e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>60da6f70-2e4d-11e5-9284-b827eb9e62be<commit_msg>60df7646-2e4d-11e5-9284-b827eb9e62be<commit_after>60df7646-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>82987b60-2e4e-11e5-9284-b827eb9e62be<commit_msg>829de726-2e4e-11e5-9284-b827eb9e62be<commit_after>829de726-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1dbea52e-2e4f-11e5-9284-b827eb9e62be<commit_msg>1dc3a31c-2e4f-11e5-9284-b827eb9e62be<commit_after>1dc3a31c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3da86908-2e4d-11e5-9284-b827eb9e62be<commit_msg>3dad77b8-2e4d-11e5-9284-b827eb9e62be<commit_after>3dad77b8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fe1464f4-2e4c-11e5-9284-b827eb9e62be<commit_msg>fe195e64-2e4c-11e5-9284-b827eb9e62be<commit_after>fe195e64-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f78ebfc0-2e4d-11e5-9284-b827eb9e62be<commit_msg>f793ac24-2e4d-11e5-9284-b827eb9e62be<commit_after>f793ac24-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>37796fe4-2e4f-11e5-9284-b827eb9e62be<commit_msg>377e6990-2e4f-11e5-9284-b827eb9e62be<commit_after>377e6990-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e04c7f06-2e4c-11e5-9284-b827eb9e62be<commit_msg>e0516c00-2e4c-11e5-9284-b827eb9e62be<commit_after>e0516c00-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>02f2c352-2e4e-11e5-9284-b827eb9e62be<commit_msg>02f7b934-2e4e-11e5-9284-b827eb9e62be<commit_after>02f7b934-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>91ad1a34-2e4e-11e5-9284-b827eb9e62be<commit_msg>91b2176e-2e4e-11e5-9284-b827eb9e62be<commit_after>91b2176e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb54c2c6-2e4d-11e5-9284-b827eb9e62be<commit_msg>fb59b4f2-2e4d-11e5-9284-b827eb9e62be<commit_after>fb59b4f2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>13b5eecc-2e4d-11e5-9284-b827eb9e62be<commit_msg>13bb03a8-2e4d-11e5-9284-b827eb9e62be<commit_after>13bb03a8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>40092192-2e4d-11e5-9284-b827eb9e62be<commit_msg>400e26ba-2e4d-11e5-9284-b827eb9e62be<commit_after>400e26ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b7eb3592-2e4d-11e5-9284-b827eb9e62be<commit_msg>b7f02674-2e4d-11e5-9284-b827eb9e62be<commit_after>b7f02674-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ba9c8e80-2e4d-11e5-9284-b827eb9e62be<commit_msg>baa182c8-2e4d-11e5-9284-b827eb9e62be<commit_after>baa182c8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>09cba176-2e4e-11e5-9284-b827eb9e62be<commit_msg>09d0be04-2e4e-11e5-9284-b827eb9e62be<commit_after>09d0be04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0bcf152e-2e4f-11e5-9284-b827eb9e62be<commit_msg>0bd409d0-2e4f-11e5-9284-b827eb9e62be<commit_after>0bd409d0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** ** Copyright (C) 2010, 2012 Aldebaran Robotics */ #include <vector> #include <iostream> #include <string> #include <gtest/gtest.h> #include <qimessaging/session.hpp> #include <qitype/anyobject.hpp> #include <qitype/dynamicobjectbuilder.hpp> #include <qitype/dynamicobject.hpp> #include <qitype/objecttypebuilder.hpp> #include <qimessaging/servicedirectory.hpp> #include <qimessaging/gateway.hpp> #include <qi/os.hpp> #include <qi/application.hpp> #include <testsession/testsessionpair.hpp> qiLogCategory("test"); static std::string reply(const std::string &msg) { return msg; } /* For asynchronous things where no synchronisation mechanism * is possible, loop the check and wait a small delay, * instead of one big sleep that will slow us down * */ #define PERSIST_CHECK(code, cond, what, msdelay) \ do \ { \ code; \ for(unsigned i=0; i<50 && !(cond); ++i) \ { \ qi::os::msleep(1 + msdelay / 50); \ code; \ } \ what(cond); \ } while(0) #define PERSIST_ASSERT(code, cond, msdelay) \ PERSIST_CHECK(code, cond, ASSERT_TRUE, msdelay) #define PERSIST_EXPECT(code, cond, msdelay) \ PERSIST_CHECK(code, cond, EXPECT_TRUE, msdelay) #define PERSIST(code, cond, msdelay) \ PERSIST_CHECK(code, cond, (void),msdelay) //check for server closed //check for socket disconnected //check for service unregistered //check for service unregistered, then readded TEST(QiService, RemoteObjectCacheServerClose) { TestSessionPair p; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->close(); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); } TEST(QiService, RemoteObjectCacheUnregister) { TestSessionPair p; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->unregisterService(idx); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); } TEST(QiService, RemoteObjectCacheABAUnregister) { TestSessionPair p; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->unregisterService(idx); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); unsigned int idx2 = p.server()->registerService("serviceTest", obj); //new service should not have a previoulsy registered ID EXPECT_NE(idx2, idx); fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi"); if (fret.hasError()) { std::cout << "Error returned:" << fret.error(); } EXPECT_FALSE(fret.hasError()); EXPECT_EQ(std::string("titi"), fret.value()); } TEST(QiService, RemoteObjectCacheABANewServer) { TestSessionPair p; qi::Session ses; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->close(); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); qi::Future<void> f = ses.connect(p.client()->url().str()); f.wait(8000); EXPECT_FALSE(f.hasError()); ses.listen("tcp://0.0.0.0:0"); unsigned int idx2 = ses.registerService("serviceTest", obj); //new service should not have a previoulsy registered ID EXPECT_NE(idx2, idx); fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi"); if (fret.hasError()) { std::cout << "Error returned:" << fret.error(); } EXPECT_FALSE(fret.hasError()); EXPECT_EQ(std::string("titi"), fret.value()); } TEST(QiService, RemoteObjectNackTransactionWhenServerClosed) { TestSessionPair p; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("msleep", &qi::os::msleep); qi::AnyObject obj(ob.object()); p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<void> fret = fut.value().call<void>("msleep", 2000); qi::Future<void> fclose = p.server()->close(); fclose.wait(1000); EXPECT_TRUE(fclose.isFinished()); EXPECT_FALSE(fclose.hasError(1)); fret.wait(1000); //once the server is close, the answer should be ready. EXPECT_TRUE(fret.isFinished()); //the service is closed, so it can't send an answer. EXPECT_TRUE(fret.hasError(1000)); } class Foo { public: int ping(int i) { return i + prop.get();} qi::Property<int> prop; }; void inc (int* daInt, int unused) { ++(*daInt); } TEST(QiService, ClassProperty) { TestSessionPair p; qi::ObjectTypeBuilder<Foo> builder; builder.advertiseMethod("ping", &Foo::ping); ASSERT_TRUE(builder.advertiseProperty("offset", &Foo::prop) > 0); Foo f; qi::AnyObject obj = builder.object(&f, &qi::AnyObject::deleteGenericObjectOnly); p.server()->registerService("foo", obj); qi::AnyObject client = p.client()->service("foo"); qi::details::printMetaObject(std::cerr, obj.metaObject()); std::cerr <<"--" << std::endl; qi::details::printMetaObject(std::cerr, client.metaObject()); qiLogDebug() << "setProp"; client.setProperty<int>("offset", 1).value(); qiLogDebug() << "setProp done"; ASSERT_EQ(1, f.prop.get()); ASSERT_EQ(2, client.call<int>("ping", 1)); f.prop.set(2); ASSERT_EQ(3, client.call<int>("ping", 1)); ASSERT_EQ(2, client.property<int>("offset")); // test event int hit = 0; f.prop.connect(boost::bind(&inc, &hit, _1)); obj.connect("offset", boost::bind(&inc, &hit,_1)); client.connect("offset", boost::bind(&inc, &hit,_1)); f.prop.set(1); PERSIST_ASSERT(, hit == 3, 500); client.setProperty("offset", 2); PERSIST_ASSERT(, hit == 6, 500); // test error handling EXPECT_TRUE(client.setProperty("canard", 5).hasError()); EXPECT_TRUE(client.setProperty("offset", "astring").hasError()); } int prop_ping(qi::PropertyBase* &p, int v) { return p->value().toInt() + v; } TEST(QiService, GenericProperty) { TestSessionPair p; qi::DynamicObject* dobj = new qi::DynamicObject(); qi::DynamicObjectBuilder builder(dobj); unsigned int propId = builder.advertiseProperty<int>("offset"); qi::PropertyBase* prop; builder.advertiseMethod("ping", (boost::function<int (int)>)boost::bind(&prop_ping, boost::ref(prop), _1)); qi::AnyObject obj = builder.object(); prop = dobj->property(propId); prop->setValue(qi::AnyValue(qi::AnyReference(0))); p.server()->registerService("foo", obj); qi::AnyObject client = p.client()->service("foo"); client.setProperty("offset", 1); ASSERT_EQ(1, prop->value().toInt()); ASSERT_EQ(2, client.call<int>("ping", 1)); prop->setValue(qi::AnyValue(qi::AnyReference(2))); ASSERT_EQ(3, client.call<int>("ping", 1)); ASSERT_EQ(2, client.property<int>("offset")); // test event int hit = 0; qiLogVerbose() << "Connecting to signal"; ASSERT_NE(qi::SignalBase::invalidSignalLink, prop->signal()->connect((boost::function<void(int)>)boost::bind(&inc, &hit, _1))); ASSERT_NE(qi::SignalBase::invalidSignalLink, obj.connect("offset", boost::bind(&inc, &hit, _1))); ASSERT_NE(qi::SignalBase::invalidSignalLink, client.connect("offset", boost::bind(&inc, &hit, _1))); qiLogVerbose() << "Triggering prop set"; prop->setValue(qi::AnyValue(qi::AnyReference(1))); PERSIST(, hit == 3, 500); qi::os::msleep(500); EXPECT_EQ(3, hit); client.setProperty<int>("offset", 2); PERSIST(, hit == 6, 500); qi::os::msleep(500); EXPECT_EQ(6, hit); if (client != obj) { client.call<void>("setProperty", "offset", 3); EXPECT_EQ(3, prop->value().toInt()); } // test error handling EXPECT_TRUE(client.setProperty("canard", 5).hasError()); EXPECT_TRUE(client.setProperty("offset", "astring").hasError()); } class Bar { public: void ping() { } }; QI_REGISTER_OBJECT(Bar, ping) TEST(QiService, RemoteServiceRegistrationAfterDisconnection) { TestSessionPair p; // Create an object boost::shared_ptr<Bar> bar(new Bar()); qi::AnyObject barAsObject = qi::AnyValue::from(bar).to<qi::AnyObject>(); // Register the object with the provider, find it back from the client p.server()->registerService("Bar", barAsObject); qi::AnyObject barAsRemoteService = p.client()->service("Bar"); ASSERT_TRUE(barAsRemoteService != NULL); // Disconnect the provider, it should unregister any related services p.server()->close(); qi::Future<void> fc = p.server()->connect(p.serviceDirectoryEndpoints()[0]); fc.wait(1000); if (fc.hasError()) qiLogError() << fc.error(); ASSERT_TRUE(fc.hasValue()); // Register the object again with the provider, find it back from the client ASSERT_NO_THROW(p.server()->registerService("Bar", barAsObject)); qi::Future<qi::AnyObject> f = p.client()->service("Bar"); f.wait(1000); ASSERT_TRUE(f.hasValue()); barAsRemoteService = f.value(); ASSERT_TRUE(barAsRemoteService != NULL); } int main(int argc, char **argv) { qi::Application app(argc, argv); #if defined(__APPLE__) || defined(__linux__) setsid(); #endif TestMode::initTestMode(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>test_service: Fix ++ race by using atomics.<commit_after>/* ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** ** Copyright (C) 2010, 2012 Aldebaran Robotics */ #include <vector> #include <iostream> #include <string> #include <gtest/gtest.h> #include <qimessaging/session.hpp> #include <qitype/anyobject.hpp> #include <qitype/dynamicobjectbuilder.hpp> #include <qitype/dynamicobject.hpp> #include <qitype/objecttypebuilder.hpp> #include <qimessaging/servicedirectory.hpp> #include <qimessaging/gateway.hpp> #include <qi/os.hpp> #include <qi/application.hpp> #include <testsession/testsessionpair.hpp> qiLogCategory("test"); static std::string reply(const std::string &msg) { return msg; } /* For asynchronous things where no synchronisation mechanism * is possible, loop the check and wait a small delay, * instead of one big sleep that will slow us down * */ #define PERSIST_CHECK(code, cond, what, msdelay) \ do \ { \ code; \ for(unsigned i=0; i<50 && !(cond); ++i) \ { \ qi::os::msleep(1 + msdelay / 50); \ code; \ } \ what(cond); \ } while(0) #define PERSIST_ASSERT(code, cond, msdelay) \ PERSIST_CHECK(code, cond, ASSERT_TRUE, msdelay) #define PERSIST_EXPECT(code, cond, msdelay) \ PERSIST_CHECK(code, cond, EXPECT_TRUE, msdelay) #define PERSIST(code, cond, msdelay) \ PERSIST_CHECK(code, cond, (void),msdelay) //check for server closed //check for socket disconnected //check for service unregistered //check for service unregistered, then readded TEST(QiService, RemoteObjectCacheServerClose) { TestSessionPair p; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->close(); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); } TEST(QiService, RemoteObjectCacheUnregister) { TestSessionPair p; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->unregisterService(idx); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); } TEST(QiService, RemoteObjectCacheABAUnregister) { TestSessionPair p; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->unregisterService(idx); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); unsigned int idx2 = p.server()->registerService("serviceTest", obj); //new service should not have a previoulsy registered ID EXPECT_NE(idx2, idx); fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi"); if (fret.hasError()) { std::cout << "Error returned:" << fret.error(); } EXPECT_FALSE(fret.hasError()); EXPECT_EQ(std::string("titi"), fret.value()); } TEST(QiService, RemoteObjectCacheABANewServer) { TestSessionPair p; qi::Session ses; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("reply", &reply); qi::AnyObject obj(ob.object()); unsigned int idx = p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value()); p.server()->close(); PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000); qi::Future<void> f = ses.connect(p.client()->url().str()); f.wait(8000); EXPECT_FALSE(f.hasError()); ses.listen("tcp://0.0.0.0:0"); unsigned int idx2 = ses.registerService("serviceTest", obj); //new service should not have a previoulsy registered ID EXPECT_NE(idx2, idx); fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi"); if (fret.hasError()) { std::cout << "Error returned:" << fret.error(); } EXPECT_FALSE(fret.hasError()); EXPECT_EQ(std::string("titi"), fret.value()); } TEST(QiService, RemoteObjectNackTransactionWhenServerClosed) { TestSessionPair p; if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode return; qi::DynamicObjectBuilder ob; ob.advertiseMethod("msleep", &qi::os::msleep); qi::AnyObject obj(ob.object()); p.server()->registerService("serviceTest", obj); qi::Future<qi::AnyObject> fut; fut = p.client()->service("serviceTest"); EXPECT_FALSE(fut.hasError()); qi::Future<void> fret = fut.value().call<void>("msleep", 2000); qi::Future<void> fclose = p.server()->close(); fclose.wait(1000); EXPECT_TRUE(fclose.isFinished()); EXPECT_FALSE(fclose.hasError(1)); fret.wait(1000); //once the server is close, the answer should be ready. EXPECT_TRUE(fret.isFinished()); //the service is closed, so it can't send an answer. EXPECT_TRUE(fret.hasError(1000)); } class Foo { public: int ping(int i) { return i + prop.get();} qi::Property<int> prop; }; void inc (qi::Atomic<int>* daInt, int unused) { ++(*daInt); } TEST(QiService, ClassProperty) { TestSessionPair p; qi::ObjectTypeBuilder<Foo> builder; builder.advertiseMethod("ping", &Foo::ping); ASSERT_TRUE(builder.advertiseProperty("offset", &Foo::prop) > 0); Foo f; qi::AnyObject obj = builder.object(&f, &qi::AnyObject::deleteGenericObjectOnly); p.server()->registerService("foo", obj); qi::AnyObject client = p.client()->service("foo"); qi::details::printMetaObject(std::cerr, obj.metaObject()); std::cerr <<"--" << std::endl; qi::details::printMetaObject(std::cerr, client.metaObject()); qiLogDebug() << "setProp"; client.setProperty<int>("offset", 1).value(); qiLogDebug() << "setProp done"; ASSERT_EQ(1, f.prop.get()); ASSERT_EQ(2, client.call<int>("ping", 1)); f.prop.set(2); ASSERT_EQ(3, client.call<int>("ping", 1)); ASSERT_EQ(2, client.property<int>("offset")); // test event qi::Atomic<int> hit = 0; f.prop.connect(boost::bind(&inc, &hit, _1)); obj.connect("offset", boost::bind(&inc, &hit,_1)); client.connect("offset", boost::bind(&inc, &hit,_1)); f.prop.set(1); PERSIST_ASSERT(, (*hit) == 3, 500); client.setProperty("offset", 2); PERSIST_ASSERT(, (*hit) == 6, 500); // test error handling EXPECT_TRUE(client.setProperty("canard", 5).hasError()); EXPECT_TRUE(client.setProperty("offset", "astring").hasError()); } int prop_ping(qi::PropertyBase* &p, int v) { return p->value().toInt() + v; } TEST(QiService, GenericProperty) { TestSessionPair p; qi::DynamicObject* dobj = new qi::DynamicObject(); qi::DynamicObjectBuilder builder(dobj); unsigned int propId = builder.advertiseProperty<int>("offset"); qi::PropertyBase* prop; builder.advertiseMethod("ping", (boost::function<int (int)>)boost::bind(&prop_ping, boost::ref(prop), _1)); qi::AnyObject obj = builder.object(); prop = dobj->property(propId); prop->setValue(qi::AnyValue(qi::AnyReference(0))); p.server()->registerService("foo", obj); qi::AnyObject client = p.client()->service("foo"); client.setProperty("offset", 1); ASSERT_EQ(1, prop->value().toInt()); ASSERT_EQ(2, client.call<int>("ping", 1)); prop->setValue(qi::AnyValue(qi::AnyReference(2))); ASSERT_EQ(3, client.call<int>("ping", 1)); ASSERT_EQ(2, client.property<int>("offset")); // test event qi::Atomic<int> hit; qiLogVerbose() << "Connecting to signal"; ASSERT_NE(qi::SignalBase::invalidSignalLink, prop->signal()->connect((boost::function<void(int)>)boost::bind(&inc, &hit, _1))); ASSERT_NE(qi::SignalBase::invalidSignalLink, obj.connect("offset", boost::bind(&inc, &hit, _1))); ASSERT_NE(qi::SignalBase::invalidSignalLink, client.connect("offset", boost::bind(&inc, &hit, _1))); qiLogVerbose() << "Triggering prop set"; prop->setValue(qi::AnyValue(qi::AnyReference(1))); PERSIST(, (*hit) == 3, 500); qi::os::msleep(500); EXPECT_EQ(3, *hit); client.setProperty<int>("offset", 2); PERSIST(, (*hit) == 6, 500); qi::os::msleep(500); EXPECT_EQ(6, *hit); if (client != obj) { client.call<void>("setProperty", "offset", 3); EXPECT_EQ(3, prop->value().toInt()); } // test error handling EXPECT_TRUE(client.setProperty("canard", 5).hasError()); EXPECT_TRUE(client.setProperty("offset", "astring").hasError()); } class Bar { public: void ping() { } }; QI_REGISTER_OBJECT(Bar, ping) TEST(QiService, RemoteServiceRegistrationAfterDisconnection) { TestSessionPair p; // Create an object boost::shared_ptr<Bar> bar(new Bar()); qi::AnyObject barAsObject = qi::AnyValue::from(bar).to<qi::AnyObject>(); // Register the object with the provider, find it back from the client p.server()->registerService("Bar", barAsObject); qi::AnyObject barAsRemoteService = p.client()->service("Bar"); ASSERT_TRUE(barAsRemoteService != NULL); // Disconnect the provider, it should unregister any related services p.server()->close(); qi::Future<void> fc = p.server()->connect(p.serviceDirectoryEndpoints()[0]); fc.wait(1000); if (fc.hasError()) qiLogError() << fc.error(); ASSERT_TRUE(fc.hasValue()); // Register the object again with the provider, find it back from the client ASSERT_NO_THROW(p.server()->registerService("Bar", barAsObject)); qi::Future<qi::AnyObject> f = p.client()->service("Bar"); f.wait(1000); ASSERT_TRUE(f.hasValue()); barAsRemoteService = f.value(); ASSERT_TRUE(barAsRemoteService != NULL); } int main(int argc, char **argv) { qi::Application app(argc, argv); #if defined(__APPLE__) || defined(__linux__) setsid(); #endif TestMode::initTestMode(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <catch.hpp> #include <iostream> #include "../cauldron/just.h" #include "../cauldron/strings.h" #include "predicates.h" #include "factories.h" bool is_string_from_alphabet(const std::string &string, const std::string &alphabet_characters) { auto is_character_from_alphabet = [=](char character) -> bool { return is_character_in_string(character, alphabet_characters); }; return std::all_of(string.begin(), string.end(), is_character_from_alphabet); } TEST_CASE("\"strings\" strategy", "[strings]") { size_t min_length = 1; size_t max_length = 100; std::string non_zero_characters = factories::non_zero_characters(); SECTION("single character alphabet") { strategies::Just<size_t> ones(1); for (char single_character: non_zero_characters) { std::string single_character_string{single_character}; strategies::Characters same_character(single_character_string); strategies::Strings same_character_strings( std::make_shared<strategies::Just<size_t>>(ones), std::make_shared<strategies::Characters>(same_character)); auto string = same_character_strings(); REQUIRE(string == single_character_string); } } SECTION("multiple characters alphabet") { strategies::Integers<size_t> alphabets_lengths(min_length, max_length); strategies::Integers<size_t> strings_lengths(0, max_length); auto alphabet_length = alphabets_lengths(); strategies::Integers<char> characters_integers; std::string alphabet_characters; for (size_t _ = 0; _ < alphabet_length; ++_) { alphabet_characters.push_back(characters_integers()); } strategies::Characters alphabet(alphabet_characters); strategies::Strings strings( std::make_shared<strategies::Integers<size_t>>(strings_lengths), std::make_shared<strategies::Characters>(alphabet)); auto string = strings(); REQUIRE(min_length <= string.length() <= max_length); REQUIRE(is_string_from_alphabet(string, alphabet_characters)); } SECTION("filtration") { auto all_digits = [&](const std::string &string) -> bool { return std::all_of(string.begin(), string.end(), is_digit); }; auto all_alphabetic = [&](const std::string &string) -> bool { return std::all_of(string.begin(), string.end(), is_alphabetic); }; size_t max_length = 3; strategies::Integers<size_t> strings_lengths(min_length, max_length); strategies::Characters non_zero(non_zero_characters); auto alphanumeric = non_zero.filter(is_alphanumeric); strategies::Strings strings( std::make_shared<strategies::Integers<size_t>>(strings_lengths), std::move(alphanumeric)); SECTION("alphanumeric") { auto all_digits_strings = strings.filter(all_digits); auto all_alphabetic_strings = strings.filter(all_alphabetic); auto all_digits_string = (*all_digits_strings)(); auto all_alphabetic_string = (*all_alphabetic_strings)(); REQUIRE(min_length <= all_digits_string.length() <= max_length); REQUIRE(all_digits(all_digits_string)); REQUIRE(all_alphabetic(all_alphabetic_string)); } SECTION("impossible") { auto invalid_strings = strings.filter(all_digits)->filter(all_alphabetic); REQUIRE_THROWS_AS((*invalid_strings)(), strategies::OutOfCycles); } } } <commit_msg>Using 'min/max capacity' constants, 'characters_string' factory, 'sufficient_capacity' utility instead of local variables and hardcoded values<commit_after>#include <catch.hpp> #include <iostream> #include "../cauldron/just.h" #include "../cauldron/strings.h" #include "predicates.h" #include "factories.h" #include "utils.h" bool is_string_from_alphabet(const std::string &string, const std::string &alphabet_characters) { auto is_character_from_alphabet = [=](char character) -> bool { return is_character_in_string(character, alphabet_characters); }; return std::all_of(string.begin(), string.end(), is_character_from_alphabet); } TEST_CASE("\"strings\" strategy", "[strings]") { std::string non_zero_characters = factories::non_zero_characters(); SECTION("single character alphabet") { strategies::Just<size_t> ones(1); for (char single_character: non_zero_characters) { std::string single_character_string{single_character}; strategies::Characters same_character(single_character_string); strategies::Strings same_character_strings( std::make_shared<strategies::Just<size_t>>(ones), std::make_shared<strategies::Characters>(same_character)); auto string = same_character_strings(); REQUIRE(string == single_character_string); } } SECTION("multiple characters alphabet") { size_t min_length = 0; size_t max_length = constants::max_capacity; const std::shared_ptr<strategies::Integers<size_t>> &lengths = std::make_shared<strategies::Integers<size_t>>(min_length, max_length); std::string alphabet_characters = factories::characters_string( constants::min_capacity, constants::max_capacity); const std::shared_ptr<strategies::Characters> &alphabet = std::make_shared<strategies::Characters>(alphabet_characters); strategies::Strings strings(lengths, alphabet); auto string = strings(); auto stays_in_range = in_range_checker<size_t>(min_length, max_length); REQUIRE(stays_in_range(string.length())); REQUIRE(is_string_from_alphabet(string, alphabet_characters)); } SECTION("filtration") { auto all_digits = [&](const std::string &string) -> bool { return std::all_of(string.begin(), string.end(), is_digit); }; auto all_alphabetic = [&](const std::string &string) -> bool { return std::all_of(string.begin(), string.end(), is_alphabetic); }; size_t min_length = constants::min_capacity; size_t max_length = sufficient_capacity( constants::alphanumeric_characters_count, constants::non_zero_characters_count, strategies::MAX_CYCLES); strategies::Integers<size_t> strings_lengths(min_length, max_length); strategies::Characters non_zero(non_zero_characters); auto alphanumeric = non_zero.filter(is_alphanumeric); strategies::Strings strings( std::make_shared<strategies::Integers<size_t>>(strings_lengths), std::move(alphanumeric)); SECTION("alphanumeric") { auto all_digits_strings = strings.filter(all_digits); auto all_alphabetic_strings = strings.filter(all_alphabetic); auto all_digits_string = (*all_digits_strings)(); auto all_alphabetic_string = (*all_alphabetic_strings)(); auto stays_in_range = in_range_checker(min_length, max_length); REQUIRE(stays_in_range(all_digits_string.length())); REQUIRE(stays_in_range(all_alphabetic_string.length())); REQUIRE(all_digits(all_digits_string)); REQUIRE(all_alphabetic(all_alphabetic_string)); } SECTION("impossible") { auto invalid_strings = strings.filter(all_digits)->filter(all_alphabetic); REQUIRE_THROWS_AS((*invalid_strings)(), strategies::OutOfCycles); } } } <|endoftext|>
<commit_before> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #define BOOST_TEST_IGNORE_NON_ZERO_CHILD_CODE #include <boost/version.hpp> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <string> #include <vector> #include "storage/Exception.h" #include "storage/Utils/Mockup.h" #include "storage/Utils/SystemCmd.h" using namespace std; using namespace storage; string join(const vector<string>& input) { return boost::join(input, "\n") + "\n"; } BOOST_AUTO_TEST_CASE(hello_stdout) { vector<string> stdout = { "stdout #1: hello", "stdout #2: stdout" }; SystemCmd cmd( "helpers/echoargs hello stdout" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK(cmd.stderr().empty()); BOOST_CHECK(cmd.retcode() == 0); } BOOST_AUTO_TEST_CASE(hello_stderr) { vector<string> stderr = { "stderr #1: hello", "stderr #2: stderr" }; SystemCmd cmd("helpers/echoargs_stderr hello stderr"); BOOST_CHECK_EQUAL(join(cmd.stderr()),join(stderr)); BOOST_CHECK(cmd.stdout().empty()); } BOOST_AUTO_TEST_CASE(hello_mixed) { vector<string> stdout = { "line #1: stdout #1: mixed", "line #3: stdout #2: stdout", "line #5: stdout #3: stderr" }; vector<string> stderr = { "line #2: stderr #1: to", "line #4: stderr #2: and" }; SystemCmd cmd( "helpers/echoargs_mixed mixed to stdout and stderr" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK_EQUAL(join(cmd.stderr()), join(stderr)); } BOOST_AUTO_TEST_CASE(retcode_42) { SystemCmd cmd("helpers/retcode 42"); BOOST_CHECK(cmd.retcode() == 42); } BOOST_AUTO_TEST_CASE(non_existent_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_existent_throw) { BOOST_CHECK_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::DoThrow);}, CommandNotFoundException); } BOOST_AUTO_TEST_CASE(segfault_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(segfault_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } BOOST_AUTO_TEST_CASE(non_exec_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_exec_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } <commit_msg>- removed unneeded define<commit_after> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <boost/version.hpp> #include <boost/test/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <iostream> #include <string> #include <vector> #include "storage/Exception.h" #include "storage/Utils/Mockup.h" #include "storage/Utils/SystemCmd.h" using namespace std; using namespace storage; string join(const vector<string>& input) { return boost::join(input, "\n") + "\n"; } BOOST_AUTO_TEST_CASE(hello_stdout) { vector<string> stdout = { "stdout #1: hello", "stdout #2: stdout" }; SystemCmd cmd( "helpers/echoargs hello stdout" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK(cmd.stderr().empty()); BOOST_CHECK(cmd.retcode() == 0); } BOOST_AUTO_TEST_CASE(hello_stderr) { vector<string> stderr = { "stderr #1: hello", "stderr #2: stderr" }; SystemCmd cmd("helpers/echoargs_stderr hello stderr"); BOOST_CHECK_EQUAL(join(cmd.stderr()),join(stderr)); BOOST_CHECK(cmd.stdout().empty()); } BOOST_AUTO_TEST_CASE(hello_mixed) { vector<string> stdout = { "line #1: stdout #1: mixed", "line #3: stdout #2: stdout", "line #5: stdout #3: stderr" }; vector<string> stderr = { "line #2: stderr #1: to", "line #4: stderr #2: and" }; SystemCmd cmd( "helpers/echoargs_mixed mixed to stdout and stderr" ); BOOST_CHECK_EQUAL(join(cmd.stdout()), join(stdout)); BOOST_CHECK_EQUAL(join(cmd.stderr()), join(stderr)); } BOOST_AUTO_TEST_CASE(retcode_42) { SystemCmd cmd("helpers/retcode 42"); BOOST_CHECK(cmd.retcode() == 42); } BOOST_AUTO_TEST_CASE(non_existent_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_existent_throw) { BOOST_CHECK_THROW({SystemCmd cmd("/bin/wrglbrmpf", SystemCmd::ThrowBehaviour::DoThrow);}, CommandNotFoundException); } BOOST_AUTO_TEST_CASE(segfault_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(segfault_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "helpers/segfaulter", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } BOOST_AUTO_TEST_CASE(non_exec_no_throw) { BOOST_CHECK_NO_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::NoThrow);}); } BOOST_AUTO_TEST_CASE(non_exec_throw) { BOOST_CHECK_THROW({SystemCmd cmd( "/etc/fstab", SystemCmd::ThrowBehaviour::DoThrow);}, SystemCmdException); } <|endoftext|>
<commit_before>#include "compare.h" #include <cassert> #include <cmath> int remove_single_exon_transcripts(genome &gm) { for(int i = 0; i < gm.genes.size(); i++) { gm.genes[i].remove_single_exon_transcripts(); } return 0; } bool compare_structure(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; for(int i = 0; i < x.exons.size(); i++) { if(x.exons[i].first != y.exons[i].first) return false; if(x.exons[i].second != y.exons[i].second) return false; } return true; } bool compare_intron_chain(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; if(x.exons.size() == 0) return false; if(x.exons.size() == 1) { if(fabs(x.exons[0].first - y.exons[0].first) > 100) return false; if(fabs(x.exons[0].second - y.exons[0].second) > 100) return false; return true; } for(int i = 0; i < x.exons.size(); i++) { double diff1 = 0.5; double diff2 = 0.5; if(i == 0) diff1 = 9999999999; if(i == x.exons.size() - 1) diff2 = 9999999999; if(fabs(x.exons[i].first - y.exons[i].first) > diff1) return false; if(fabs(x.exons[i].second - y.exons[i].second) > diff2) return false; } return true; } bool compare_expression(const transcript &x, const transcript &y) { if(x.expression == y.expression) return true; else return false; } int compare_gene(const gene &x, const gene &y, int mode) { return compare_transcripts(x.transcripts, y.transcripts, mode); } int compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode) { int cnt = 0; vector<bool> v; v.assign(y.size(), false); for(int i = 0; i < x.size(); i++) { const transcript &t1 = x[i]; bool flag = false; for(int j = 0; j < y.size(); j++) { if(v[j] == true) continue; const transcript &t2 = y[j]; bool b = false; if(mode == 1) { if(compare_structure(t1, t2) == false) b = false; if(compare_expression(t1, t2) == false) b = false; } if(mode == 2) { b = compare_intron_chain(t1, t2); if(b == true) { printf("TRUE %s %s %s %c %d %lu %d %.2lf %.2lf %s %s %s %c %d %lu %d %.2lf %.2lf\n", t1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length(), t1.coverage, t1.coverage / t1.length() * 100.0, t2.gene_id.c_str(), t2.transcript_id.c_str(), t2.label().c_str(), t2.strand, t2.expression, t2.exons.size(), t2.length(), t2.coverage, t2.coverage / t2.length() * 100.0); } if(t1.strand != t2.strand) b = false; } if(b == false) continue; flag = true; v[j] = true; cnt++; break; } if(flag == false) printf("FALSE %s %s %s %c %d %lu %d %.2lf %.2lf\n", t1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length(), t1.coverage, t1.coverage / t1.length() * 100.0); } return cnt; } int compare_gene_bounds(const gene &x, const gene &y) { if(x.get_seqname() != y.get_seqname()) return 0; PI32 px = x.get_bounds(); PI32 py = y.get_bounds(); assert(px.first < px.second); assert(py.first < py.second); if(py.first < px.first && px.first < py.second && py.second < px.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d overlap1\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(px.first < py.first && py.first < px.second && px.second < py.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d overlap2\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(px.first <= py.first && px.second >= py.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d inclusive1\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(py.first <= px.first && py.second >= px.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d inclusive2\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); return 0; } int compare_genome1(const genome &x, const genome &y) { int gequal = 0; int tequal = 0; int gtotal = x.genes.size(); int ttotal = 0; for(int i = 0; i < x.genes.size(); i++) { const gene* gx = &(x.genes[i]); const gene* gy = y.get_gene(x.genes[i].get_gene_id()); if(gx == NULL || gy == NULL) continue; int tx = gx->transcripts.size(); int ty = gy->transcripts.size(); int t0 = compare_gene(*gx, *gy, 1); assert(t0 <= tx); assert(t0 <= ty); ttotal += tx; tequal += t0; if(t0 == tx) gequal++; string s; if(tx == ty) s = "EQUAL"; else if(tx > ty) s = "GREATER"; else s = "LESS"; printf("%s %d and %d transcripts, %d are equal, %s, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE", s.c_str()); } printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n", gequal, gtotal, tequal, ttotal); return 0; } int compare_genome2(const genome &x, const genome &y) { typedef pair< string, vector<transcript> > PSVT; typedef map< string, vector<transcript> > MSVT; MSVT m1; MSVT m2; int xtotal = 0; int ytotal = 0; for(int i = 0; i < x.genes.size(); i++) { string chrm = x.genes[i].get_seqname(); const vector<transcript> &v = x.genes[i].transcripts; xtotal += v.size(); if(m1.find(chrm) == m1.end()) { m1.insert(PSVT(chrm, v)); } else { m1[chrm].insert(m1[chrm].end(), v.begin(), v.end()); } } for(int i = 0; i < y.genes.size(); i++) { string chrm = y.genes[i].get_seqname(); const vector<transcript> &v = y.genes[i].transcripts; ytotal += v.size(); if(m2.find(chrm) == m2.end()) { m2.insert(PSVT(chrm, v)); } else { m2[chrm].insert(m2[chrm].end(), v.begin(), v.end()); } } int correct = 0; for(MSVT::iterator it = m1.begin(); it != m1.end(); it++) { const vector<transcript> &v1 = it->second; if(m2.find(it->first) == m2.end()) continue; const vector<transcript> &v2 = m2[it->first]; correct += compare_transcripts(v1, v2, 2); } double s = (xtotal == 0) ? 0 : correct * 100.0 / xtotal; double p = (ytotal == 0) ? 0 : correct * 100.0 / ytotal; printf("reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\n", xtotal, ytotal, correct, s, p); return 0; } int compare_genome3(const genome &x, const genome &y) { typedef pair< string, vector<int> > PSVI; typedef map< string, vector<int> > MSVI; MSVI m1; MSVI m2; for(int i = 0; i < x.genes.size(); i++) { string chrm = x.genes[i].get_seqname(); if(m1.find(chrm) == m1.end()) { vector<int> v; v.push_back(i); m1.insert(PSVI(chrm, v)); } else { m1[chrm].push_back(i); } } for(int i = 0; i < y.genes.size(); i++) { string chrm = y.genes[i].get_seqname(); if(m2.find(chrm) == m2.end()) { vector<int> v; v.push_back(i); m2.insert(PSVI(chrm, v)); } else { m2[chrm].push_back(i); } } for(MSVI::iterator it = m1.begin(); it != m1.end(); it++) { vector<int> v1 = it->second; if(m2.find(it->first) == m2.end()) continue; vector<int> v2 = m2[it->first]; for(int i = 0; i < v1.size(); i++) { for(int j = 0; j < v2.size(); j++) { compare_gene_bounds(x.genes[v1[i]], y.genes[v2[j]]); } } } return 0; } <commit_msg>output RPKM<commit_after>#include "compare.h" #include <cassert> #include <cmath> int remove_single_exon_transcripts(genome &gm) { for(int i = 0; i < gm.genes.size(); i++) { gm.genes[i].remove_single_exon_transcripts(); } return 0; } bool compare_structure(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; for(int i = 0; i < x.exons.size(); i++) { if(x.exons[i].first != y.exons[i].first) return false; if(x.exons[i].second != y.exons[i].second) return false; } return true; } bool compare_intron_chain(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; if(x.exons.size() == 0) return false; if(x.exons.size() == 1) { if(fabs(x.exons[0].first - y.exons[0].first) > 100) return false; if(fabs(x.exons[0].second - y.exons[0].second) > 100) return false; return true; } for(int i = 0; i < x.exons.size(); i++) { double diff1 = 0.5; double diff2 = 0.5; if(i == 0) diff1 = 9999999999; if(i == x.exons.size() - 1) diff2 = 9999999999; if(fabs(x.exons[i].first - y.exons[i].first) > diff1) return false; if(fabs(x.exons[i].second - y.exons[i].second) > diff2) return false; } return true; } bool compare_expression(const transcript &x, const transcript &y) { if(x.expression == y.expression) return true; else return false; } int compare_gene(const gene &x, const gene &y, int mode) { return compare_transcripts(x.transcripts, y.transcripts, mode); } int compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode) { int cnt = 0; vector<bool> v; v.assign(y.size(), false); for(int i = 0; i < x.size(); i++) { const transcript &t1 = x[i]; bool flag = false; for(int j = 0; j < y.size(); j++) { if(v[j] == true) continue; const transcript &t2 = y[j]; bool b = false; if(mode == 1) { if(compare_structure(t1, t2) == false) b = false; if(compare_expression(t1, t2) == false) b = false; } if(mode == 2) { b = compare_intron_chain(t1, t2); if(b == true) { printf("TRUE %s %s %s %c %lu %d %d %.2lf %.2lf %s %s %s %c %lu %d %d %.2lf %.2lf\n", t1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.exons.size(), t1.length(), t1.expression, t1.coverage, t1.RPKM, t2.gene_id.c_str(), t2.transcript_id.c_str(), t2.label().c_str(), t2.strand, t2.exons.size(), t2.length(), t2.expression, t2.coverage, t2.RPKM); } if(t1.strand != t2.strand) b = false; } if(b == false) continue; flag = true; v[j] = true; cnt++; break; } if(flag == false) printf("FALSE %s %s %s %c %lu %d %d %.2lf %.2lf\n", t1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.exons.size(), t1.length(), t1.expression, t1.coverage, t1.RPKM); } return cnt; } int compare_gene_bounds(const gene &x, const gene &y) { if(x.get_seqname() != y.get_seqname()) return 0; PI32 px = x.get_bounds(); PI32 py = y.get_bounds(); assert(px.first < px.second); assert(py.first < py.second); if(py.first < px.first && px.first < py.second && py.second < px.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d overlap1\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(px.first < py.first && py.first < px.second && px.second < py.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d overlap2\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(px.first <= py.first && px.second >= py.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d inclusive1\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); if(py.first <= px.first && py.second >= px.second) printf("%s %c %s:%d-%d %s %c %s:%d-%d inclusive2\n", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second); return 0; } int compare_genome1(const genome &x, const genome &y) { int gequal = 0; int tequal = 0; int gtotal = x.genes.size(); int ttotal = 0; for(int i = 0; i < x.genes.size(); i++) { const gene* gx = &(x.genes[i]); const gene* gy = y.get_gene(x.genes[i].get_gene_id()); if(gx == NULL || gy == NULL) continue; int tx = gx->transcripts.size(); int ty = gy->transcripts.size(); int t0 = compare_gene(*gx, *gy, 1); assert(t0 <= tx); assert(t0 <= ty); ttotal += tx; tequal += t0; if(t0 == tx) gequal++; string s; if(tx == ty) s = "EQUAL"; else if(tx > ty) s = "GREATER"; else s = "LESS"; printf("%s %d and %d transcripts, %d are equal, %s, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE", s.c_str()); } printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n", gequal, gtotal, tequal, ttotal); return 0; } int compare_genome2(const genome &x, const genome &y) { typedef pair< string, vector<transcript> > PSVT; typedef map< string, vector<transcript> > MSVT; MSVT m1; MSVT m2; int xtotal = 0; int ytotal = 0; for(int i = 0; i < x.genes.size(); i++) { string chrm = x.genes[i].get_seqname(); const vector<transcript> &v = x.genes[i].transcripts; xtotal += v.size(); if(m1.find(chrm) == m1.end()) { m1.insert(PSVT(chrm, v)); } else { m1[chrm].insert(m1[chrm].end(), v.begin(), v.end()); } } for(int i = 0; i < y.genes.size(); i++) { string chrm = y.genes[i].get_seqname(); const vector<transcript> &v = y.genes[i].transcripts; ytotal += v.size(); if(m2.find(chrm) == m2.end()) { m2.insert(PSVT(chrm, v)); } else { m2[chrm].insert(m2[chrm].end(), v.begin(), v.end()); } } int correct = 0; for(MSVT::iterator it = m1.begin(); it != m1.end(); it++) { const vector<transcript> &v1 = it->second; if(m2.find(it->first) == m2.end()) continue; const vector<transcript> &v2 = m2[it->first]; correct += compare_transcripts(v1, v2, 2); } double s = (xtotal == 0) ? 0 : correct * 100.0 / xtotal; double p = (ytotal == 0) ? 0 : correct * 100.0 / ytotal; printf("reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\n", xtotal, ytotal, correct, s, p); return 0; } int compare_genome3(const genome &x, const genome &y) { typedef pair< string, vector<int> > PSVI; typedef map< string, vector<int> > MSVI; MSVI m1; MSVI m2; for(int i = 0; i < x.genes.size(); i++) { string chrm = x.genes[i].get_seqname(); if(m1.find(chrm) == m1.end()) { vector<int> v; v.push_back(i); m1.insert(PSVI(chrm, v)); } else { m1[chrm].push_back(i); } } for(int i = 0; i < y.genes.size(); i++) { string chrm = y.genes[i].get_seqname(); if(m2.find(chrm) == m2.end()) { vector<int> v; v.push_back(i); m2.insert(PSVI(chrm, v)); } else { m2[chrm].push_back(i); } } for(MSVI::iterator it = m1.begin(); it != m1.end(); it++) { vector<int> v1 = it->second; if(m2.find(it->first) == m2.end()) continue; vector<int> v2 = m2[it->first]; for(int i = 0; i < v1.size(); i++) { for(int j = 0; j < v2.size(); j++) { compare_gene_bounds(x.genes[v1[i]], y.genes[v2[j]]); } } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 Muhammad Tayyab Akram * * 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. */ extern "C" { #include <SBCodepointSequence.h> #include <SBLine.h> #include <SBMirrorLocator.h> } #include <jni.h> #include "BidiBuffer.h" #include "JavaBridge.h" #include "BidiMirrorLocator.h" using namespace Tehreer; static jlong create(JNIEnv *env, jobject obj) { SBMirrorLocatorRef mirrorLocator = SBMirrorLocatorCreate(); return reinterpret_cast<jlong>(mirrorLocator); } static void dispose(JNIEnv *env, jobject obj, jlong locatorHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); SBMirrorLocatorRelease(mirrorLocator); } static void loadLine(JNIEnv *env, jobject obj, jlong locatorHandle, jlong lineHandle, jlong bufferHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); SBLineRef bidiLine = reinterpret_cast<SBLineRef>(lineHandle); BidiBuffer *bidiBuffer = reinterpret_cast<BidiBuffer *>(bufferHandle); void *stringBuffer = static_cast<void *>(bidiBuffer->data()); SBMirrorLocatorLoadLine(mirrorLocator, bidiLine, stringBuffer); } static jobject getNextPair(JNIEnv *env, jobject obj, jlong locatorHandle, jlong bufferHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); if (SBMirrorLocatorMoveNext(mirrorLocator)) { BidiBuffer *bidiBuffer = reinterpret_cast<BidiBuffer *>(bufferHandle); void *stringBuffer = static_cast<void *>(bidiBuffer->data()); SBUInteger stringLength = static_cast<SBUInteger>(bidiBuffer->length()); SBCodepointSequence codepointSequence; codepointSequence.stringEncoding = SBStringEncodingUTF16; codepointSequence.stringBuffer = stringBuffer; codepointSequence.stringLength = stringLength; SBMirrorAgentRef mirrorAgent = SBMirrorLocatorGetAgent(mirrorLocator); SBUInteger index = mirrorAgent->index; SBCodepoint source = SBCodepointSequenceGetCodepointAt(&codepointSequence, &index); SBCodepoint mirror = mirrorAgent->mirror; jint charIndex = static_cast<jint>(index); jint actualCodePoint = static_cast<jint>(source); jint pairingCodePoint = static_cast<jint>(mirror); return JavaBridge(env).BidiPair_construct(charIndex, actualCodePoint, pairingCodePoint); } return nullptr; } static JNINativeMethod JNI_METHODS[] = { { "nCreate", "()J", (void *)create }, { "nDispose", "(J)V", (void *)dispose }, { "nLoadLine", "(JJJ)V", (void *)loadLine }, { "nGetNextPair", "(JJ)Lcom/mta/tehreer/unicode/BidiPair;", (void *)getNextPair }, }; jint register_com_mta_tehreer_unicode_BidiMirrorLocator(JNIEnv *env) { return JavaBridge::registerClass(env, "com/mta/tehreer/unicode/BidiMirrorLocator", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0])); } <commit_msg>[jni] Simplified bidi mirror locator<commit_after>/* * Copyright (C) 2016-2018 Muhammad Tayyab Akram * * 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. */ extern "C" { #include <SBCodepointSequence.h> #include <SBLine.h> #include <SBMirrorLocator.h> } #include <jni.h> #include "BidiBuffer.h" #include "JavaBridge.h" #include "BidiMirrorLocator.h" using namespace Tehreer; static jlong create(JNIEnv *env, jobject obj) { SBMirrorLocatorRef mirrorLocator = SBMirrorLocatorCreate(); return reinterpret_cast<jlong>(mirrorLocator); } static void dispose(JNIEnv *env, jobject obj, jlong locatorHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); SBMirrorLocatorRelease(mirrorLocator); } static void loadLine(JNIEnv *env, jobject obj, jlong locatorHandle, jlong lineHandle, jlong bufferHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); SBLineRef bidiLine = reinterpret_cast<SBLineRef>(lineHandle); BidiBuffer *bidiBuffer = reinterpret_cast<BidiBuffer *>(bufferHandle); void *stringBuffer = static_cast<void *>(bidiBuffer->data()); SBMirrorLocatorLoadLine(mirrorLocator, bidiLine, stringBuffer); } static jobject getNextPair(JNIEnv *env, jobject obj, jlong locatorHandle) { SBMirrorLocatorRef mirrorLocator = reinterpret_cast<SBMirrorLocatorRef>(locatorHandle); if (SBMirrorLocatorMoveNext(mirrorLocator)) { const SBMirrorAgent *mirrorAgent = SBMirrorLocatorGetAgent(mirrorLocator); jint charIndex = static_cast<jint>(mirrorAgent->index); jint actualCodePoint = static_cast<jint>(mirrorAgent->codepoint); jint pairingCodePoint = static_cast<jint>(mirrorAgent->mirror); return JavaBridge(env).BidiPair_construct(charIndex, actualCodePoint, pairingCodePoint); } return nullptr; } static JNINativeMethod JNI_METHODS[] = { { "nCreate", "()J", (void *)create }, { "nDispose", "(J)V", (void *)dispose }, { "nLoadLine", "(JJJ)V", (void *)loadLine }, { "nGetNextPair", "(J)Lcom/mta/tehreer/unicode/BidiPair;", (void *)getNextPair }, }; jint register_com_mta_tehreer_unicode_BidiMirrorLocator(JNIEnv *env) { return JavaBridge::registerClass(env, "com/mta/tehreer/unicode/BidiMirrorLocator", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0])); } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-02-05 Martin Siggel <martin.siggel@dlr.de> * * 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 <QDialog> #include <QColorDialog> #include <TIGLViewerSettingsDialog.h> #include <TIGLViewerSettings.h> #include <cmath> #include <iostream> #define WORST_TESSELATION 0.01 #define BEST_TESSELATION 0.00001 #define WORST_TRIANGULATION 0.01 #define BEST_TRIANGULATION 0.00005 TIGLViewerSettingsDialog::TIGLViewerSettingsDialog(TIGLViewerSettings& settings, QWidget *parent) : _settings(settings), QDialog(parent) { setupUi(this); tessAccuEdit->setText (QString("%1").arg(sliderTesselationAccuracy->value())); trianAccuEdit->setText(QString("%1").arg(sliderTriangulationAccuracy->value())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(onSettingsAccepted())); connect(sliderTesselationAccuracy, SIGNAL(valueChanged(int)), this, SLOT(onSliderTesselationChanged(int))); connect(sliderTriangulationAccuracy, SIGNAL(valueChanged(int)), this, SLOT(onSliderTriangulationChanged(int))); connect(buttonColorChoser, SIGNAL(clicked()), this, SLOT(onColorChoserPushed())); } double TIGLViewerSettingsDialog::calcTesselationAccu(int value){ // calculate tesselation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TESSELATION, dmin = BEST_TESSELATION; int imin = sliderTesselationAccuracy->minimum(), imax = sliderTesselationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); return c * exp(-mu * (double)value); } double TIGLViewerSettingsDialog::calcTriangulationAccu(int value){ // calculate triangulation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TRIANGULATION, dmin = BEST_TRIANGULATION; int imin = sliderTriangulationAccuracy->minimum(), imax = sliderTriangulationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); return c * exp(-mu * (double)value); } void TIGLViewerSettingsDialog::onSettingsAccepted(){ _settings.setTesselationAccuracy(calcTesselationAccu(sliderTesselationAccuracy->value())); _settings.setTriangulationAccuracy(calcTriangulationAccu(sliderTriangulationAccuracy->value())); _settings.setBGColor(_bgcolor); } void TIGLViewerSettingsDialog::updateEntries(){ // calculate tesselation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TESSELATION, dmin = BEST_TESSELATION; int imin = sliderTesselationAccuracy->minimum(), imax = sliderTesselationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); int tessVal = int (log(c/_settings.tesselationAccuracy())/mu); sliderTesselationAccuracy->setValue(tessVal); dmax = WORST_TRIANGULATION, dmin = BEST_TRIANGULATION; imin = sliderTriangulationAccuracy->minimum(), imax = sliderTriangulationAccuracy->maximum(); mu = log(dmax/dmin)/double(imax-imin); c = dmax / exp(-mu * (double)imin); int triaVal = int (log(c/_settings.triangulationAccuracy())/mu); sliderTriangulationAccuracy->setValue(triaVal); _bgcolor = _settings.BGColor(); updateBGColorButton(); } void TIGLViewerSettingsDialog::onSliderTesselationChanged(int val){ tessAccuEdit->setText(QString("%1").arg(val)); } void TIGLViewerSettingsDialog::onSliderTriangulationChanged(int val){ trianAccuEdit->setText(QString("%1").arg(val)); } void TIGLViewerSettingsDialog::onColorChoserPushed(){ QColor col = QColorDialog::getColor(_bgcolor, this); if(col.isValid()) { _bgcolor = col; updateBGColorButton(); } } void TIGLViewerSettingsDialog::updateBGColorButton(){ QString qss = QString("background-color: %1").arg(_bgcolor.name()); buttonColorChoser->setStyleSheet(qss); } TIGLViewerSettingsDialog::~TIGLViewerSettingsDialog() { } <commit_msg>tweaked color btn style<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-02-05 Martin Siggel <martin.siggel@dlr.de> * * 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 <QDialog> #include <QColorDialog> #include <TIGLViewerSettingsDialog.h> #include <TIGLViewerSettings.h> #include <cmath> #include <iostream> #define WORST_TESSELATION 0.01 #define BEST_TESSELATION 0.00001 #define WORST_TRIANGULATION 0.01 #define BEST_TRIANGULATION 0.00005 #define BTN_STYLE "#buttonColorChoser {background-color: %1; border: 1px solid black; border-radius: 5px;} #buttonColorChoser:hover {border: 1px solid white;}" TIGLViewerSettingsDialog::TIGLViewerSettingsDialog(TIGLViewerSettings& settings, QWidget *parent) : _settings(settings), QDialog(parent) { setupUi(this); tessAccuEdit->setText (QString("%1").arg(sliderTesselationAccuracy->value())); trianAccuEdit->setText(QString("%1").arg(sliderTriangulationAccuracy->value())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(onSettingsAccepted())); connect(sliderTesselationAccuracy, SIGNAL(valueChanged(int)), this, SLOT(onSliderTesselationChanged(int))); connect(sliderTriangulationAccuracy, SIGNAL(valueChanged(int)), this, SLOT(onSliderTriangulationChanged(int))); connect(buttonColorChoser, SIGNAL(clicked()), this, SLOT(onColorChoserPushed())); } double TIGLViewerSettingsDialog::calcTesselationAccu(int value){ // calculate tesselation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TESSELATION, dmin = BEST_TESSELATION; int imin = sliderTesselationAccuracy->minimum(), imax = sliderTesselationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); return c * exp(-mu * (double)value); } double TIGLViewerSettingsDialog::calcTriangulationAccu(int value){ // calculate triangulation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TRIANGULATION, dmin = BEST_TRIANGULATION; int imin = sliderTriangulationAccuracy->minimum(), imax = sliderTriangulationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); return c * exp(-mu * (double)value); } void TIGLViewerSettingsDialog::onSettingsAccepted(){ _settings.setTesselationAccuracy(calcTesselationAccu(sliderTesselationAccuracy->value())); _settings.setTriangulationAccuracy(calcTriangulationAccu(sliderTriangulationAccuracy->value())); _settings.setBGColor(_bgcolor); } void TIGLViewerSettingsDialog::updateEntries(){ // calculate tesselation accuracy, slider range is from 0 ... 10 // we map it onto 0.1 to 0.00001 - logarithmic slider double dmax = WORST_TESSELATION, dmin = BEST_TESSELATION; int imin = sliderTesselationAccuracy->minimum(), imax = sliderTesselationAccuracy->maximum(); double mu = log(dmax/dmin)/double(imax-imin); double c = dmax / exp(-mu * (double)imin); int tessVal = int (log(c/_settings.tesselationAccuracy())/mu); sliderTesselationAccuracy->setValue(tessVal); dmax = WORST_TRIANGULATION, dmin = BEST_TRIANGULATION; imin = sliderTriangulationAccuracy->minimum(), imax = sliderTriangulationAccuracy->maximum(); mu = log(dmax/dmin)/double(imax-imin); c = dmax / exp(-mu * (double)imin); int triaVal = int (log(c/_settings.triangulationAccuracy())/mu); sliderTriangulationAccuracy->setValue(triaVal); _bgcolor = _settings.BGColor(); updateBGColorButton(); } void TIGLViewerSettingsDialog::onSliderTesselationChanged(int val){ tessAccuEdit->setText(QString("%1").arg(val)); } void TIGLViewerSettingsDialog::onSliderTriangulationChanged(int val){ trianAccuEdit->setText(QString("%1").arg(val)); } void TIGLViewerSettingsDialog::onColorChoserPushed(){ QColor col = QColorDialog::getColor(_bgcolor, this); if(col.isValid()) { _bgcolor = col; updateBGColorButton(); } } void TIGLViewerSettingsDialog::updateBGColorButton(){ QString qss = QString(BTN_STYLE).arg(_bgcolor.name()); buttonColorChoser->setStyleSheet(qss); } TIGLViewerSettingsDialog::~TIGLViewerSettingsDialog() { } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageAdaptor.h" #include "itkAffineTransform.txx" #include "itkArray.txx" #include "itkArray2D.txx" #include "itkAsinImageAdaptor.h" #include "itkAtanImageAdaptor.h" #include "itkAzimuthElevationToCartesianTransform.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBackwardDifferenceOperator.txx" #include "itkBinaryBallStructuringElement.txx" #include "itkBinaryThresholdImageFunction.txx" #include "itkBloxBoundaryPointImage.txx" #include "itkBloxBoundaryPointItem.txx" #include "itkBloxBoundaryPointPixel.txx" #include "itkBloxCoreAtomImage.txx" #include "itkBloxCoreAtomItem.txx" #include "itkBloxCoreAtomPixel.txx" #include "itkBloxImage.txx" #include "itkBloxItem.h" #include "itkBloxPixel.txx" #include "itkBluePixelAccessor.h" #include "itkBoundingBox.txx" #include "itkByteSwapper.txx" #include "itkCellBoundary.txx" #include "itkCellInterface.txx" #include "itkCellInterfaceVisitor.h" #include "itkCentralDifferenceImageFunction.txx" #include "itkColorTable.txx" #include "itkCommand.h" #include "itkConceptChecking.h" #include "itkConditionalIterator.txx" #include "itkConicShellInteriorExteriorSpatialFunction.txx" #include "itkConstNeighborhoodIterator.txx" #include "itkConstRandomAccessNeighborhoodIterator.txx" #include "itkConstSliceIterator.h" #include "itkConstSmartNeighborhoodIterator.txx" #include "itkConstantBoundaryCondition.h" #include "itkContinuousIndex.h" #include "itkCosImageAdaptor.h" #include "itkCovariantVector.txx" #include "itkCreateObjectFunction.h" #include "itkDataObject.h" #include "itkDecisionRuleBase.h" #include "itkDefaultDynamicMeshTraits.h" #include "itkDefaultImageTraits.h" #include "itkDefaultPixelAccessor.h" #include "itkDefaultStaticMeshTraits.h" #include "itkDenseFiniteDifferenceImageFilter.txx" #include "itkDerivativeOperator.txx" #include "itkDirectory.h" #include "itkDynamicLoader.h" #include "itkElasticBodySplineKernelTransform.txx" #include "itkEllipsoidInteriorExteriorSpatialFunction.txx" #include "itkEntropyPreservingGradientMagnitudeImageFunction.txx" #include "itkEventObject.h" #include "itkExceptionObject.h" #include "itkExpImageAdaptor.h" #include "itkFastMutexLock.h" #include "itkFileOutputWindow.h" #include "itkFiniteDifferenceFunction.txx" #include "itkFiniteDifferenceImageFilter.txx" #include "itkFixedArray.txx" #include "itkFloodFilledFunctionConditionalIterator.txx" #include "itkFloodFilledImageFunctionConditionalIterator.txx" #include "itkFloodFilledSpatialFunctionConditionalIterator.txx" #include "itkForwardDifferenceOperator.txx" #include "itkFrustumSpatialFunction.txx" #include "itkFunctionBase.h" #include "itkGaussianKernelFunction.h" #include "itkGaussianOperator.txx" #include "itkGaussianSpatialFunction.txx" #include "itkGreenPixelAccessor.h" #include "itkHexahedronCell.txx" #include "itkIdentityTransform.h" #include "itkImage.txx" #include "itkImageAdaptor.txx" #include "itkImageBase.txx" #include "itkImageBoundaryCondition.h" #include "itkImageConstIterator.txx" #include "itkImageConstIteratorWithIndex.txx" #include "itkImageContainerInterface.h" #include "itkImageFunction.txx" #include "itkImageIO.h" #include "itkImageIOCommon.h" #include "itkImageIterator.txx" #include "itkImageIteratorWithIndex.txx" #include "itkImageLinearConstIteratorWithIndex.txx" #include "itkImageLinearIteratorWithIndex.txx" #include "itkImageRegion.txx" #include "itkImageRegionConstIteratorWithIndex.txx" #include "itkImageRegionExclusionConstIteratorWithIndex.txx" #include "itkImageRegionExclusionIteratorWithIndex.txx" #include "itkImageRegionIterator.txx" #include "itkImageRegionIteratorWithIndex.txx" #include "itkImageRegionMultidimensionalSplitter.txx" #include "itkImageRegionReverseIterator.txx" #include "itkImageRegionSplitter.txx" #include "itkImageReverseIterator.txx" #include "itkImageSliceConstIteratorWithIndex.txx" #include "itkImageSliceIteratorWithIndex.txx" #include "itkImageSource.txx" #include "itkImageToImageFilter.txx" #include "itkImportImageContainer.txx" #include "itkIndent.h" #include "itkIndex.h" #include "itkIndexedContainerInterface.h" #include "itkIntTypes.h" #include "itkInteriorExteriorSpatialFunction.txx" #include "itkInterpolateImageFunction.h" #include "itkKLMSegmentationBorder.h" #include "itkKLMSegmentationRegion.h" #include "itkKernelFunction.h" #include "itkKernelTransform.txx" #include "itkLaplacianOperator.txx" #include "itkLevelSetCurvatureFunction.txx" #include "itkLightObject.h" #include "itkLightProcessObject.h" #include "itkLineCell.txx" #include "itkLinearInterpolateImageFunction.txx" #include "itkLog10ImageAdaptor.h" #include "itkLogImageAdaptor.h" #include "itkMacro.h" #include "itkMapContainer.txx" #include "itkMatrix.txx" #include "itkMeanImageFunction.txx" #include "itkMedianImageFunction.txx" #include "itkMesh.txx" #include "itkMeshRegion.h" #include "itkMeshSource.txx" #include "itkMeshToMeshFilter.txx" #include "itkMinimumDecisionRule.h" #include "itkMultiThreader.h" #include "itkMutexLock.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkNeighborhood.txx" #include "itkNeighborhoodAlgorithm.txx" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhoodBinaryThresholdImageFunction.txx" #include "itkNeighborhoodInnerProduct.txx" #include "itkNeighborhoodIterator.txx" #include "itkNeighborhoodOperator.txx" #include "itkNthElementImageAdaptor.h" #include "itkNthElementPixelAccessor.h" #include "itkNumericTraits.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkObjectFactoryBase.h" #include "itkOffset.h" #include "itkOutputWindow.h" #include "itkPixelAccessor.h" #include "itkPixelTraits.h" #include "itkPoint.txx" #include "itkPointLocator.txx" #include "itkPointSet.txx" #include "itkPolygonCell.txx" #include "itkProcessObject.h" #include "itkQuadrilateralCell.txx" #include "itkQuaternionRigidTransform.txx" #include "itkRGBAPixel.txx" #include "itkRGBPixel.txx" #include "itkRandomAccessNeighborhoodIterator.txx" #include "itkRedPixelAccessor.h" #include "itkRegion.h" #include "itkRigid3DPerspectiveTransform.txx" #include "itkRigid3DTransform.txx" #include "itkScalarVector.h" #include "itkScaleTransform.txx" #include "itkSegmentationBorder.h" #include "itkSegmentationRegion.h" #include "itkSimpleFastMutexLock.h" #include "itkSimpleImageRegionConstIterator.txx" #include "itkSimpleImageRegionIterator.txx" #include "itkSinImageAdaptor.h" #include "itkSize.h" #include "itkSliceIterator.h" #include "itkSmartNeighborhoodIterator.txx" #include "itkSmartPointer.h" #include "itkSmartPointerForwardReference.txx" #include "itkSobelOperator.txx" #include "itkSpatialFunction.txx" #include "itkSphereSpatialFunction.txx" #include "itkSqrtImageAdaptor.h" #include "itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx" #include "itkTanImageAdaptor.h" #include "itkTetrahedronCell.txx" #include "itkThinPlateSplineKernelTransform.txx" #include "itkTimeProbe.h" #include "itkTimeProbesCollectorBase.h" #include "itkTimeStamp.h" #include "itkTransform.txx" #include "itkTranslationTransform.txx" #include "itkTriangleCell.txx" #include "itkUpwindDerivativeImageFunction.txx" #include "itkValarrayImageContainer.h" #include "itkVarianceImageFunction.txx" #include "itkVector.txx" #include "itkVectorContainer.txx" #include "itkVectorInterpolateImageFunction.h" #include "itkVectorLinearInterpolateImageFunction.txx" #include "itkVectorNeighborhoodInnerProduct.txx" #include "itkVersion.h" #include "itkVersor.txx" #include "itkVersorRigid3DTransform.txx" #include "itkVersorTransform.txx" #include "itkVertexCell.txx" #include "itkWeakPointer.h" #include "itkXMLFileOutputWindow.h" #include "itkZeroFluxNeumannBoundaryCondition.txx" #include "itk_alloc.h" #include "itk_hash_map.h" #include "itk_hash_set.h" #include "itk_hashtable.h" #include "vcl_alloc.h" int main ( int argc, char* argv ) { return 0; } <commit_msg>ENH: Updated to latest headers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageAdaptor.h" #include "itkAffineTransform.txx" #include "itkArray.txx" #include "itkArray2D.txx" #include "itkAsinImageAdaptor.h" #include "itkAtanImageAdaptor.h" #include "itkAzimuthElevationToCartesianTransform.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBackwardDifferenceOperator.txx" #include "itkBinaryBallStructuringElement.txx" #include "itkBinaryThresholdImageFunction.txx" #include "itkBloxBoundaryPointImage.txx" #include "itkBloxBoundaryPointItem.txx" #include "itkBloxBoundaryPointPixel.txx" #include "itkBloxCoreAtomImage.txx" #include "itkBloxCoreAtomItem.txx" #include "itkBloxCoreAtomPixel.txx" #include "itkBloxImage.txx" #include "itkBloxItem.h" #include "itkBloxPixel.txx" #include "itkBluePixelAccessor.h" #include "itkBoundingBox.txx" #include "itkByteSwapper.txx" #include "itkCellBoundary.txx" #include "itkCellInterface.txx" #include "itkCellInterfaceVisitor.h" #include "itkCentralDifferenceImageFunction.txx" #include "itkColorTable.txx" #include "itkCommand.h" #include "itkConceptChecking.h" #include "itkConditionalConstIterator.txx" #include "itkConditionalIterator.txx" #include "itkConicShellInteriorExteriorSpatialFunction.txx" #include "itkConstNeighborhoodIterator.txx" #include "itkConstRandomAccessNeighborhoodIterator.txx" #include "itkConstSliceIterator.h" #include "itkConstSmartNeighborhoodIterator.txx" #include "itkConstantBoundaryCondition.h" #include "itkContinuousIndex.h" #include "itkCosImageAdaptor.h" #include "itkCovariantVector.txx" #include "itkCreateObjectFunction.h" #include "itkDataObject.h" #include "itkDecisionRuleBase.h" #include "itkDefaultDynamicMeshTraits.h" #include "itkDefaultImageTraits.h" #include "itkDefaultPixelAccessor.h" #include "itkDefaultStaticMeshTraits.h" #include "itkDenseFiniteDifferenceImageFilter.txx" #include "itkDerivativeOperator.txx" #include "itkDirectory.h" #include "itkDynamicLoader.h" #include "itkElasticBodySplineKernelTransform.txx" #include "itkEllipsoidInteriorExteriorSpatialFunction.txx" #include "itkEntropyPreservingGradientMagnitudeImageFunction.txx" #include "itkEventObject.h" #include "itkExceptionObject.h" #include "itkExpImageAdaptor.h" #include "itkFastMutexLock.h" #include "itkFileOutputWindow.h" #include "itkFiniteDifferenceFunction.txx" #include "itkFiniteDifferenceImageFilter.txx" #include "itkFixedArray.txx" #include "itkFloodFilledFunctionConditionalConstIterator.txx" #include "itkFloodFilledFunctionConditionalIterator.txx" #include "itkFloodFilledImageFunctionConditionalConstIterator.txx" #include "itkFloodFilledImageFunctionConditionalIterator.txx" #include "itkFloodFilledSpatialFunctionConditionalConstIterator.txx" #include "itkFloodFilledSpatialFunctionConditionalIterator.txx" #include "itkForwardDifferenceOperator.txx" #include "itkFrustumSpatialFunction.txx" #include "itkFunctionBase.h" #include "itkGaussianKernelFunction.h" #include "itkGaussianOperator.txx" #include "itkGaussianSpatialFunction.txx" #include "itkGreenPixelAccessor.h" #include "itkHexahedronCell.txx" #include "itkIdentityTransform.h" #include "itkImage.txx" #include "itkImageAdaptor.txx" #include "itkImageBase.txx" #include "itkImageBoundaryCondition.h" #include "itkImageConstIterator.txx" #include "itkImageConstIteratorWithIndex.txx" #include "itkImageContainerInterface.h" #include "itkImageFunction.txx" #include "itkImageIO.h" #include "itkImageIOCommon.h" #include "itkImageIterator.txx" #include "itkImageIteratorWithIndex.txx" #include "itkImageLinearConstIteratorWithIndex.txx" #include "itkImageLinearIteratorWithIndex.txx" #include "itkImageRegion.txx" #include "itkImageRegionConstIterator.txx" #include "itkImageRegionConstIteratorWithIndex.txx" #include "itkImageRegionExclusionConstIteratorWithIndex.txx" #include "itkImageRegionExclusionIteratorWithIndex.txx" #include "itkImageRegionIterator.txx" #include "itkImageRegionIteratorWithIndex.txx" #include "itkImageRegionMultidimensionalSplitter.txx" #include "itkImageRegionReverseIterator.txx" #include "itkImageRegionSplitter.txx" #include "itkImageReverseIterator.txx" #include "itkImageSliceConstIteratorWithIndex.txx" #include "itkImageSliceIteratorWithIndex.txx" #include "itkImageSource.txx" #include "itkImageToImageFilter.txx" #include "itkImportImageContainer.txx" #include "itkIndent.h" #include "itkIndex.h" #include "itkIndexedContainerInterface.h" #include "itkIntTypes.h" #include "itkInteriorExteriorSpatialFunction.txx" #include "itkInterpolateImageFunction.h" #include "itkKLMSegmentationBorder.h" #include "itkKLMSegmentationRegion.h" #include "itkKernelFunction.h" #include "itkKernelTransform.txx" #include "itkLaplacianOperator.txx" #include "itkLevelSetCurvatureFunction.txx" #include "itkLightObject.h" #include "itkLightProcessObject.h" #include "itkLineCell.txx" #include "itkLinearInterpolateImageFunction.txx" #include "itkLog10ImageAdaptor.h" #include "itkLogImageAdaptor.h" #include "itkMacro.h" #include "itkMapContainer.txx" #include "itkMatrix.txx" #include "itkMeanImageFunction.txx" #include "itkMedianImageFunction.txx" #include "itkMesh.txx" #include "itkMeshRegion.h" #include "itkMeshSource.txx" #include "itkMeshToMeshFilter.txx" #include "itkMinimumDecisionRule.h" #include "itkMultiThreader.h" #include "itkMutexLock.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkNeighborhood.txx" #include "itkNeighborhoodAlgorithm.txx" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhoodBinaryThresholdImageFunction.txx" #include "itkNeighborhoodInnerProduct.txx" #include "itkNeighborhoodIterator.txx" #include "itkNeighborhoodOperator.txx" #include "itkNthElementImageAdaptor.h" #include "itkNthElementPixelAccessor.h" #include "itkNumericTraits.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkObjectFactoryBase.h" #include "itkOffset.h" #include "itkOutputWindow.h" #include "itkPixelAccessor.h" #include "itkPixelTraits.h" #include "itkPoint.txx" #include "itkPointLocator.txx" #include "itkPointSet.txx" #include "itkPolygonCell.txx" #include "itkProcessObject.h" #include "itkQuadrilateralCell.txx" #include "itkQuaternionRigidTransform.txx" #include "itkRGBAPixel.txx" #include "itkRGBPixel.txx" #include "itkRandomAccessNeighborhoodIterator.txx" #include "itkRedPixelAccessor.h" #include "itkRegion.h" #include "itkRigid3DPerspectiveTransform.txx" #include "itkRigid3DTransform.txx" #include "itkScalarVector.h" #include "itkScaleTransform.txx" #include "itkSegmentationBorder.h" #include "itkSegmentationRegion.h" #include "itkSimpleFastMutexLock.h" #include "itkSimpleImageRegionConstIterator.txx" #include "itkSimpleImageRegionIterator.txx" #include "itkSinImageAdaptor.h" #include "itkSize.h" #include "itkSliceIterator.h" #include "itkSmartNeighborhoodIterator.txx" #include "itkSmartPointer.h" #include "itkSmartPointerForwardReference.txx" #include "itkSobelOperator.txx" #include "itkSpatialFunction.txx" #include "itkSphereSpatialFunction.txx" #include "itkSqrtImageAdaptor.h" #include "itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx" #include "itkTanImageAdaptor.h" #include "itkTetrahedronCell.txx" #include "itkThinPlateSplineKernelTransform.txx" #include "itkTimeProbe.h" #include "itkTimeProbesCollectorBase.h" #include "itkTimeStamp.h" #include "itkTransform.txx" #include "itkTranslationTransform.txx" #include "itkTriangleCell.txx" #include "itkUpwindDerivativeImageFunction.txx" #include "itkValarrayImageContainer.h" #include "itkVarianceImageFunction.txx" #include "itkVector.txx" #include "itkVectorContainer.txx" #include "itkVectorInterpolateImageFunction.h" #include "itkVectorLinearInterpolateImageFunction.txx" #include "itkVectorNeighborhoodInnerProduct.txx" #include "itkVersion.h" #include "itkVersor.txx" #include "itkVersorRigid3DTransform.txx" #include "itkVersorTransform.txx" #include "itkVertexCell.txx" #include "itkVolumeSplineKernelTransform.txx" #include "itkWeakPointer.h" #include "itkXMLFileOutputWindow.h" #include "itkZeroFluxNeumannBoundaryCondition.txx" #include "itk_alloc.h" #include "itk_hash_map.h" #include "itk_hash_set.h" #include "itk_hashtable.h" #include "vcl_alloc.h" int main ( int argc, char* argv ) { return 0; } <|endoftext|>
<commit_before> #include "vtkActor.h" #include "vtkAreaPicker.h" #include "vtkBSPCuts.h" #include "vtkCubeSource.h" #include "vtkFloatArray.h" #include "vtkForceDirectedLayoutStrategy.h" #include "vtkGlyph3D.h" #include "vtkGraph.h" #include "vtkGraphLayout.h" #include "vtkGraphToPolyData.h" #include "vtkIdTypeArray.h" #include "vtkInteractorStyleRubberBandPick.h" #include "vtkKdNode.h" #include "vtkKdTree.h" #include "vtkLookupTable.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRandomGraphSource.h" #include "vtkSimple2DLayoutStrategy.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include "vtkTree.h" #include "vtkTreeLevelsFilter.h" #include "vtkTreeMapToPolyData.h" #define VTK_CREATE(type,name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() // // Make a vtkTree from a kd-tree // void BuildTree(vtkIdType parent, vtkKdNode* parentVertex, vtkTree* tree, vtkFloatArray* rectArray) { double bounds[6]; parentVertex->GetBounds(bounds); rectArray->InsertTuple(parent, bounds); if (parentVertex->GetLeft() != NULL) { vtkIdType curIndex = tree->AddChild(parent); BuildTree(curIndex, parentVertex->GetLeft(), tree, rectArray); curIndex = tree->AddChild(parent); BuildTree(curIndex, parentVertex->GetRight(), tree, rectArray); } } int TestKdTreeBoxSelection(int argc, char *argv[]) { bool interactive = false; bool threedim = false; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-I")) { interactive = true; continue; } if (!strcmp(argv[i], "-d")) { threedim = true; continue; } cerr << argv[0] << " options:\n" << " -I run interactively\n" << " -d three-dimensional\n"; return 0; } // // Create a random graph and perform layout // VTK_CREATE(vtkRandomGraphSource, source); source->SetStartWithTree(true); source->SetNumberOfVertices(100); source->SetNumberOfEdges(15); VTK_CREATE(vtkGraphLayout, layout); layout->SetInputConnection(source->GetOutputPort()); if (threedim) { VTK_CREATE(vtkForceDirectedLayoutStrategy, forceLayout); forceLayout->SetGraphBounds(-3, 3, -3, 3, -3, 3); layout->SetLayoutStrategy(forceLayout); } else { VTK_CREATE(vtkSimple2DLayoutStrategy, simpleLayout); layout->SetLayoutStrategy(simpleLayout); } layout->Update(); vtkGraph* g = vtkGraph::SafeDownCast(layout->GetOutput()); // // Create the kd-tree // VTK_CREATE(vtkKdTree, kdTree); kdTree->OmitZPartitioning(); kdTree->SetMinCells(1); kdTree->BuildLocatorFromPoints(g->GetPoints()); // // Perform an area selection // VTK_CREATE(vtkIdTypeArray, selection); double bounds[6] = {-2, 2, -0.5, 3, -1, 1}; //{-1, 1, -1, 1, -1, 1}; kdTree->FindPointsInArea(bounds, selection); // // Create selected vertex glyphs // double glyphSize = 0.05; VTK_CREATE(vtkPolyData, selectPoly); VTK_CREATE(vtkPoints, selectPoints); double pt[3]; for (vtkIdType i = 0; i < selection->GetNumberOfTuples(); i++) { g->GetPoint(selection->GetValue(i), pt); selectPoints->InsertNextPoint(pt); } selectPoly->SetPoints(selectPoints); VTK_CREATE(vtkSphereSource, selectSphere); selectSphere->SetRadius(1.1*glyphSize); VTK_CREATE(vtkGlyph3D, selectGlyph); selectGlyph->SetInput(0, selectPoly); selectGlyph->SetInputConnection(1, selectSphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, selectMapper); selectMapper->SetInputConnection(selectGlyph->GetOutputPort()); VTK_CREATE(vtkActor, selectActor); selectActor->SetMapper(selectMapper); selectActor->GetProperty()->SetColor(1.0, 0.0, 0.0); // // Create selection box actor // VTK_CREATE(vtkCubeSource, cubeSource); cubeSource->SetBounds(bounds); VTK_CREATE(vtkPolyDataMapper, cubeMapper); cubeMapper->SetInputConnection(cubeSource->GetOutputPort()); VTK_CREATE(vtkActor, cubeActor); cubeActor->SetMapper(cubeMapper); cubeActor->GetProperty()->SetColor(0.0, 0.0, 1.0); cubeActor->GetProperty()->SetOpacity(0.5); // // Create kd-tree actor // VTK_CREATE(vtkTree, tree); VTK_CREATE(vtkFloatArray, rectArray); rectArray->SetName("rectangles"); rectArray->SetNumberOfComponents(4); tree->GetPointData()->AddArray(rectArray); vtkKdNode* top = kdTree->GetCuts()->GetKdNodeTree(); BuildTree(tree->AddRoot(), top, tree, rectArray); VTK_CREATE(vtkTreeLevelsFilter, treeLevels); treeLevels->SetInput(tree); VTK_CREATE(vtkTreeMapToPolyData, treePoly); treePoly->SetInputConnection(treeLevels->GetOutputPort()); VTK_CREATE(vtkLookupTable, lut); VTK_CREATE(vtkPolyDataMapper, treeMapper); treeMapper->SetInputConnection(treePoly->GetOutputPort()); treeMapper->SetScalarRange(0, 10); treeMapper->SetLookupTable(lut); VTK_CREATE(vtkActor, treeActor); treeActor->SetMapper(treeMapper); //treeActor->GetProperty()->SetRepresentationToWireframe(); //treeActor->GetProperty()->SetOpacity(0.2); // // Create graph actor // VTK_CREATE(vtkGraphToPolyData, graphToPoly); graphToPoly->SetInput(g); VTK_CREATE(vtkTransform, transform); if (threedim) { transform->Translate(0, 0, 0); } else { transform->Translate(0, 0, glyphSize); } VTK_CREATE(vtkTransformFilter, transFilter); transFilter->SetInputConnection(graphToPoly->GetOutputPort()); transFilter->SetTransform(transform); VTK_CREATE(vtkPolyDataMapper, graphMapper); graphMapper->SetInputConnection(transFilter->GetOutputPort()); VTK_CREATE(vtkActor, graphActor); graphActor->SetMapper(graphMapper); // // Create vertex glyphs // VTK_CREATE(vtkSphereSource, sphere); sphere->SetRadius(glyphSize); VTK_CREATE(vtkGlyph3D, glyph); glyph->SetInputConnection(0, graphToPoly->GetOutputPort()); glyph->SetInputConnection(1, sphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, glyphMapper); glyphMapper->SetInputConnection(glyph->GetOutputPort()); VTK_CREATE(vtkActor, glyphActor); glyphActor->SetMapper(glyphMapper); // // Set up render window // VTK_CREATE(vtkRenderer, ren); if (!threedim) { ren->AddActor(treeActor); } ren->AddActor(graphActor); ren->AddActor(glyphActor); ren->AddActor(cubeActor); ren->AddActor(selectActor); VTK_CREATE(vtkRenderWindow, win); win->AddRenderer(ren); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(win); VTK_CREATE(vtkAreaPicker, picker); iren->SetPicker(picker); VTK_CREATE(vtkInteractorStyleRubberBandPick, interact); iren->SetInteractorStyle(interact); if (interactive) { iren->Initialize(); iren->Start(); } return 0; } <commit_msg>BUG: Trying to fix 'Abnormal program termination' on the Borland compiled tests (Dash19)<commit_after> #include "vtkActor.h" #include "vtkAreaPicker.h" #include "vtkBSPCuts.h" #include "vtkCubeSource.h" #include "vtkFloatArray.h" #include "vtkForceDirectedLayoutStrategy.h" #include "vtkGlyph3D.h" #include "vtkGraph.h" #include "vtkGraphLayout.h" #include "vtkGraphToPolyData.h" #include "vtkIdTypeArray.h" #include "vtkInteractorStyleRubberBandPick.h" #include "vtkKdNode.h" #include "vtkKdTree.h" #include "vtkLookupTable.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRandomGraphSource.h" #include "vtkSimple2DLayoutStrategy.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include "vtkTree.h" #include "vtkTreeLevelsFilter.h" #include "vtkTreeMapToPolyData.h" #define VTK_CREATE(type,name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() // // Make a vtkTree from a kd-tree // void BuildTree(vtkIdType parent, vtkKdNode* parentVertex, vtkTree* tree, vtkFloatArray* rectArray) { double bounds[6]; parentVertex->GetBounds(bounds); rectArray->InsertTuple(parent, bounds); if (parentVertex->GetLeft() != NULL) { vtkIdType curIndex = tree->AddChild(parent); BuildTree(curIndex, parentVertex->GetLeft(), tree, rectArray); curIndex = tree->AddChild(parent); BuildTree(curIndex, parentVertex->GetRight(), tree, rectArray); } } int TestKdTreeBoxSelection(int argc, char *argv[]) { bool interactive = false; bool threedim = false; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-I")) { interactive = true; continue; } if (!strcmp(argv[i], "-d")) { threedim = true; continue; } cerr << argv[0] << " options:\n" << " -I run interactively\n" << " -d three-dimensional\n"; return 0; } // // Create a random graph and perform layout // VTK_CREATE(vtkRandomGraphSource, source); source->SetStartWithTree(true); source->SetNumberOfVertices(100); source->SetNumberOfEdges(15); VTK_CREATE(vtkGraphLayout, layout); layout->SetInputConnection(source->GetOutputPort()); if (threedim) { VTK_CREATE(vtkForceDirectedLayoutStrategy, forceLayout); forceLayout->SetGraphBounds(-3, 3, -3, 3, -3, 3); layout->SetLayoutStrategy(forceLayout); } else { VTK_CREATE(vtkSimple2DLayoutStrategy, simpleLayout); simpleLayout->SetJitter(true); layout->SetLayoutStrategy(simpleLayout); } layout->Update(); vtkGraph* g = vtkGraph::SafeDownCast(layout->GetOutput()); // // Create the kd-tree // VTK_CREATE(vtkKdTree, kdTree); kdTree->OmitZPartitioning(); kdTree->SetMinCells(1); kdTree->BuildLocatorFromPoints(g->GetPoints()); // // Perform an area selection // VTK_CREATE(vtkIdTypeArray, selection); double bounds[6] = {-2, 2, -0.5, 3, -1, 1}; //{-1, 1, -1, 1, -1, 1}; kdTree->FindPointsInArea(bounds, selection); // // Create selected vertex glyphs // double glyphSize = 0.05; VTK_CREATE(vtkPolyData, selectPoly); VTK_CREATE(vtkPoints, selectPoints); double pt[3]; for (vtkIdType i = 0; i < selection->GetNumberOfTuples(); i++) { g->GetPoint(selection->GetValue(i), pt); selectPoints->InsertNextPoint(pt); } selectPoly->SetPoints(selectPoints); VTK_CREATE(vtkSphereSource, selectSphere); selectSphere->SetRadius(1.1*glyphSize); VTK_CREATE(vtkGlyph3D, selectGlyph); selectGlyph->SetInput(0, selectPoly); selectGlyph->SetInputConnection(1, selectSphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, selectMapper); selectMapper->SetInputConnection(selectGlyph->GetOutputPort()); VTK_CREATE(vtkActor, selectActor); selectActor->SetMapper(selectMapper); selectActor->GetProperty()->SetColor(1.0, 0.0, 0.0); // // Create selection box actor // VTK_CREATE(vtkCubeSource, cubeSource); cubeSource->SetBounds(bounds); VTK_CREATE(vtkPolyDataMapper, cubeMapper); cubeMapper->SetInputConnection(cubeSource->GetOutputPort()); VTK_CREATE(vtkActor, cubeActor); cubeActor->SetMapper(cubeMapper); cubeActor->GetProperty()->SetColor(0.0, 0.0, 1.0); cubeActor->GetProperty()->SetOpacity(0.5); // // Create kd-tree actor // VTK_CREATE(vtkTree, tree); VTK_CREATE(vtkFloatArray, rectArray); rectArray->SetName("rectangles"); rectArray->SetNumberOfComponents(4); tree->GetPointData()->AddArray(rectArray); vtkKdNode* top = kdTree->GetCuts()->GetKdNodeTree(); BuildTree(tree->AddRoot(), top, tree, rectArray); VTK_CREATE(vtkTreeLevelsFilter, treeLevels); treeLevels->SetInput(tree); VTK_CREATE(vtkTreeMapToPolyData, treePoly); treePoly->SetInputConnection(treeLevels->GetOutputPort()); VTK_CREATE(vtkLookupTable, lut); VTK_CREATE(vtkPolyDataMapper, treeMapper); treeMapper->SetInputConnection(treePoly->GetOutputPort()); treeMapper->SetScalarRange(0, 10); treeMapper->SetLookupTable(lut); VTK_CREATE(vtkActor, treeActor); treeActor->SetMapper(treeMapper); //treeActor->GetProperty()->SetRepresentationToWireframe(); //treeActor->GetProperty()->SetOpacity(0.2); // // Create graph actor // VTK_CREATE(vtkGraphToPolyData, graphToPoly); graphToPoly->SetInput(g); VTK_CREATE(vtkTransform, transform); if (threedim) { transform->Translate(0, 0, 0); } else { transform->Translate(0, 0, glyphSize); } VTK_CREATE(vtkTransformFilter, transFilter); transFilter->SetInputConnection(graphToPoly->GetOutputPort()); transFilter->SetTransform(transform); VTK_CREATE(vtkPolyDataMapper, graphMapper); graphMapper->SetInputConnection(transFilter->GetOutputPort()); VTK_CREATE(vtkActor, graphActor); graphActor->SetMapper(graphMapper); // // Create vertex glyphs // VTK_CREATE(vtkSphereSource, sphere); sphere->SetRadius(glyphSize); VTK_CREATE(vtkGlyph3D, glyph); glyph->SetInputConnection(0, graphToPoly->GetOutputPort()); glyph->SetInputConnection(1, sphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, glyphMapper); glyphMapper->SetInputConnection(glyph->GetOutputPort()); VTK_CREATE(vtkActor, glyphActor); glyphActor->SetMapper(glyphMapper); // // Set up render window // VTK_CREATE(vtkRenderer, ren); if (!threedim) { ren->AddActor(treeActor); } ren->AddActor(graphActor); ren->AddActor(glyphActor); ren->AddActor(cubeActor); ren->AddActor(selectActor); VTK_CREATE(vtkRenderWindow, win); win->AddRenderer(ren); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(win); VTK_CREATE(vtkAreaPicker, picker); iren->SetPicker(picker); VTK_CREATE(vtkInteractorStyleRubberBandPick, interact); iren->SetInteractorStyle(interact); if (interactive) { iren->Initialize(); iren->Start(); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Linguist of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "translator.h" #include <QtCore/QByteArray> #include <QtCore/QDebug> #include <QtCore/QTextCodec> #include <QtCore/QTextStream> #include <QtXml/QXmlStreamReader> #include <QtXml/QXmlStreamAttribute> QT_BEGIN_NAMESPACE class QPHReader : public QXmlStreamReader { public: QPHReader(QIODevice &dev) : QXmlStreamReader(&dev) {} // the "real thing" bool read(Translator &translator); private: bool isWhiteSpace() const { return isCharacters() && text().toString().trimmed().isEmpty(); } enum DataField { NoField, SourceField, TargetField, DefinitionField }; DataField m_currentField; QString m_currentSource; QString m_currentTarget; QString m_currentDefinition; }; bool QPHReader::read(Translator &translator) { m_currentField = NoField; QString result; while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("source")) m_currentField = SourceField; else if (name() == QLatin1String("target")) m_currentField = TargetField; else if (name() == QLatin1String("definition")) m_currentField = DefinitionField; else m_currentField = NoField; } else if (isWhiteSpace()) { // ignore these } else if (isCharacters()) { if (m_currentField == SourceField) m_currentSource += text(); else if (m_currentField == TargetField) m_currentTarget += text(); else if (m_currentField == DefinitionField) m_currentDefinition += text(); } else if (isEndElement() && name() == QLatin1String("phrase")) { m_currentTarget.replace(QChar(Translator::TextVariantSeparator), QChar(Translator::BinaryVariantSeparator)); TranslatorMessage msg; msg.setSourceText(m_currentSource); msg.setTranslation(m_currentTarget); msg.setComment(m_currentDefinition); translator.append(msg); m_currentSource.clear(); m_currentTarget.clear(); m_currentDefinition.clear(); } } return true; } static bool loadQPH(Translator &translator, QIODevice &dev, ConversionData &) { translator.setLocationsType(Translator::NoLocations); QPHReader reader(dev); return reader.read(translator); } static QString protect(const QString &str) { QString result; result.reserve(str.length() * 12 / 10); for (int i = 0; i != str.size(); ++i) { uint c = str.at(i).unicode(); switch (c) { case '\"': result += QLatin1String("&quot;"); break; case '&': result += QLatin1String("&amp;"); break; case '>': result += QLatin1String("&gt;"); break; case '<': result += QLatin1String("&lt;"); break; case '\'': result += QLatin1String("&apos;"); break; default: if (c < 0x20 && c != '\r' && c != '\n' && c != '\t') result += QString(QLatin1String("&#%1;")).arg(c); else // this also covers surrogates result += QChar(c); } } return result; } static bool saveQPH(const Translator &translator, QIODevice &dev, ConversionData &) { QTextStream t(&dev); t.setCodec(QTextCodec::codecForName("UTF-8")); t << "<!DOCTYPE QPH>\n<QPH>\n"; foreach (const TranslatorMessage &msg, translator.messages()) { t << "<phrase>\n"; t << " <source>" << protect(msg.sourceText()) << "</source>\n"; QString str = msg.translations().join(QLatin1String("@")); str.replace(QChar(Translator::BinaryVariantSeparator), QChar(Translator::TextVariantSeparator)); t << " <target>" << protect(str) << "</target>\n"; if (!msg.comment().isEmpty()) t << " <definition>" << msg.comment() << "</definition>\n"; t << "</phrase>\n"; } t << "</QPH>\n"; return true; } int initQPH() { Translator::FileFormat format; format.extension = QLatin1String("qph"); format.description = QObject::tr("Qt Linguist 'Phrase Book'"); format.fileType = Translator::FileFormat::TranslationSource; format.priority = 0; format.loader = &loadQPH; format.saver = &saveQPH; Translator::registerFileFormat(format); return 1; } Q_CONSTRUCTOR_FUNCTION(initQPH) QT_END_NAMESPACE <commit_msg>the definition needs xml escaping, too<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Linguist of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "translator.h" #include <QtCore/QByteArray> #include <QtCore/QDebug> #include <QtCore/QTextCodec> #include <QtCore/QTextStream> #include <QtXml/QXmlStreamReader> #include <QtXml/QXmlStreamAttribute> QT_BEGIN_NAMESPACE class QPHReader : public QXmlStreamReader { public: QPHReader(QIODevice &dev) : QXmlStreamReader(&dev) {} // the "real thing" bool read(Translator &translator); private: bool isWhiteSpace() const { return isCharacters() && text().toString().trimmed().isEmpty(); } enum DataField { NoField, SourceField, TargetField, DefinitionField }; DataField m_currentField; QString m_currentSource; QString m_currentTarget; QString m_currentDefinition; }; bool QPHReader::read(Translator &translator) { m_currentField = NoField; QString result; while (!atEnd()) { readNext(); if (isStartElement()) { if (name() == QLatin1String("source")) m_currentField = SourceField; else if (name() == QLatin1String("target")) m_currentField = TargetField; else if (name() == QLatin1String("definition")) m_currentField = DefinitionField; else m_currentField = NoField; } else if (isWhiteSpace()) { // ignore these } else if (isCharacters()) { if (m_currentField == SourceField) m_currentSource += text(); else if (m_currentField == TargetField) m_currentTarget += text(); else if (m_currentField == DefinitionField) m_currentDefinition += text(); } else if (isEndElement() && name() == QLatin1String("phrase")) { m_currentTarget.replace(QChar(Translator::TextVariantSeparator), QChar(Translator::BinaryVariantSeparator)); TranslatorMessage msg; msg.setSourceText(m_currentSource); msg.setTranslation(m_currentTarget); msg.setComment(m_currentDefinition); translator.append(msg); m_currentSource.clear(); m_currentTarget.clear(); m_currentDefinition.clear(); } } return true; } static bool loadQPH(Translator &translator, QIODevice &dev, ConversionData &) { translator.setLocationsType(Translator::NoLocations); QPHReader reader(dev); return reader.read(translator); } static QString protect(const QString &str) { QString result; result.reserve(str.length() * 12 / 10); for (int i = 0; i != str.size(); ++i) { uint c = str.at(i).unicode(); switch (c) { case '\"': result += QLatin1String("&quot;"); break; case '&': result += QLatin1String("&amp;"); break; case '>': result += QLatin1String("&gt;"); break; case '<': result += QLatin1String("&lt;"); break; case '\'': result += QLatin1String("&apos;"); break; default: if (c < 0x20 && c != '\r' && c != '\n' && c != '\t') result += QString(QLatin1String("&#%1;")).arg(c); else // this also covers surrogates result += QChar(c); } } return result; } static bool saveQPH(const Translator &translator, QIODevice &dev, ConversionData &) { QTextStream t(&dev); t.setCodec(QTextCodec::codecForName("UTF-8")); t << "<!DOCTYPE QPH>\n<QPH>\n"; foreach (const TranslatorMessage &msg, translator.messages()) { t << "<phrase>\n"; t << " <source>" << protect(msg.sourceText()) << "</source>\n"; QString str = msg.translations().join(QLatin1String("@")); str.replace(QChar(Translator::BinaryVariantSeparator), QChar(Translator::TextVariantSeparator)); t << " <target>" << protect(str) << "</target>\n"; if (!msg.comment().isEmpty()) t << " <definition>" << protect(msg.comment()) << "</definition>\n"; t << "</phrase>\n"; } t << "</QPH>\n"; return true; } int initQPH() { Translator::FileFormat format; format.extension = QLatin1String("qph"); format.description = QObject::tr("Qt Linguist 'Phrase Book'"); format.fileType = Translator::FileFormat::TranslationSource; format.priority = 0; format.loader = &loadQPH; format.saver = &saveQPH; Translator::registerFileFormat(format); return 1; } Q_CONSTRUCTOR_FUNCTION(initQPH) QT_END_NAMESPACE <|endoftext|>
<commit_before>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "llvm/InstrTypes.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/System/Signals.h" #include <algorithm> #include <iostream> #include <iomanip> #include <map> #include <set> using namespace llvm; namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); cl::opt<bool> PrintAllCode("print-all-code", cl::desc("Print annotated code for the entire program")); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF, std::map<ProfileInfoLoader::Edge, unsigned> &EF) : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << "\t;;; Basic block executed " << Count << " times.\n"; else OS << "\t;;; Never executed!\n"; } virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, std::ostream &OS){ if (EdgeFreqs.empty()) return; // Figure out how many times each successor executed. std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts; const TerminatorInst *TI = BB->getTerminator(); std::map<ProfileInfoLoader::Edge, unsigned>::iterator I = EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U)); for (; I != EdgeFreqs.end() && I->first.first == BB; ++I) if (I->second) SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second), I->second)); if (!SuccCounts.empty()) { OS << "\t;;; Out-edge counts:"; for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i) OS << " [" << SuccCounts[i].second << " -> " << SuccCounts[i].first->getName() << "]"; OS << "\n"; } } }; } int main(int argc, char **argv) { llvm_shutdown_obj X; // Call llvm_shutdown() on exit. try { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); sys::PrintStackTraceOnErrorSignal(); // Read in the bytecode file... std::string ErrorMessage; Module *M; if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BytecodeFile, &ErrorMessage)) { M = ParseBitcodeFile(Buffer, &ErrorMessage); delete Buffer; } if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfoLoader PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); uint64_t TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... std::cout << " ## Frequency\n"; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { std::cout << "\n NOTE: " << e-i << " function" << (e-i-1 ? "s were" : " was") << " never executed!\n"; break; } std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << FunctionCounts[i].second << "/" << TotalExecutions << " " << FunctionCounts[i].first->getName().c_str() << "\n"; } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... std::cout <<" ## %% \tFrequency\n"; unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { if (Counts[i].second == 0) break; Function *F = Counts[i].first->getParent(); std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << std::setprecision(2) << Counts[i].second/(double)TotalExecutions*100 << "% " << std::setw(5) << Counts[i].second << "/" << TotalExecutions << "\t" << F->getName().c_str() << "() - " << Counts[i].first->getName().c_str() << "\n"; FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PI.hasAccurateEdgeCounts()) { std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts; PI.getEdgeCounts(Counts); EdgeFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM || PrintAllCode) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs); if (FunctionsToPrint.empty() || PrintAllCode) M->print(std::cout, &PA); else // Print just a subset of the functions... for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } return 1; } <commit_msg>Initialize variable to null so it has a value in the off chance that a memory buffer couldn't be allocated.<commit_after>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "llvm/InstrTypes.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/System/Signals.h" #include <algorithm> #include <iostream> #include <iomanip> #include <map> #include <set> using namespace llvm; namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); cl::opt<bool> PrintAllCode("print-all-code", cl::desc("Print annotated code for the entire program")); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF, std::map<ProfileInfoLoader::Edge, unsigned> &EF) : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << "\t;;; Basic block executed " << Count << " times.\n"; else OS << "\t;;; Never executed!\n"; } virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, std::ostream &OS){ if (EdgeFreqs.empty()) return; // Figure out how many times each successor executed. std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts; const TerminatorInst *TI = BB->getTerminator(); std::map<ProfileInfoLoader::Edge, unsigned>::iterator I = EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U)); for (; I != EdgeFreqs.end() && I->first.first == BB; ++I) if (I->second) SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second), I->second)); if (!SuccCounts.empty()) { OS << "\t;;; Out-edge counts:"; for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i) OS << " [" << SuccCounts[i].second << " -> " << SuccCounts[i].first->getName() << "]"; OS << "\n"; } } }; } int main(int argc, char **argv) { llvm_shutdown_obj X; // Call llvm_shutdown() on exit. try { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); sys::PrintStackTraceOnErrorSignal(); // Read in the bytecode file... std::string ErrorMessage; Module *M = 0; if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BytecodeFile, &ErrorMessage)) { M = ParseBitcodeFile(Buffer, &ErrorMessage); delete Buffer; } if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfoLoader PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); uint64_t TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... std::cout << " ## Frequency\n"; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { std::cout << "\n NOTE: " << e-i << " function" << (e-i-1 ? "s were" : " was") << " never executed!\n"; break; } std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << FunctionCounts[i].second << "/" << TotalExecutions << " " << FunctionCounts[i].first->getName().c_str() << "\n"; } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... std::cout <<" ## %% \tFrequency\n"; unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { if (Counts[i].second == 0) break; Function *F = Counts[i].first->getParent(); std::cout << std::setw(3) << i+1 << ". " << std::setw(5) << std::setprecision(2) << Counts[i].second/(double)TotalExecutions*100 << "% " << std::setw(5) << Counts[i].second << "/" << TotalExecutions << "\t" << F->getName().c_str() << "() - " << Counts[i].first->getName().c_str() << "\n"; FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PI.hasAccurateEdgeCounts()) { std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts; PI.getEdgeCounts(Counts); EdgeFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM || PrintAllCode) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs); if (FunctionsToPrint.empty() || PrintAllCode) M->print(std::cout, &PA); else // Print just a subset of the functions... for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } return 1; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthIce40Pass : public ScriptPass { SynthIce40Pass() : ScriptPass("synth_ice40", "synthesis for iCE40 FPGAs") { } virtual void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_ice40 [options]\n"); log("\n"); log("This command runs synthesis for iCE40 FPGAs.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -noflatten\n"); log(" do not flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -nocarry\n"); log(" do not use SB_CARRY cells in output netlist\n"); log("\n"); log(" -nobram\n"); log(" do not use SB_RAM40_4K* cells in output netlist\n"); log("\n"); log(" -abc2\n"); log(" run two passes of 'abc' for slightly improved logic density\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } string top_opt, blif_file, edif_file; bool nocarry, nobram, flatten, retime, abc2, vpr; virtual void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; blif_file = ""; edif_file = ""; nocarry = false; nobram = false; flatten = true; retime = false; abc2 = false; vpr = false; } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-noflatten") { flatten = false; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-abc2") { abc2 = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } break; } extra_args(args, argidx, design); if (!design->full_selection()) log_cmd_error("This comannd only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_ICE40 pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } virtual void script() YS_OVERRIDE { if (check_label("begin")) { run("read_verilog -lib +/ice40/cells_sim.v"); run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str())); } if (flatten && check_label("flatten", "(unless -noflatten)")) { run("proc"); run("flatten"); run("tribuf -logic"); run("deminout"); } if (check_label("coarse")) { run("synth -run coarse"); } if (!nobram && check_label("bram", "(skip if -nobram)")) { run("memory_bram -rules +/ice40/brams.txt"); run("techmap -map +/ice40/brams_map.v"); } if (check_label("fine")) { run("opt -fast -mux_undef -undriven -fine"); run("memory_map"); run("opt -undriven -fine"); if (nocarry) run("techmap"); else run("techmap -map +/techmap.v -map +/ice40/arith_map.v"); if (retime || help_mode) run("abc -dff", "(only if -retime)"); run("ice40_opt"); } if (check_label("map_ffs")) { run("dffsr2dff"); run("dff2dffe -direct-match $_DFF_*"); run("techmap -D NO_SB_LUT4 -map +/ice40/cells_map.v"); run("opt_expr -mux_undef"); run("simplemap"); run("ice40_ffinit"); run("ice40_ffssr"); run("ice40_opt -full"); } if (check_label("map_luts")) { if (abc2 || help_mode) { run("abc", " (only if -abc2)"); run("ice40_opt", "(only if -abc2)"); } run("techmap -map +/ice40/latches_map.v"); run("abc -lut 4"); run("clean"); } if (check_label("map_cells")) { if (vpr) run("techmap -D NO_SB_LUT4 -map +/ice40/cells_map.v"); else run("techmap -map +/ice40/cells_map.v", "(with -D NO_SB_LUT4 in vpr mode)"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat"); run("check -noinit"); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) { if (vpr || help_mode) { run(stringf("opt_clean -purge"), " (vpr mode)"); run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()), " (vpr mode)"); } if (!vpr) run(stringf("write_blif -gates -attr -param %s", help_mode ? "<file-name>" : blif_file.c_str()), "(non-vpr mode)"); } } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif %s", help_mode ? "<file-name>" : edif_file.c_str())); } } } SynthIce40Pass; PRIVATE_NAMESPACE_END <commit_msg>Add "synth_ice40 -nodffe"<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthIce40Pass : public ScriptPass { SynthIce40Pass() : ScriptPass("synth_ice40", "synthesis for iCE40 FPGAs") { } virtual void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_ice40 [options]\n"); log("\n"); log("This command runs synthesis for iCE40 FPGAs.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -noflatten\n"); log(" do not flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -nocarry\n"); log(" do not use SB_CARRY cells in output netlist\n"); log("\n"); log(" -nodffe\n"); log(" do not use SB_DFFE* cells in output netlist\n"); log("\n"); log(" -nobram\n"); log(" do not use SB_RAM40_4K* cells in output netlist\n"); log("\n"); log(" -abc2\n"); log(" run two passes of 'abc' for slightly improved logic density\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } string top_opt, blif_file, edif_file; bool nocarry, nodffe, nobram, flatten, retime, abc2, vpr; virtual void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; blif_file = ""; edif_file = ""; nocarry = false; nodffe = false; nobram = false; flatten = true; retime = false; abc2 = false; vpr = false; } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-noflatten") { flatten = false; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nodffe") { nodffe = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-abc2") { abc2 = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } break; } extra_args(args, argidx, design); if (!design->full_selection()) log_cmd_error("This comannd only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_ICE40 pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } virtual void script() YS_OVERRIDE { if (check_label("begin")) { run("read_verilog -lib +/ice40/cells_sim.v"); run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str())); } if (flatten && check_label("flatten", "(unless -noflatten)")) { run("proc"); run("flatten"); run("tribuf -logic"); run("deminout"); } if (check_label("coarse")) { run("synth -run coarse"); } if (!nobram && check_label("bram", "(skip if -nobram)")) { run("memory_bram -rules +/ice40/brams.txt"); run("techmap -map +/ice40/brams_map.v"); } if (check_label("fine")) { run("opt -fast -mux_undef -undriven -fine"); run("memory_map"); run("opt -undriven -fine"); if (nocarry) run("techmap"); else run("techmap -map +/techmap.v -map +/ice40/arith_map.v"); if (retime || help_mode) run("abc -dff", "(only if -retime)"); run("ice40_opt"); } if (check_label("map_ffs")) { run("dffsr2dff"); if (!nodffe) run("dff2dffe -direct-match $_DFF_*"); run("techmap -D NO_SB_LUT4 -map +/ice40/cells_map.v"); run("opt_expr -mux_undef"); run("simplemap"); run("ice40_ffinit"); run("ice40_ffssr"); run("ice40_opt -full"); } if (check_label("map_luts")) { if (abc2 || help_mode) { run("abc", " (only if -abc2)"); run("ice40_opt", "(only if -abc2)"); } run("techmap -map +/ice40/latches_map.v"); run("abc -lut 4"); run("clean"); } if (check_label("map_cells")) { if (vpr) run("techmap -D NO_SB_LUT4 -map +/ice40/cells_map.v"); else run("techmap -map +/ice40/cells_map.v", "(with -D NO_SB_LUT4 in vpr mode)"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat"); run("check -noinit"); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) { if (vpr || help_mode) { run(stringf("opt_clean -purge"), " (vpr mode)"); run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()), " (vpr mode)"); } if (!vpr) run(stringf("write_blif -gates -attr -param %s", help_mode ? "<file-name>" : blif_file.c_str()), "(non-vpr mode)"); } } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif %s", help_mode ? "<file-name>" : edif_file.c_str())); } } } SynthIce40Pass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>#include "physics/forkable.hpp" #include "geometry/named_quantities.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" namespace principia { using geometry::Instant; using si::Second; using ::testing::ElementsAre; namespace physics { class FakeTrajectory : public Forkable<FakeTrajectory, std::list<Instant>::const_iterator> { public: FakeTrajectory(); void push_back(Instant const& time); protected: not_null<FakeTrajectory*> that() override; not_null<FakeTrajectory const*> that() const override; TimelineConstIterator timeline_begin() const override; TimelineConstIterator timeline_end() const override; TimelineConstIterator timeline_find(Instant const& time) const override; void timeline_insert(TimelineConstIterator begin, TimelineConstIterator end) override; bool timeline_empty() const override; private: // Use list<> because we want the iterators to remain valid across operations. std::list<Instant> timeline_; template<typename Tr4jectory, typename TimelineConstIterator_> friend class Forkable; template<typename Tr4jectory, typename TimelineConstIterator_> friend class Forkable<Tr4jectory, TimelineConstIterator_>::Iterator; }; FakeTrajectory::FakeTrajectory() : Forkable<FakeTrajectory, std::list<Instant>::const_iterator>() {} void FakeTrajectory::push_back(Instant const& time) { timeline_.push_back(time); } not_null<FakeTrajectory*> FakeTrajectory::that() { return this; } not_null<FakeTrajectory const*> FakeTrajectory::that() const { return this; } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_begin() const { return timeline_.begin(); } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_end() const { return timeline_.end(); } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_find( Instant const & time) const { // Stupid O(N) search. for (auto it = timeline_.begin(); it != timeline_.end(); ++it) { if (*it == time) { return it; } } return timeline_.end(); } void FakeTrajectory::timeline_insert(TimelineConstIterator begin, TimelineConstIterator end) { CHECK(timeline_empty()); timeline_.insert(timeline_.end(), begin, end); } bool FakeTrajectory::timeline_empty() const { return timeline_.empty(); } class ForkableTest : public testing::Test { protected: ForkableTest() : t0_(), t1_(t0_ + 7 * Second), t2_(t0_ + 17 * Second), t3_(t0_ + 27 * Second), t4_(t0_ + 37 * Second) {} static std::vector<Instant> After( not_null<FakeTrajectory const*> const trajectory, Instant const& time) { std::vector<Instant> after; for (FakeTrajectory::Iterator it = trajectory->Find(time); it != trajectory->End(); ++it) { after.push_back(*it.current()); } return after; } static Instant const& LastTime( not_null<FakeTrajectory const*> const trajectory) { FakeTrajectory::Iterator it = trajectory->End(); --it; return *it.current(); } static std::vector<Instant> Times( not_null<FakeTrajectory const*> const trajectory) { std::vector<Instant> times; for (FakeTrajectory::Iterator it = trajectory->Begin(); it != trajectory->End(); ++it) { times.push_back(*it.current()); } return times; } FakeTrajectory trajectory_; Instant t0_, t1_, t2_, t3_, t4_; }; using ForkableDeathTest = ForkableTest; TEST_F(ForkableDeathTest, ForkError) { EXPECT_DEATH({ trajectory_.push_back(t1_); trajectory_.push_back(t3_); trajectory_.NewFork(t2_); }, "nonexistent time"); } TEST_F(ForkableDeathTest, ForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); auto times = Times(&trajectory_); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); times = Times(fork); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_)); } TEST_F(ForkableTest, ForkAtLast) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t3_); not_null<FakeTrajectory*> const fork2 = fork1->NewFork(LastTime(fork1)); not_null<FakeTrajectory*> const fork3 = fork2->NewFork(LastTime(fork1)); EXPECT_EQ(t3_, LastTime(&trajectory_)); EXPECT_EQ(t3_, LastTime(fork1)); auto times = Times(fork2); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); EXPECT_EQ(t3_, LastTime(fork2)); EXPECT_EQ(t3_, *fork2->ForkTime()); auto after = After(fork3, t3_); EXPECT_THAT(after, ElementsAre(t3_)); after = After(fork2, t3_); EXPECT_THAT(after, ElementsAre(t3_)); fork1->push_back(t4_); times = Times(fork2); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); after = After(fork1, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); times = Times(fork3); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); fork2->push_back(t4_); after = After(fork2, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); fork3->push_back(t4_); after = After(fork3, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); after = After(fork3, t2_); EXPECT_THAT(after, ElementsAre(t2_, t3_, t4_)); } TEST_F(ForkableDeathTest, DeleteForkError) { EXPECT_DEATH({ trajectory_.push_back(t1_); FakeTrajectory* root = &trajectory_; trajectory_.DeleteFork(&root); }, "'fork_time'.* non NULL"); EXPECT_DEATH({ trajectory_.push_back(t1_); FakeTrajectory* fork1 = trajectory_.NewFork(t1_); fork1->push_back(t2_); FakeTrajectory* fork2 = fork1->NewFork(t2_); trajectory_.DeleteFork(&fork2); }, "not a child"); } TEST_F(ForkableTest, DeleteForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t2_); FakeTrajectory* fork2 = trajectory_.NewFork(t2_); fork1->push_back(t4_); trajectory_.DeleteFork(&fork2); EXPECT_EQ(nullptr, fork2); auto times = Times(&trajectory_); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); times = Times(fork1); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_)); } TEST_F(ForkableDeathTest, IteratorDecrementError) { EXPECT_DEATH({ auto it = trajectory_.End(); --it; }, "parent_.*non NULL"); } TEST_F(ForkableTest, IteratorDecrementNoForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); auto it = trajectory_.End(); --it; EXPECT_EQ(t3_, *it.current()); --it; EXPECT_EQ(t2_, *it.current()); --it; EXPECT_EQ(t1_, *it.current()); } TEST_F(ForkableTest, IteratorDecrementForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); auto fork = trajectory_.NewFork(t1_); trajectory_.push_back(t4_); fork->push_back(t3_); auto it = fork->End(); --it; EXPECT_EQ(t3_, *it.current()); --it; EXPECT_EQ(t2_, *it.current()); --it; EXPECT_EQ(t1_, *it.current()); } TEST_F(ForkableTest, Root) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); EXPECT_TRUE(trajectory_.is_root()); EXPECT_FALSE(fork->is_root()); EXPECT_EQ(&trajectory_, trajectory_.root()); EXPECT_EQ(&trajectory_, fork->root()); EXPECT_EQ(nullptr, trajectory_.ForkTime()); EXPECT_EQ(t2_, *fork->ForkTime()); } TEST_F(ForkableTest, IteratorBeginSuccess) { auto it = trajectory_.Begin(); EXPECT_EQ(it, trajectory_.End()); trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); it = trajectory_.Begin(); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); ++it; EXPECT_EQ(it, trajectory_.End()); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); it = fork->Begin(); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); ++it; EXPECT_EQ(t4_, *it.current()); ++it; EXPECT_EQ(it, trajectory_.End()); } TEST_F(ForkableTest, IteratorFindSuccess) { auto it = trajectory_.Find(t0_); EXPECT_EQ(it, trajectory_.End()); trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); it = trajectory_.Find(t1_); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); it = trajectory_.Find(t2_); EXPECT_EQ(t2_, *it.current()); it = trajectory_.Find(t4_); EXPECT_EQ(it, trajectory_.End()); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); it = fork->Find(t1_); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); it = fork->Find(t2_); EXPECT_EQ(t2_, *it.current()); it = fork->Find(t4_); EXPECT_EQ(t4_, *it.current()); it = fork->Find(t4_ + 1 * Second); EXPECT_EQ(it, trajectory_.End()); } } // namespace physics } // namespace principia <commit_msg>Increment tests.<commit_after>#include "physics/forkable.hpp" #include "geometry/named_quantities.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" namespace principia { using geometry::Instant; using si::Second; using ::testing::ElementsAre; namespace physics { class FakeTrajectory : public Forkable<FakeTrajectory, std::list<Instant>::const_iterator> { public: FakeTrajectory(); void push_back(Instant const& time); protected: not_null<FakeTrajectory*> that() override; not_null<FakeTrajectory const*> that() const override; TimelineConstIterator timeline_begin() const override; TimelineConstIterator timeline_end() const override; TimelineConstIterator timeline_find(Instant const& time) const override; void timeline_insert(TimelineConstIterator begin, TimelineConstIterator end) override; bool timeline_empty() const override; private: // Use list<> because we want the iterators to remain valid across operations. std::list<Instant> timeline_; template<typename Tr4jectory, typename TimelineConstIterator_> friend class Forkable; template<typename Tr4jectory, typename TimelineConstIterator_> friend class Forkable<Tr4jectory, TimelineConstIterator_>::Iterator; }; FakeTrajectory::FakeTrajectory() : Forkable<FakeTrajectory, std::list<Instant>::const_iterator>() {} void FakeTrajectory::push_back(Instant const& time) { timeline_.push_back(time); } not_null<FakeTrajectory*> FakeTrajectory::that() { return this; } not_null<FakeTrajectory const*> FakeTrajectory::that() const { return this; } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_begin() const { return timeline_.begin(); } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_end() const { return timeline_.end(); } FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_find( Instant const & time) const { // Stupid O(N) search. for (auto it = timeline_.begin(); it != timeline_.end(); ++it) { if (*it == time) { return it; } } return timeline_.end(); } void FakeTrajectory::timeline_insert(TimelineConstIterator begin, TimelineConstIterator end) { CHECK(timeline_empty()); timeline_.insert(timeline_.end(), begin, end); } bool FakeTrajectory::timeline_empty() const { return timeline_.empty(); } class ForkableTest : public testing::Test { protected: ForkableTest() : t0_(), t1_(t0_ + 7 * Second), t2_(t0_ + 17 * Second), t3_(t0_ + 27 * Second), t4_(t0_ + 37 * Second) {} static std::vector<Instant> After( not_null<FakeTrajectory const*> const trajectory, Instant const& time) { std::vector<Instant> after; for (FakeTrajectory::Iterator it = trajectory->Find(time); it != trajectory->End(); ++it) { after.push_back(*it.current()); } return after; } static Instant const& LastTime( not_null<FakeTrajectory const*> const trajectory) { FakeTrajectory::Iterator it = trajectory->End(); --it; return *it.current(); } static std::vector<Instant> Times( not_null<FakeTrajectory const*> const trajectory) { std::vector<Instant> times; for (FakeTrajectory::Iterator it = trajectory->Begin(); it != trajectory->End(); ++it) { times.push_back(*it.current()); } return times; } FakeTrajectory trajectory_; Instant t0_, t1_, t2_, t3_, t4_; }; using ForkableDeathTest = ForkableTest; TEST_F(ForkableDeathTest, ForkError) { EXPECT_DEATH({ trajectory_.push_back(t1_); trajectory_.push_back(t3_); trajectory_.NewFork(t2_); }, "nonexistent time"); } TEST_F(ForkableDeathTest, ForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); auto times = Times(&trajectory_); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); times = Times(fork); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_)); } TEST_F(ForkableTest, ForkAtLast) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t3_); not_null<FakeTrajectory*> const fork2 = fork1->NewFork(LastTime(fork1)); not_null<FakeTrajectory*> const fork3 = fork2->NewFork(LastTime(fork1)); EXPECT_EQ(t3_, LastTime(&trajectory_)); EXPECT_EQ(t3_, LastTime(fork1)); auto times = Times(fork2); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); EXPECT_EQ(t3_, LastTime(fork2)); EXPECT_EQ(t3_, *fork2->ForkTime()); auto after = After(fork3, t3_); EXPECT_THAT(after, ElementsAre(t3_)); after = After(fork2, t3_); EXPECT_THAT(after, ElementsAre(t3_)); fork1->push_back(t4_); times = Times(fork2); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); after = After(fork1, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); times = Times(fork3); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); fork2->push_back(t4_); after = After(fork2, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); fork3->push_back(t4_); after = After(fork3, t3_); EXPECT_THAT(after, ElementsAre(t3_, t4_)); after = After(fork3, t2_); EXPECT_THAT(after, ElementsAre(t2_, t3_, t4_)); } TEST_F(ForkableDeathTest, DeleteForkError) { EXPECT_DEATH({ trajectory_.push_back(t1_); FakeTrajectory* root = &trajectory_; trajectory_.DeleteFork(&root); }, "'fork_time'.* non NULL"); EXPECT_DEATH({ trajectory_.push_back(t1_); FakeTrajectory* fork1 = trajectory_.NewFork(t1_); fork1->push_back(t2_); FakeTrajectory* fork2 = fork1->NewFork(t2_); trajectory_.DeleteFork(&fork2); }, "not a child"); } TEST_F(ForkableTest, DeleteForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t2_); FakeTrajectory* fork2 = trajectory_.NewFork(t2_); fork1->push_back(t4_); trajectory_.DeleteFork(&fork2); EXPECT_EQ(nullptr, fork2); auto times = Times(&trajectory_); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_)); times = Times(fork1); EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_)); } TEST_F(ForkableDeathTest, IteratorDecrementError) { EXPECT_DEATH({ auto it = trajectory_.End(); --it; }, "parent_.*non NULL"); } TEST_F(ForkableTest, IteratorDecrementNoForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); auto it = trajectory_.End(); --it; EXPECT_EQ(t3_, *it.current()); --it; EXPECT_EQ(t2_, *it.current()); --it; EXPECT_EQ(t1_, *it.current()); } TEST_F(ForkableTest, IteratorDecrementForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); auto fork = trajectory_.NewFork(t1_); trajectory_.push_back(t4_); fork->push_back(t3_); auto it = fork->End(); --it; EXPECT_EQ(t3_, *it.current()); --it; EXPECT_EQ(t2_, *it.current()); --it; EXPECT_EQ(t1_, *it.current()); } TEST_F(ForkableDeathTest, IteratorIncrementError) { EXPECT_DEATH({ auto it = trajectory_.Begin(); ++it; }, "!at_end"); } TEST_F(ForkableTest, IteratorIncrementNoForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); auto it = trajectory_.Begin(); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); } TEST_F(ForkableTest, IteratorIncrementForkSuccess) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); auto fork = trajectory_.NewFork(t1_); trajectory_.push_back(t4_); fork->push_back(t3_); auto it = fork->Begin(); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); } TEST_F(ForkableTest, Root) { trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); EXPECT_TRUE(trajectory_.is_root()); EXPECT_FALSE(fork->is_root()); EXPECT_EQ(&trajectory_, trajectory_.root()); EXPECT_EQ(&trajectory_, fork->root()); EXPECT_EQ(nullptr, trajectory_.ForkTime()); EXPECT_EQ(t2_, *fork->ForkTime()); } TEST_F(ForkableTest, IteratorBeginSuccess) { auto it = trajectory_.Begin(); EXPECT_EQ(it, trajectory_.End()); trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); it = trajectory_.Begin(); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); ++it; EXPECT_EQ(it, trajectory_.End()); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); it = fork->Begin(); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); ++it; EXPECT_EQ(t2_, *it.current()); ++it; EXPECT_EQ(t3_, *it.current()); ++it; EXPECT_EQ(t4_, *it.current()); ++it; EXPECT_EQ(it, trajectory_.End()); } TEST_F(ForkableTest, IteratorFindSuccess) { auto it = trajectory_.Find(t0_); EXPECT_EQ(it, trajectory_.End()); trajectory_.push_back(t1_); trajectory_.push_back(t2_); trajectory_.push_back(t3_); it = trajectory_.Find(t1_); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); it = trajectory_.Find(t2_); EXPECT_EQ(t2_, *it.current()); it = trajectory_.Find(t4_); EXPECT_EQ(it, trajectory_.End()); not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_); fork->push_back(t4_); it = fork->Find(t1_); EXPECT_NE(it, trajectory_.End()); EXPECT_EQ(t1_, *it.current()); it = fork->Find(t2_); EXPECT_EQ(t2_, *it.current()); it = fork->Find(t4_); EXPECT_EQ(t4_, *it.current()); it = fork->Find(t4_ + 1 * Second); EXPECT_EQ(it, trajectory_.End()); } } // namespace physics } // namespace principia <|endoftext|>
<commit_before>/* * Copyright 2011, 2012 Esrille 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. */ // A test harness for the implementation report of // the CSS2.1 Conformance Test Suite // http://test.csswg.org/suites/css2.1/20110323/ #include <unistd.h> #include <sys/wait.h> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <boost/version.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> enum { INTERACTIVE, HEADLESS, REPORT, UPDATE }; int processOutput(std::istream& stream, std::string& result) { std::string output; bool completed = false; while (std::getline(stream, output)) { if (!completed) { if (output == "## complete") completed = true; continue; } if (output == "##") break; result += output + '\n'; } return 0; } int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result) { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; return -1; } if (pid == 0) { close(1); dup(pipefd[1]); close(pipefd[0]); int argi = argc - 1; if (!userStyle.empty()) argv[argi++] = strdup(userStyle.c_str()); if (testFonts == "on") argv[argi++] ="-testfonts"; url = "http://localhost:8000/" + url; // url = "http://test.csswg.org/suites/css2.1/20110323/" + url; argv[argi++] = strdup(url.c_str()); argv[argi] = 0; execvp(argv[0], argv); exit(EXIT_FAILURE); } close(pipefd[1]); #if 104400 <= BOOST_VERSION boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle); #else boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true); #endif processOutput(stream, result); return pid; } void killTest(int pid) { int status; kill(pid, SIGTERM); if (wait(&status) == -1) std::cerr << "error: failed to wait for a test process to complete\n"; } bool loadLog(const std::string& path, std::string& result, std::string& log) { std::ifstream file(path.c_str()); if (!file) { result = "?"; return false; } std::string line; std::getline(file, line); size_t pos = line.find('\t'); if (pos != std::string::npos) result = line.substr(pos + 1); else { result = "?"; return false; } log.clear(); while (std::getline(file, line)) log += line + '\n'; return true; } bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log) { std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc); if (!file) { std::cerr << "error: failed to open the report file\n"; return false; } file << "# " << url.c_str() << '\t' << result << '\n' << log; file.flush(); file.close(); return true; } int main(int argc, char* argv[]) { int mode = HEADLESS; int argi = 1; while (*argv[argi] == '-') { switch (argv[argi][1]) { case 'i': mode = INTERACTIVE; break; case 'r': mode = REPORT; break; case 'u': mode = UPDATE; break; default: break; } ++argi; } if (argc < argi + 2) { std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n"; return EXIT_FAILURE; } std::ifstream data(argv[argi]); if (!data) { std::cerr << "error: " << argv[argi] << ": no such file\n"; return EXIT_FAILURE; } std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc); if (!report) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } char* args[argc - argi + 3]; for (int i = 2; i < argc; ++i) args[i - 2] = argv[i + argi - 1]; args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0; std::string result; std::string url; std::string undo; std::string userStyle; std::string testFonts; bool redo = false; while (data) { if (result == "undo") { std::swap(url, undo); redo = true; } else if (redo) { std::swap(url, undo); redo = false; } else { std::string line; std::getline(data, line); if (line.empty() || line == "testname result comment") { report << line << '\n'; continue; } if (line[0] == '#') { if (line.compare(1, 9, "userstyle") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> userStyle; } else userStyle.clear(); } else if (line.compare(1, 9, "testfonts") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> testFonts; } else testFonts.clear(); } report << line << '\n'; continue; } undo = url; std::stringstream s(line, std::stringstream::in); s >> url; } if (url.empty()) continue; std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case REPORT: break; case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc - argi, args, userStyle, testFonts, url, output); break; } if (0 < pid && output.empty()) result = "fatal"; else if (mode == INTERACTIVE) { std::cout << "## complete\n" << output; std::cout << '[' << url << "] "; if (evaluation.empty() || evaluation[0] == '?') std::cout << "pass? "; else { std::cout << evaluation << "? "; if (evaluation != "pass") std::cout << '\a'; } std::getline(std::cin, result); if (result.empty()) { if (evaluation.empty() || evaluation[0] == '?') result = "pass"; else result = evaluation; } else if (result == "p" || result == "\x1b") result = "pass"; else if (result == "f") result = "fail"; else if (result == "i") result = "invalid"; else if (result == "k") // keep result = evaluation; else if (result == "n") result = "na"; else if (result == "s") result = "skip"; else if (result == "u") result = "uncertain"; else if (result == "q" || result == "quit") break; else if (result == "z") result = "undo"; if (result != "undo" && !saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } } else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; std::cout << url << '\t' << result << '\n'; } else if (mode == REPORT) { result = evaluation; std::cout << url << '\t' << result << '\n'; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } std::cout << url << '\t' << result << '\n'; } } if (0 < pid) killTest(pid); if (result != "undo") report << url << '\t' << result << '\n'; } report.close(); } <commit_msg>(harness) : Report 'fatal' to the standard output.<commit_after>/* * Copyright 2011, 2012 Esrille 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. */ // A test harness for the implementation report of // the CSS2.1 Conformance Test Suite // http://test.csswg.org/suites/css2.1/20110323/ #include <unistd.h> #include <sys/wait.h> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <boost/version.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> enum { INTERACTIVE, HEADLESS, REPORT, UPDATE }; int processOutput(std::istream& stream, std::string& result) { std::string output; bool completed = false; while (std::getline(stream, output)) { if (!completed) { if (output == "## complete") completed = true; continue; } if (output == "##") break; result += output + '\n'; } return 0; } int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result) { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; return -1; } if (pid == 0) { close(1); dup(pipefd[1]); close(pipefd[0]); int argi = argc - 1; if (!userStyle.empty()) argv[argi++] = strdup(userStyle.c_str()); if (testFonts == "on") argv[argi++] ="-testfonts"; url = "http://localhost:8000/" + url; // url = "http://test.csswg.org/suites/css2.1/20110323/" + url; argv[argi++] = strdup(url.c_str()); argv[argi] = 0; execvp(argv[0], argv); exit(EXIT_FAILURE); } close(pipefd[1]); #if 104400 <= BOOST_VERSION boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle); #else boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true); #endif processOutput(stream, result); return pid; } void killTest(int pid) { int status; kill(pid, SIGTERM); if (wait(&status) == -1) std::cerr << "error: failed to wait for a test process to complete\n"; } bool loadLog(const std::string& path, std::string& result, std::string& log) { std::ifstream file(path.c_str()); if (!file) { result = "?"; return false; } std::string line; std::getline(file, line); size_t pos = line.find('\t'); if (pos != std::string::npos) result = line.substr(pos + 1); else { result = "?"; return false; } log.clear(); while (std::getline(file, line)) log += line + '\n'; return true; } bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log) { std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc); if (!file) { std::cerr << "error: failed to open the report file\n"; return false; } file << "# " << url.c_str() << '\t' << result << '\n' << log; file.flush(); file.close(); return true; } int main(int argc, char* argv[]) { int mode = HEADLESS; int argi = 1; while (*argv[argi] == '-') { switch (argv[argi][1]) { case 'i': mode = INTERACTIVE; break; case 'r': mode = REPORT; break; case 'u': mode = UPDATE; break; default: break; } ++argi; } if (argc < argi + 2) { std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n"; return EXIT_FAILURE; } std::ifstream data(argv[argi]); if (!data) { std::cerr << "error: " << argv[argi] << ": no such file\n"; return EXIT_FAILURE; } std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc); if (!report) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } char* args[argc - argi + 3]; for (int i = 2; i < argc; ++i) args[i - 2] = argv[i + argi - 1]; args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0; std::string result; std::string url; std::string undo; std::string userStyle; std::string testFonts; bool redo = false; while (data) { if (result == "undo") { std::swap(url, undo); redo = true; } else if (redo) { std::swap(url, undo); redo = false; } else { std::string line; std::getline(data, line); if (line.empty() || line == "testname result comment") { report << line << '\n'; continue; } if (line[0] == '#') { if (line.compare(1, 9, "userstyle") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> userStyle; } else userStyle.clear(); } else if (line.compare(1, 9, "testfonts") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> testFonts; } else testFonts.clear(); } report << line << '\n'; continue; } undo = url; std::stringstream s(line, std::stringstream::in); s >> url; } if (url.empty()) continue; std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case REPORT: break; case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc - argi, args, userStyle, testFonts, url, output); break; } if (0 < pid && output.empty()) result = "fatal"; else if (mode == INTERACTIVE) { std::cout << "## complete\n" << output; std::cout << '[' << url << "] "; if (evaluation.empty() || evaluation[0] == '?') std::cout << "pass? "; else { std::cout << evaluation << "? "; if (evaluation != "pass") std::cout << '\a'; } std::getline(std::cin, result); if (result.empty()) { if (evaluation.empty() || evaluation[0] == '?') result = "pass"; else result = evaluation; } else if (result == "p" || result == "\x1b") result = "pass"; else if (result == "f") result = "fail"; else if (result == "i") result = "invalid"; else if (result == "k") // keep result = evaluation; else if (result == "n") result = "na"; else if (result == "s") result = "skip"; else if (result == "u") result = "uncertain"; else if (result == "q" || result == "quit") break; else if (result == "z") result = "undo"; if (result != "undo" && !saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } } else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; } else if (mode == REPORT) { result = evaluation; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } } } if (0 < pid) killTest(pid); if (result != "undo") report << url << '\t' << result << '\n'; if (mode != INTERACTIVE && result[0] != '?') std::cout << url << '\t' << result << '\n'; } report.close(); } <|endoftext|>
<commit_before>/** * Hashidsxx (c) 2014 Toon Schoenmakers * * https://github.com/schoentoon/hashidsxx * hashidsxx may be freely distributed under the MIT license. * * Modifications and optimizations: (c) 2015 Ian Matyssik <ian@phpb.com> */ #include "hashids.h" #include <algorithm> #define RATIO_SEPARATORS 3.5 #define RATIO_GUARDS 12 #include <iterator> #include <iostream> #include <sstream> namespace hashidsxx { const static std::string separators("cfhistuCFHISTU"); Hashids::Hashids(const std::string &salt, unsigned int min_length, const std::string &alphabet) : _salt(salt), _alphabet(alphabet), _min_length(min_length), _separators(), _guards() { std::for_each(separators.begin(), separators.end(), [this](char c) { if (_alphabet.find(c) != std::string::npos) _separators.push_back(c); }); _alphabet.erase( std::remove_if(_alphabet.begin(), _alphabet.end(), [this](char c) { return _separators.find(c) != std::string::npos; }), _alphabet.end()); if (_alphabet.size() + _separators.size() < 16) _alphabet = DEFAULT_ALPHABET; _separators = _reorder(_separators, _salt); std::size_t min_separators = (std::size_t)std::ceil((float)_alphabet.length() / RATIO_SEPARATORS); if (_separators.empty() || _separators.length() < min_separators) { if (min_separators == 1) min_separators = 2; if (min_separators > _separators.length()) { auto split_at = min_separators - _separators.length(); _separators.append(_alphabet.substr(0, split_at)); _alphabet = _alphabet.substr(split_at); }; }; _alphabet = _reorder(_alphabet, _salt); std::size_t num_guards = (std::size_t)std::ceil((float)_alphabet.length() / RATIO_GUARDS); if (_alphabet.length() < 3) { _guards = _separators.substr(0, num_guards); _separators = _separators.substr(num_guards); } else { _guards = _alphabet.substr(0, num_guards); _alphabet = _alphabet.substr(num_guards); }; } Hashids::Hashids(const Hashids &that) : _salt(that._salt), _alphabet(that._alphabet), _min_length(that._min_length), _separators(that._separators), _guards(that._guards) { } Hashids::Hashids(Hashids &&that) : _salt(std::move(that._salt)), _alphabet(std::move(that._alphabet)), _min_length(that._min_length), _separators(std::move(that._separators)), _guards(std::move(that._guards)) { } Hashids::~Hashids() { } std::string &Hashids::_reorder(std::string &input, const std::string &salt) const { uint8_t i, j, v, p; if (salt.empty()) return input; if (salt.size() > UINT8_MAX || input.size() > UINT8_MAX) return input; for (i = input.length() - 1, v = 0, p = 0; i > 0; --i, ++v) { v %= salt.length(); p += salt[v]; j = (uint8_t)(salt[v] + v + p) % i; std::swap(input[i], input[j]); } return input; } std::string Hashids::_reorder_norewrite(const std::string &input, const std::string &salt) const { auto output(input); return _reorder(output, salt); } std::string Hashids::_hash(uint64_t number, const std::string &alphabet) const { std::string output; uint64_t n = number; uint8_t r = 0; while (true) { n = n / alphabet.size(); r = (uint8_t)n % alphabet.size(); output.insert(output.begin(), alphabet[r]); if (n == 0) return output; }; } uint64_t Hashids::_unhash(const std::string &input, const std::string &alphabet) const { uint64_t output = 0; for (std::string::size_type i = 0; i < input.size(); ++i) { char c = input[i]; std::string::size_type pos = alphabet.find(c); output += pos * std::pow(alphabet.size(), input.size() - i - 1); }; return output; } void Hashids::_ensure_length(std::string &output, std::string &alphabet, int values_hash) const { uint8_t guard_index = (uint8_t)(values_hash + output[0]) % _guards.size(); output.insert(output.begin(), _guards[guard_index]); if (output.size() < _min_length) { guard_index = (values_hash + output[2]) % _guards.size(); output.push_back(_guards[guard_index]); }; uint8_t split_at = (uint8_t)alphabet.size() / 2; while (output.size() < _min_length) { alphabet = _reorder_norewrite(alphabet, alphabet); output = alphabet.substr(split_at) + output + alphabet.substr(0, split_at); auto excess = output.size() - _min_length; if (excess > 0) { auto from_index = excess / 2; output = output.substr(from_index, _min_length); }; }; } std::vector<std::string> Hashids::_split(const std::string &input, const std::string &splitters) const { std::vector<std::string> parts; std::string tmp; for (auto c : input) { if (splitters.find(c) != std::string::npos) { parts.push_back(tmp); tmp.clear(); } else tmp.push_back(c); }; if (!tmp.empty()) parts.push_back(tmp); return parts; } std::vector<uint64_t> Hashids::decode(const std::string &input) const { std::vector<uint64_t> output; auto parts = _split(input, _guards); auto hashid = parts[0]; if (parts.size() >= 2) hashid = parts[1]; if (hashid.empty()) return output; output.reserve(parts.size()); char lottery = hashid[0]; auto alphabet(_alphabet); hashid.erase(hashid.begin()); auto hash_parts = _split(hashid, _separators); for (const std::string &part : hash_parts) { auto alphabet_salt = (lottery + _salt + alphabet); alphabet_salt = alphabet_salt.substr(0, alphabet.size()); alphabet = _reorder(alphabet, alphabet_salt); output.push_back(_unhash(part, alphabet)); }; return output; } }; // vim: syntax=cpp11:ts=2:sw=2<commit_msg>See if it is due to overflow of the datatype<commit_after>/** * Hashidsxx (c) 2014 Toon Schoenmakers * * https://github.com/schoentoon/hashidsxx * hashidsxx may be freely distributed under the MIT license. * * Modifications and optimizations: (c) 2015 Ian Matyssik <ian@phpb.com> */ #include "hashids.h" #include <algorithm> #define RATIO_SEPARATORS 3.5 #define RATIO_GUARDS 12 #include <iterator> #include <iostream> #include <sstream> namespace hashidsxx { const static std::string separators("cfhistuCFHISTU"); Hashids::Hashids(const std::string &salt, unsigned int min_length, const std::string &alphabet) : _salt(salt), _alphabet(alphabet), _min_length(min_length), _separators(), _guards() { std::for_each(separators.begin(), separators.end(), [this](char c) { if (_alphabet.find(c) != std::string::npos) _separators.push_back(c); }); _alphabet.erase( std::remove_if(_alphabet.begin(), _alphabet.end(), [this](char c) { return _separators.find(c) != std::string::npos; }), _alphabet.end()); if (_alphabet.size() + _separators.size() < 16) _alphabet = DEFAULT_ALPHABET; _separators = _reorder(_separators, _salt); std::size_t min_separators = (std::size_t)std::ceil((float)_alphabet.length() / RATIO_SEPARATORS); if (_separators.empty() || _separators.length() < min_separators) { if (min_separators == 1) min_separators = 2; if (min_separators > _separators.length()) { auto split_at = min_separators - _separators.length(); _separators.append(_alphabet.substr(0, split_at)); _alphabet = _alphabet.substr(split_at); }; }; _alphabet = _reorder(_alphabet, _salt); std::size_t num_guards = (std::size_t)std::ceil((float)_alphabet.length() / RATIO_GUARDS); if (_alphabet.length() < 3) { _guards = _separators.substr(0, num_guards); _separators = _separators.substr(num_guards); } else { _guards = _alphabet.substr(0, num_guards); _alphabet = _alphabet.substr(num_guards); }; } Hashids::Hashids(const Hashids &that) : _salt(that._salt), _alphabet(that._alphabet), _min_length(that._min_length), _separators(that._separators), _guards(that._guards) { } Hashids::Hashids(Hashids &&that) : _salt(std::move(that._salt)), _alphabet(std::move(that._alphabet)), _min_length(that._min_length), _separators(std::move(that._separators)), _guards(std::move(that._guards)) { } Hashids::~Hashids() { } std::string &Hashids::_reorder(std::string &input, const std::string &salt) const { uint32_t i, j, v, p; if (salt.empty()) return input; if (salt.size() > UINT32_MAX || input.size() > UINT32_MAX) return input; for (i = input.length() - 1, v = 0, p = 0; i > 0; --i, ++v) { v %= salt.length(); p += salt[v]; j = (uint8_t)(salt[v] + v + p) % i; std::swap(input[i], input[j]); } return input; } std::string Hashids::_reorder_norewrite(const std::string &input, const std::string &salt) const { auto output(input); return _reorder(output, salt); } std::string Hashids::_hash(uint64_t number, const std::string &alphabet) const { std::string output; uint64_t n = number; uint8_t r = 0; while (true) { n = n / alphabet.size(); r = (uint8_t)n % alphabet.size(); output.insert(output.begin(), alphabet[r]); if (n == 0) return output; }; } uint64_t Hashids::_unhash(const std::string &input, const std::string &alphabet) const { uint64_t output = 0; for (std::string::size_type i = 0; i < input.size(); ++i) { char c = input[i]; std::string::size_type pos = alphabet.find(c); output += pos * std::pow(alphabet.size(), input.size() - i - 1); }; return output; } void Hashids::_ensure_length(std::string &output, std::string &alphabet, int values_hash) const { uint8_t guard_index = (uint8_t)(values_hash + output[0]) % _guards.size(); output.insert(output.begin(), _guards[guard_index]); if (output.size() < _min_length) { guard_index = (values_hash + output[2]) % _guards.size(); output.push_back(_guards[guard_index]); }; uint8_t split_at = (uint8_t)alphabet.size() / 2; while (output.size() < _min_length) { alphabet = _reorder_norewrite(alphabet, alphabet); output = alphabet.substr(split_at) + output + alphabet.substr(0, split_at); auto excess = output.size() - _min_length; if (excess > 0) { auto from_index = excess / 2; output = output.substr(from_index, _min_length); }; }; } std::vector<std::string> Hashids::_split(const std::string &input, const std::string &splitters) const { std::vector<std::string> parts; std::string tmp; for (auto c : input) { if (splitters.find(c) != std::string::npos) { parts.push_back(tmp); tmp.clear(); } else tmp.push_back(c); }; if (!tmp.empty()) parts.push_back(tmp); return parts; } std::vector<uint64_t> Hashids::decode(const std::string &input) const { std::vector<uint64_t> output; auto parts = _split(input, _guards); auto hashid = parts[0]; if (parts.size() >= 2) hashid = parts[1]; if (hashid.empty()) return output; output.reserve(parts.size()); char lottery = hashid[0]; auto alphabet(_alphabet); hashid.erase(hashid.begin()); auto hash_parts = _split(hashid, _separators); for (const std::string &part : hash_parts) { auto alphabet_salt = (lottery + _salt + alphabet); alphabet_salt = alphabet_salt.substr(0, alphabet.size()); alphabet = _reorder(alphabet, alphabet_salt); output.push_back(_unhash(part, alphabet)); }; return output; } }; // vim: syntax=cpp11:ts=2:sw=2<|endoftext|>
<commit_before>// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "pink/include/server_thread.h" #include <arpa/inet.h> #include <sys/time.h> #include <fcntl.h> #include "slash/include/xdebug.h" #include "pink/src/pink_epoll.h" #include "pink/src/server_socket.h" namespace pink { using slash::Status; class DefaultServerHandle : public ServerHandle { public: virtual void CronHandle() const override {} virtual void FdTimeoutHandle( int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } virtual void FdClosedHandle( int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } virtual bool AccessHandle(std::string& ip) const override { UNUSED(ip); return true; } virtual bool AccessHandle(int fd, std::string& ip) const override { UNUSED(fd); UNUSED(ip); return true; } virtual int CreateWorkerSpecificData(void** data) const override { UNUSED(data); return 0; } virtual int DeleteWorkerSpecificData(void* data) const override { UNUSED(data); return 0; } }; static const ServerHandle* SanitizeHandle(const ServerHandle* raw_handle) { if (raw_handle == nullptr) { return new DefaultServerHandle(); } return raw_handle; } ServerThread::ServerThread(int port, int cron_interval, const ServerHandle* handle) : pink_epoll_(NULL), cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_.insert("0.0.0.0"); } ServerThread::ServerThread(const std::string& bind_ip, int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_.insert(bind_ip); } ServerThread::ServerThread(const std::set<std::string>& bind_ips, int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_ = bind_ips; } ServerThread::~ServerThread() { #ifdef __ENABLE_SSL if (security_) { SSL_CTX_free(ssl_ctx_); EVP_cleanup(); } #endif delete(pink_epoll_); for (std::vector<ServerSocket*>::iterator iter = server_sockets_.begin(); iter != server_sockets_.end(); ++iter) { delete *iter; } if (own_handle_) { delete handle_; } } int ServerThread::StartThread() { int ret = 0; ret = InitHandle(); if (ret != kSuccess) return ret; return Thread::StartThread(); } int ServerThread::InitHandle() { int ret = 0; ServerSocket* socket_p; pink_epoll_ = new PinkEpoll(); if (ips_.find("0.0.0.0") != ips_.end()) { ips_.clear(); ips_.insert("0.0.0.0"); } for (std::set<std::string>::iterator iter = ips_.begin(); iter != ips_.end(); ++iter) { socket_p = new ServerSocket(port_); server_sockets_.push_back(socket_p); ret = socket_p->Listen(*iter); if (ret != kSuccess) { return ret; } // init pool pink_epoll_->PinkAddEvent( socket_p->sockfd(), EPOLLIN | EPOLLERR | EPOLLHUP); server_fds_.insert(socket_p->sockfd()); } return kSuccess; } void ServerThread::DoCronTask() { } void *ServerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe; Status s; struct sockaddr_in cliaddr; socklen_t clilen = sizeof(struct sockaddr); int fd, connfd; struct timeval when; gettimeofday(&when, nullptr); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } std::string ip_port; char port_buf[32]; char ip_addr[INET_ADDRSTRLEN] = ""; while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, nullptr); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { // Do own cron task as well as user's DoCronTask(); handle_->CronHandle(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; fd = pfe->fd; /* * Handle server event */ if (server_fds_.find(fd) != server_fds_.end()) { if (pfe->mask & EPOLLIN) { connfd = accept(fd, (struct sockaddr *) &cliaddr, &clilen); if (connfd == -1) { log_warn("accept error, errno numberis %d, error reason %s", errno, strerror(errno)); continue; } fcntl(connfd, F_SETFD, fcntl(connfd, F_GETFD) | FD_CLOEXEC); // Just ip ip_port = inet_ntop(AF_INET, &cliaddr.sin_addr, ip_addr, sizeof(ip_addr)); ip_port.append(":"); snprintf(port_buf, sizeof(port_buf), "%d", ntohs(cliaddr.sin_port)); ip_port.append(port_buf); if (!handle_->AccessHandle(ip_port) || !handle_->AccessHandle(connfd, ip_port)) { close(connfd); continue; } /* * Handle new connection, * implemented in derived class */ HandleNewConn(connfd, ip_port); } else if (pfe->mask & (EPOLLHUP | EPOLLERR)) { /* * this branch means there is error on the listen fd */ close(pfe->fd); continue; } } else { /* * Handle connection's event * implemented in derived class */ HandleConnEvent(pfe); } } } for (auto iter = server_sockets_.begin(); iter != server_sockets_.end(); iter++) { delete *iter; } server_sockets_.clear(); server_fds_.clear(); delete pink_epoll_; pink_epoll_ = nullptr; return nullptr; } #ifdef __ENABLE_SSL static std::vector<std::unique_ptr<slash::Mutex>> ssl_mutex_; static void SSLLockingCallback(int mode, int type, const char* file, int line) { if (mode & CRYPTO_LOCK) { ssl_mutex_[type]->Lock(); } else { ssl_mutex_[type]->Unlock(); } } static unsigned long SSLIdCallback() { return (unsigned long)pthread_self(); } int ServerThread::EnableSecurity(const std::string& cert_file, const std::string& key_file) { if (cert_file.empty() || key_file.empty()) { log_warn("cert_file and key_file can not be empty!"); } // Init Security Env // 1. Create multithread mutex used by openssl ssl_mutex_.resize(CRYPTO_num_locks()); for (auto& sm : ssl_mutex_) { sm.reset(new slash::Mutex()); } CRYPTO_set_locking_callback(SSLLockingCallback); CRYPTO_set_id_callback(SSLIdCallback); // 2. Use default configuration OPENSSL_config(NULL); // 3. Init library, load all algorithms SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); // 4. Create ssl context ssl_ctx_ = SSL_CTX_new(SSLv23_server_method()); if (!ssl_ctx_) { log_warn("Unable to create SSL context"); return -1; } // 5. Set cert file and key file, then check key file if (SSL_CTX_use_certificate_file( ssl_ctx_, cert_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_certificate_file(%s) failed", cert_file.c_str()); return -1; } if (SSL_CTX_use_PrivateKey_file( ssl_ctx_, key_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_PrivateKey_file(%s)", key_file.c_str()); return -1; } if (SSL_CTX_check_private_key(ssl_ctx_) != 1) { log_warn("SSL_CTX_check_private_key(%s)", key_file.c_str()); return -1; } // https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_read_ahead(3) // read data as more as possible SSL_CTX_set_read_ahead(ssl_ctx_, true); // Force using TLS 1.2 SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_SSLv2); SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_SSLv3); SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_TLSv1); // Enable ECDH // https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman // https://wiki.openssl.org/index.php/Diffie_Hellman // https://wiki.openssl.org/index.php/Diffie-Hellman_parameters EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!ecdh) { log_warn("EC_KEY_new_by_curve_name(%d)", NID_X9_62_prime256v1); return -1; } SSL_CTX_set_options(ssl_ctx_, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_tmp_ecdh(ssl_ctx_, ecdh); EC_KEY_free(ecdh); security_ = true; return 0; } #endif } // namespace pink <commit_msg>revert 228f67efde3a8546ad679b371361fab787c10a70<commit_after>// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "pink/include/server_thread.h" #include <arpa/inet.h> #include <sys/time.h> #include <fcntl.h> #include "slash/include/xdebug.h" #include "pink/src/pink_epoll.h" #include "pink/src/server_socket.h" namespace pink { using slash::Status; class DefaultServerHandle : public ServerHandle { public: virtual void CronHandle() const override {} virtual void FdTimeoutHandle( int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } virtual void FdClosedHandle( int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } virtual bool AccessHandle(std::string& ip) const override { UNUSED(ip); return true; } virtual bool AccessHandle(int fd, std::string& ip) const override { UNUSED(fd); UNUSED(ip); return true; } virtual int CreateWorkerSpecificData(void** data) const override { UNUSED(data); return 0; } virtual int DeleteWorkerSpecificData(void* data) const override { UNUSED(data); return 0; } }; static const ServerHandle* SanitizeHandle(const ServerHandle* raw_handle) { if (raw_handle == nullptr) { return new DefaultServerHandle(); } return raw_handle; } ServerThread::ServerThread(int port, int cron_interval, const ServerHandle* handle) : pink_epoll_(NULL), cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_.insert("0.0.0.0"); } ServerThread::ServerThread(const std::string& bind_ip, int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_.insert(bind_ip); } ServerThread::ServerThread(const std::set<std::string>& bind_ips, int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), #ifdef __ENABLE_SSL security_(false), #endif port_(port) { ips_ = bind_ips; } ServerThread::~ServerThread() { #ifdef __ENABLE_SSL if (security_) { SSL_CTX_free(ssl_ctx_); EVP_cleanup(); } #endif delete(pink_epoll_); for (std::vector<ServerSocket*>::iterator iter = server_sockets_.begin(); iter != server_sockets_.end(); ++iter) { delete *iter; } if (own_handle_) { delete handle_; } } int ServerThread::StartThread() { int ret = 0; ret = InitHandle(); if (ret != kSuccess) return ret; return Thread::StartThread(); } int ServerThread::InitHandle() { int ret = 0; ServerSocket* socket_p; pink_epoll_ = new PinkEpoll(); if (ips_.find("0.0.0.0") != ips_.end()) { ips_.clear(); ips_.insert("0.0.0.0"); } for (std::set<std::string>::iterator iter = ips_.begin(); iter != ips_.end(); ++iter) { socket_p = new ServerSocket(port_); server_sockets_.push_back(socket_p); ret = socket_p->Listen(*iter); if (ret != kSuccess) { return ret; } // init pool pink_epoll_->PinkAddEvent( socket_p->sockfd(), EPOLLIN | EPOLLERR | EPOLLHUP); server_fds_.insert(socket_p->sockfd()); } return kSuccess; } void ServerThread::DoCronTask() { } void *ServerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe; Status s; struct sockaddr_in cliaddr; socklen_t clilen = sizeof(struct sockaddr); int fd, connfd; struct timeval when; gettimeofday(&when, nullptr); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } std::string ip_port; char port_buf[32]; char ip_addr[INET_ADDRSTRLEN] = ""; while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, nullptr); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { // Do own cron task as well as user's DoCronTask(); handle_->CronHandle(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; fd = pfe->fd; /* * Handle server event */ if (server_fds_.find(fd) != server_fds_.end()) { if (pfe->mask & EPOLLIN) { connfd = accept(fd, (struct sockaddr *) &cliaddr, &clilen); if (connfd == -1) { log_warn("accept error, errno numberis %d, error reason %s", errno, strerror(errno)); continue; } fcntl(connfd, F_SETFD, fcntl(connfd, F_GETFD) | FD_CLOEXEC); // Just ip ip_port = inet_ntop(AF_INET, &cliaddr.sin_addr, ip_addr, sizeof(ip_addr)); if (!handle_->AccessHandle(ip_port) || !handle_->AccessHandle(connfd, ip_port)) { close(connfd); continue; } ip_port.append(":"); snprintf(port_buf, sizeof(port_buf), "%d", ntohs(cliaddr.sin_port)); ip_port.append(port_buf); /* * Handle new connection, * implemented in derived class */ HandleNewConn(connfd, ip_port); } else if (pfe->mask & (EPOLLHUP | EPOLLERR)) { /* * this branch means there is error on the listen fd */ close(pfe->fd); continue; } } else { /* * Handle connection's event * implemented in derived class */ HandleConnEvent(pfe); } } } for (auto iter = server_sockets_.begin(); iter != server_sockets_.end(); iter++) { delete *iter; } server_sockets_.clear(); server_fds_.clear(); delete pink_epoll_; pink_epoll_ = nullptr; return nullptr; } #ifdef __ENABLE_SSL static std::vector<std::unique_ptr<slash::Mutex>> ssl_mutex_; static void SSLLockingCallback(int mode, int type, const char* file, int line) { if (mode & CRYPTO_LOCK) { ssl_mutex_[type]->Lock(); } else { ssl_mutex_[type]->Unlock(); } } static unsigned long SSLIdCallback() { return (unsigned long)pthread_self(); } int ServerThread::EnableSecurity(const std::string& cert_file, const std::string& key_file) { if (cert_file.empty() || key_file.empty()) { log_warn("cert_file and key_file can not be empty!"); } // Init Security Env // 1. Create multithread mutex used by openssl ssl_mutex_.resize(CRYPTO_num_locks()); for (auto& sm : ssl_mutex_) { sm.reset(new slash::Mutex()); } CRYPTO_set_locking_callback(SSLLockingCallback); CRYPTO_set_id_callback(SSLIdCallback); // 2. Use default configuration OPENSSL_config(NULL); // 3. Init library, load all algorithms SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); // 4. Create ssl context ssl_ctx_ = SSL_CTX_new(SSLv23_server_method()); if (!ssl_ctx_) { log_warn("Unable to create SSL context"); return -1; } // 5. Set cert file and key file, then check key file if (SSL_CTX_use_certificate_file( ssl_ctx_, cert_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_certificate_file(%s) failed", cert_file.c_str()); return -1; } if (SSL_CTX_use_PrivateKey_file( ssl_ctx_, key_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_PrivateKey_file(%s)", key_file.c_str()); return -1; } if (SSL_CTX_check_private_key(ssl_ctx_) != 1) { log_warn("SSL_CTX_check_private_key(%s)", key_file.c_str()); return -1; } // https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_read_ahead(3) // read data as more as possible SSL_CTX_set_read_ahead(ssl_ctx_, true); // Force using TLS 1.2 SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_SSLv2); SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_SSLv3); SSL_CTX_set_options(ssl_ctx_, SSL_OP_NO_TLSv1); // Enable ECDH // https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman // https://wiki.openssl.org/index.php/Diffie_Hellman // https://wiki.openssl.org/index.php/Diffie-Hellman_parameters EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!ecdh) { log_warn("EC_KEY_new_by_curve_name(%d)", NID_X9_62_prime256v1); return -1; } SSL_CTX_set_options(ssl_ctx_, SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_tmp_ecdh(ssl_ctx_, ecdh); EC_KEY_free(ecdh); security_ = true; return 0; } #endif } // namespace pink <|endoftext|>