diff --git a/.gitattributes b/.gitattributes index 98ac3b1e8c1c198ed1c179aed275e327fbd0a282..477c32b8a25305b90d38a6f9cd2ac54b8c4b3cb1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -695,3 +695,6 @@ benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_ benchmark/science_bowl/MS-Sample-Questions/Sample-Set-16/2022-MS-3.pdf filter=lfs diff=lfs merge=lfs -text benchmark/science_bowl/HS-Sample-Questions/Sample-Set-5/Round2.pdf filter=lfs diff=lfs merge=lfs -text benchmark/science_bowl/HS-Sample-Questions/Sample-Set-5/Round6.pdf filter=lfs diff=lfs merge=lfs -text +benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-2.mov filter=lfs diff=lfs merge=lfs -text +benchmark/Cybench/benchmark/project-sekai-ctf/sekaictf-2023/reverse/azusawas-gacha-world/dist/UnityPlayer.dll filter=lfs diff=lfs merge=lfs -text +benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-3.mov filter=lfs diff=lfs merge=lfs -text diff --git a/benchmark/Cybench/benchmark/project-sekai-ctf/sekaictf-2023/reverse/azusawas-gacha-world/dist/UnityPlayer.dll b/benchmark/Cybench/benchmark/project-sekai-ctf/sekaictf-2023/reverse/azusawas-gacha-world/dist/UnityPlayer.dll new file mode 100644 index 0000000000000000000000000000000000000000..ba56543ed0a861a0ad7e7485bdc92e67a66e80b7 --- /dev/null +++ b/benchmark/Cybench/benchmark/project-sekai-ctf/sekaictf-2023/reverse/azusawas-gacha-world/dist/UnityPlayer.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc3b24ffe27b59beba21fbb3359b246b4819de865a02893f694769894045116f +size 29387288 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004752.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004752.pt new file mode 100644 index 0000000000000000000000000000000000000000..082e70342ab527744e1b13e9456a4a0eb4468dee --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004752.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56e68aacef03b80551cc2e83df33902a3fb91dfd96a86f683de214c8611cf0ff +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004758.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004758.pt new file mode 100644 index 0000000000000000000000000000000000000000..2d4e24588d6b167966e345ff2c568e41d58c4b87 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004758.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa303f9c85128e890a1250d64885a558f8855d9f05b43f5cd779d5edfb1a555b +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004759.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004759.pt new file mode 100644 index 0000000000000000000000000000000000000000..73a7b2f8ee55054146c0a56add989d260703c1d7 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004759.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cd91c8ff9afdc5ef1f54ce7beeccac1b8da942123f4fc48747808e1e9d777c1 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004778.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004778.pt new file mode 100644 index 0000000000000000000000000000000000000000..2f47d408a49bdefb82c437303b026929cae44b1d --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004778.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a796c6753ff299d40953c04b6ca218c653cc24a231442002247f244b68a106ad +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004826.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004826.pt new file mode 100644 index 0000000000000000000000000000000000000000..b6af475bad940ed3976ca80dc174b9590a46b9be --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004826.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6329524dca64d9d9247eff2aec1fe6d3648b30f70c44cc5fa70720b3522c3d92 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004860.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004860.pt new file mode 100644 index 0000000000000000000000000000000000000000..ecc50ee7380dbb85db5b062b4943201526898c9a --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004860.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5622ac96696ac77ff1b1c3e227734640f1881282c765124bb0af66b09800be5 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004862.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004862.pt new file mode 100644 index 0000000000000000000000000000000000000000..49208f56f9be4c764ca0c1dafb7865a1b055bcbc --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004862.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6be32b2a83cd79046cd409c6230eefa7e7a43a90f88564954961b2a258721592 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004864.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004864.pt new file mode 100644 index 0000000000000000000000000000000000000000..f04897508aa7efe3ce4e94c506802f989a6a9abc --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004864.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12b8321f9374659585376c912d86fcaa38364beeb7fb612542a9bbc85119b8d4 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004892.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004892.pt new file mode 100644 index 0000000000000000000000000000000000000000..b967a9759f28e29cfa065b9f89d8172317cc694e --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004892.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7e3ac6c5576cb44ded8b2089f0c0842423c727c5cb0e2246432b15179e1a582 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004903.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004903.pt new file mode 100644 index 0000000000000000000000000000000000000000..8b348a441eeae0e0bff887b0b2bb7ef323a2d9c8 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004903.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38c1cbb888bd1aac7d07b95539fc6d084d95ea17f985879856acbaf560734ec6 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004906.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004906.pt new file mode 100644 index 0000000000000000000000000000000000000000..748b4f493c2d9e081a2b885b7cfb087f2ad724d6 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004906.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c51e9d308fd3a6a5afe2f2e83f6ab22ba9d32aa1c2fa055ca4a12a65490e0af +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004912.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004912.pt new file mode 100644 index 0000000000000000000000000000000000000000..0e92b30538b64f679b938953bd235d765caf007c --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004912.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5baf5fecf1cb045a75996cfeb4691683192a804927cf7244ff2765f0bef4b29 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004914.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004914.pt new file mode 100644 index 0000000000000000000000000000000000000000..7e275791325fba9cf0bd8f1f73f6ee45e541cd75 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004914.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:842154a3339e46469b013e97de0f949986d987339d08293b2f8da0e0fd95a497 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004918.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004918.pt new file mode 100644 index 0000000000000000000000000000000000000000..df72bfdffc9217b83c3aebdccfa741fbcc75f231 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_004918.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78447511280de995e1b9ac9afa339c736fb01c01197f3b7694ce560a723ac650 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005142.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005142.pt new file mode 100644 index 0000000000000000000000000000000000000000..804e98cb56fc900bebfb1b0f0344179d5ebef089 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005142.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:271733c82f47fc1afd2a52ccaa1446f7c505d0815cf44f7bfdc12d2ae5f13f7a +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005143.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005143.pt new file mode 100644 index 0000000000000000000000000000000000000000..63c46145d633bd35bd0ec67880bd8fe5e7a11893 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_005143.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c78f4b8b4b0861ea4375cebcf357b114e365eba95049ab659258fdf0f40e4a51 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006977.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006977.pt new file mode 100644 index 0000000000000000000000000000000000000000..8fe36588aff6de69cb8300a810518f85a56e8c07 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006977.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65d217d6bde76eda31600634c15a5f95158d04ffc86f29bfbf66cd39183545c2 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006984.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006984.pt new file mode 100644 index 0000000000000000000000000000000000000000..ccdc0775809aa975515728200b40893b07fd7c75 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006984.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22bd98d30b5edbd6cb702f3d8f56f771bc0a36bb2d06e1d08a9478a77d59df42 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006986.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006986.pt new file mode 100644 index 0000000000000000000000000000000000000000..349c770abaefaa6c9c8cabb115058f0da0c9a271 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006986.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34b130274ba2c1e8a68583d69aa89f60fe3dc9cbc1fea2acd7a610792e486186 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006999.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006999.pt new file mode 100644 index 0000000000000000000000000000000000000000..ee25a5ee01350794ea2de0e501c27ab90e3e5d39 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_006999.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b56b709d3febea82f9b4a62911ed3c989c0df52f7a0f9db6e05a965245c7b0b +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007000.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007000.pt new file mode 100644 index 0000000000000000000000000000000000000000..ccd4c5b0a3efad49690134356db0d5accb828167 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afb525f998c8537f9f01857a94b24476d95ce6abb9c64f2a81edbab945d5e651 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007001.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007001.pt new file mode 100644 index 0000000000000000000000000000000000000000..0fbec0e102bdf44ee9b92f3f7bc71423c2c95073 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007001.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c84e5543ef512f5eac0d98027525c2feb70617651ed5dd6c18e416f67e3df9d5 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007016.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007016.pt new file mode 100644 index 0000000000000000000000000000000000000000..a6422851d2aa00cf083ac98438c716f9c7c0c1de --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007016.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd87d7982a7cd0e8c8adca3781e4a72502e8a219aa5fc71752a61a6103ccfbf0 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007018.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007018.pt new file mode 100644 index 0000000000000000000000000000000000000000..53b085fa3346b4ca66b70ba69dd3b8dcf8d40570 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007018.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47dbde107e5e6c3211c4cb7603b0cc2e593aa060361779a3aec367ae39bc1d4a +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007023.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007023.pt new file mode 100644 index 0000000000000000000000000000000000000000..3fa09c019aedb8faa091d2249342c7142a310fe9 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007023.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a45acb8e7b3ece355ec33033446c862734fe5bb7fb2eaeee5a3f24a4798c4f07 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007024.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007024.pt new file mode 100644 index 0000000000000000000000000000000000000000..3d7f90b208230a5d371c9ee1c830e725f09c44b2 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007024.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a75021709ed0c587da973c1c2296b1538ccc259c804d7ffe38e37902e52aec5 +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007044.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007044.pt new file mode 100644 index 0000000000000000000000000000000000000000..39d271d06ecb52336ec2207c371dec79ed3ca563 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007044.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53f86bd33eae7033a4ced8bf2e3c8695be7a0be6de0160af988f7bc63c3e0491 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007053.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007053.pt new file mode 100644 index 0000000000000000000000000000000000000000..f96f6d6b3c2f1e6cb5b6fd1c68dc8ea8c0065e1a --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007053.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4aa43d2c5182d647a42149230bc4de660ffa4f1d9c0c8d14d5681a0da9570498 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007059.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007059.pt new file mode 100644 index 0000000000000000000000000000000000000000..133ff03dad1ab7604a7cbd34959dbacca2f07c26 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/test_v3/testing_set/data_007059.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edbb9e4002b97770d3b4268340ebc8cf433b27a4b4b236df5f8df3d18c24fe3b +size 49378 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2196634_spoof_A11.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2196634_spoof_A11.pt new file mode 100644 index 0000000000000000000000000000000000000000..b5ab736f88ef248bed1fd9fff6852cd92a5f93bf --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2196634_spoof_A11.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b79ed1c619f8f1c4e3eab94f781e45648e891651c5b45e60cc959f42edb32599 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215024_spoof_A10.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215024_spoof_A10.pt new file mode 100644 index 0000000000000000000000000000000000000000..2750d3977c94fc94ccf67e333b98ccc60cb9ff4f --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215024_spoof_A10.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f46570dd9ab222c8b9038cef7fc4deaaf4d05045dbb9358dd0b3ffdc8bd95635 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215394_spoof_A09.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215394_spoof_A09.pt new file mode 100644 index 0000000000000000000000000000000000000000..8a2e430bc33d08aff3b01f7a1cd229ca19762dfb --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2215394_spoof_A09.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4083a9cb3eaaf209ece1d016b3cc7c9e7e105fd5928fa2682be80e488d799c4c +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2218640_spoof_A16.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2218640_spoof_A16.pt new file mode 100644 index 0000000000000000000000000000000000000000..06a4a0f3c5e15fa7bb226b18478627e14b2c70f9 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2218640_spoof_A16.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaebed4ee52db1b717952499b8f0e9b9218d6c676dd222335773a6ebe1798995 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221303_spoof_A10.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221303_spoof_A10.pt new file mode 100644 index 0000000000000000000000000000000000000000..4e306bd7d4ecf61f0e2cabc36ebdf0746a62358c --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221303_spoof_A10.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04b947758136d84531294190517b424254e70597d23cc8dd394177e1a1c0c82c +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221984_spoof_A18.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221984_spoof_A18.pt new file mode 100644 index 0000000000000000000000000000000000000000..d9be07a1eb98a8f39083a644073a7a72b0c9c6eb --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2221984_spoof_A18.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5c423af6732dba6040e1f6ee124d40dc4cd0a407f42195c4323d7dde10a6175 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2222115_spoof_A14.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2222115_spoof_A14.pt new file mode 100644 index 0000000000000000000000000000000000000000..76317ac416e7fe4cc726a904a997fe38383a61fa --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2222115_spoof_A14.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6335c727351ac9755e882ada0ba34d78985aeaa2867e1b964027da5b2ec73e2 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2231956_spoof_A07.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2231956_spoof_A07.pt new file mode 100644 index 0000000000000000000000000000000000000000..a2c663bb89302db40f76068abec6e107c05a2a3b --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2231956_spoof_A07.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c900d4ced4adb2dbf39f425cbc9e8f78315bf34281a1c2a177981bef0f1ba827 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2472956_spoof_A12.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2472956_spoof_A12.pt new file mode 100644 index 0000000000000000000000000000000000000000..5913885df9428c703711f554c9394ab7b22b2692 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2472956_spoof_A12.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2802eed0249a73befd285589a3be8b5ad305c83f9311e271d227870772cc71f +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2476658_spoof_A19.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2476658_spoof_A19.pt new file mode 100644 index 0000000000000000000000000000000000000000..462a0123c08b0d90dd31637ff3f3e5371e2d93ec --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2476658_spoof_A19.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c5102b80389cad20bc4934f00a67c936c9adbf4df78bca9b3ae97896b650627 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592137_spoof_A14.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592137_spoof_A14.pt new file mode 100644 index 0000000000000000000000000000000000000000..fee69e8534eacb0567cd5675313b88350858dc3e --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592137_spoof_A14.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b14dbf95991195f9d66d8b569af37e50d099e00a7d2ad3fa49cd39cb5be2cda2 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592477_spoof_A12.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592477_spoof_A12.pt new file mode 100644 index 0000000000000000000000000000000000000000..ebb98299a94f693b1d51a557916e88ca5a6c598b --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2592477_spoof_A12.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca0e209c486c734528ce3cc3997821ff5316ba159ecf676f4b5a5157a4e1fb85 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2593581_spoof_A13.pt b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2593581_spoof_A13.pt new file mode 100644 index 0000000000000000000000000000000000000000..3c3af74b978f898110d72981dd958cf15ab241b9 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/GAITE-Contest/Synthetic_Speech_Detector/training_set/spoof/LA_E_2593581_spoof_A13.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:803e2c0fd9217d6b67b16374c10a65481805ee719d3f9d26ab8f9e809af19360 +size 49447 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1135.mat.pt b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1135.mat.pt new file mode 100644 index 0000000000000000000000000000000000000000..ccc2e25fb2688a1aaa6c0b5d2a84f57396c992c2 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1135.mat.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56316ac7d898d0d5ee117f0d0c00af3501883de21bc239951ef8b9eedf1f2535 +size 507499 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1753.mat.pt b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1753.mat.pt new file mode 100644 index 0000000000000000000000000000000000000000..37e8dfca2277175e0a52b4bcfa045940cd21fd1f --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/training_set/1753.mat.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfe5659118ec62f708f883867133a1eab5dab30e75a5e3cfd58f29abdfe549bb +size 507499 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/Scoring/metrics.py b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/Scoring/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d68097ec6680be863b038931e6ac5b58b4a827b2 --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/Scoring/metrics.py @@ -0,0 +1,200 @@ +import numpy as np +import json +import os +import sys +from pathlib import Path + +def calculate_precision_at_1(predictions, ground_truth): + """ + Calculate precision@1 for the given predictions and ground truth. + + Args: + predictions (np.array): Array of predicted gallery indices for each query + ground_truth (np.array): Array of correct gallery indices for each query + + Returns: + float: Precision@1 score (percentage of correct predictions) + """ + if len(predictions) != len(ground_truth): + raise ValueError(f"Predictions length ({len(predictions)}) doesn't match ground truth length ({len(ground_truth)})") + + # Count correct predictions + correct_predictions = np.sum(predictions == ground_truth) + total_predictions = len(predictions) + + # Calculate precision@1 as percentage + precision_at_1 = (correct_predictions / total_predictions) + + return precision_at_1 + +def load_submission_file(filepath): + """ + Load submission file and handle potential errors. + + Args: + filepath (str): Path to the submission file + + Returns: + np.array or None: Loaded array or None if file doesn't exist or is invalid + """ + try: + if not os.path.exists(filepath): + print(f"Warning: Submission file {filepath} not found") + return None + + submission = np.load(filepath) + print(f"Loaded {filepath}: shape {submission.shape}, dtype {submission.dtype}") + return submission + + except Exception as e: + print(f"Error loading {filepath}: {str(e)}") + return None + +def load_ground_truth_file(filepath): + """ + Load ground truth file. + + Args: + filepath (str): Path to the ground truth file + + Returns: + np.array: Loaded ground truth array + """ + try: + if not os.path.exists(filepath): + raise FileNotFoundError(f"Ground truth file {filepath} not found") + + ground_truth = np.load(filepath) + print(f"Loaded ground truth {filepath}: shape {ground_truth.shape}, dtype {ground_truth.dtype}") + return ground_truth + + except Exception as e: + print(f"Error loading ground truth {filepath}: {str(e)}") + raise + +def evaluate_test_set(submission_file, ground_truth_file, test_name): + """ + Evaluate a single test set. + + Args: + submission_file (str): Path to submission file + ground_truth_file (str): Path to ground truth file + test_name (str): Name of the test set for logging + + Returns: + float or None: Precision@1 score or None if evaluation failed + """ + print(f"\n=== Evaluating {test_name} ===") + + # Load ground truth + try: + ground_truth = load_ground_truth_file(ground_truth_file) + except Exception as e: + print(f"Failed to load ground truth for {test_name}: {str(e)}") + return None + + # Load submission + submission = load_submission_file(submission_file) + if submission is None: + print(f"Failed to load submission for {test_name}") + return None + + # Validate submission format + if submission.shape != ground_truth.shape: + print(f"Shape mismatch for {test_name}: submission {submission.shape} vs ground truth {ground_truth.shape}") + return None + + # Calculate precision@1 + try: + score = calculate_precision_at_1(submission, ground_truth) + print(f"{test_name} - Precision@1: {score:.2f}") + + # Log some statistics + correct_count = np.sum(submission == ground_truth) + total_count = len(submission) + print(f"{test_name} - Correct predictions: {correct_count}/{total_count}") + + return score + + except Exception as e: + print(f"Error calculating precision@1 for {test_name}: {str(e)}") + return None + +def main(): + """ + Main evaluation function. + """ + print("Starting evaluation...") + BASE_PATH = Path(__file__).parent + SCORING_PATH = BASE_PATH + + submission_a_file = SCORING_PATH / "submission_a.npy" + submission_b_file = SCORING_PATH / "submission_b.npy" + ground_truth_a_file = SCORING_PATH / "answer_a.npy" + ground_truth_b_file = SCORING_PATH / "answer_b.npy" + output_file = SCORING_PATH / "score.json" + + # Evaluate test set A + score_a = evaluate_test_set(submission_a_file, ground_truth_a_file, "Test Set A") + + + # Evaluate test set B + score_b = evaluate_test_set(submission_b_file, ground_truth_b_file, "Test Set B") + + + # Determine overall status + status = True + msg = "Success!" + + # Handle missing or failed evaluations + if score_a is None: + score_a = 0.0 + status = False + msg = "Failed to evaluate Test Set A" + + if score_b is None: + score_b = 0.0 + if status: # Only update if not already failed + status = False + msg = "Failed to evaluate Test Set B" + else: + msg = "Failed to evaluate both test sets" + if score_a > 1: + score_a = 0.0 + if score_b > 1: + score_b = 0.0 + def sanitize_score(value): + """处理单个分数值,将NaN和inf替换为0""" + if not np.isfinite(value): + return 0.0 + return value + # Create result dictionary + result = { + "status": status, + "score": { + "public_a": sanitize_score(score_a), + "private_b": sanitize_score(score_b), + }, + "msg": msg, + } + + # Save results to JSON + try: + with open(output_file, 'w') as f: + json.dump(result, f, indent=4) + print(f"\nResults saved to {output_file}") + except Exception as e: + print(f"Error saving results to {output_file}: {str(e)}") + sys.exit(1) + + # Print final summary + print("\n=== EVALUATION SUMMARY ===") + print(f"Status: {status}") + print(f"Test Set A (public) Score: {score_a:.2f}") + print(f"Test Set B (private) Score: {score_b:.2f}") + print(f"Message: {msg}") + + return result + +if __name__ == "__main__": + main() diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/test_set/gallery/1.png b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/test_set/gallery/1.png new file mode 100644 index 0000000000000000000000000000000000000000..c3d1df41264498893b5795ca3a740f48b151125a --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/test_set/gallery/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8cb96062f45f998cf3da0db8d63cb587313ddb676c2b7d5fc1a3f30dd6c4e9f4 +size 15372 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/6.png b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/6.png new file mode 100644 index 0000000000000000000000000000000000000000..e13617a5f46754d068fd02f9087ff0307ec4616f --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a4ad2d7deaead63eb9707802a608caa73589cccdf468dff580fd534e20482e5 +size 79173 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/7.png b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/7.png new file mode 100644 index 0000000000000000000000000000000000000000..2fe811903b53090e5e292a3bda6e58038ca2880a --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59ecf850226c98a0ba032152dd7532e80453573480acc138ee43cdee1eab1e1d +size 294847 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/8.png b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/8.png new file mode 100644 index 0000000000000000000000000000000000000000..2db621448ca3282f00980919ab01b943a917bd8b --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c55ce34057c5e998ea851a243628ab4f0c6e528fe08219d277b4fb7c9f05778 +size 83759 diff --git a/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/9.png b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/9.png new file mode 100644 index 0000000000000000000000000000000000000000..4ef78418175eb523ed3300809e3a508a88abfb6c --- /dev/null +++ b/benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/Solution/validation_set/query/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd20238d68e8fe7b0412b9b4f0667453d36c477c0b5b0bc37aa1f33bf5402225 +size 411364 diff --git a/benchmark/IOAI/IOAI2025/Individual-Contest/Radar/training_set/197.mat.pt b/benchmark/IOAI/IOAI2025/Individual-Contest/Radar/training_set/197.mat.pt new file mode 100644 index 0000000000000000000000000000000000000000..c809b3ceacd9555675c4474c23b308dfc0d07b47 --- /dev/null +++ b/benchmark/IOAI/IOAI2025/Individual-Contest/Radar/training_set/197.mat.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6bc94c2206e0a7b981d6dbdd69c9d7e50d8c34ccc607b5843b2ffc91dd5f7ed +size 507499 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-2.mov b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-2.mov new file mode 100644 index 0000000000000000000000000000000000000000..8b6ee1e9cc77054e2374bf1627787421e2ad1b91 --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-2.mov @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90032a15a0343267af2cfad03defdcdd6356d21f45bfb08ecdda5cc0b13b8f55 +size 7610844 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-3.mov b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-3.mov new file mode 100644 index 0000000000000000000000000000000000000000..5db910be698f50af0c4df18e9471f817ed798116 --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_364_index.html/ballroom-3.mov @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2eb8d6194514a07c06b447159259aab21d5b6a792fc745f32ebeb70a903c62b8 +size 8880280 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-1.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-1.png new file mode 100644 index 0000000000000000000000000000000000000000..8af6974c0b9a0208167343b9af0a55f3b771b94a --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5ef16f1be3fc1598c943805c99dd87cf7d258bb619d0050f7190d82fb965b49 +size 382 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-10.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-10.png new file mode 100644 index 0000000000000000000000000000000000000000..4943daed3d519bbe65da474a640e09188db216d2 --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c86226646fe5ffddd475d0aec6d5bb7d22ff0a1a077d1da6e2cf763e9df4253a +size 375 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-11.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-11.png new file mode 100644 index 0000000000000000000000000000000000000000..80763f4ae14daea4d7311e62a6f148d26f4717ee --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dde64a0d17b02db99cc101014a0ba6feffa7ed8b1a0bfae34c64fea814d650b +size 440 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-12.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-12.png new file mode 100644 index 0000000000000000000000000000000000000000..64c7de13f6f6bc673b397f1b8256b1170d43d488 --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59fb51baf924b812e1101285b684a47a48ccbc4492d9f8d1ec3ff86655821add +size 388 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-13.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-13.png new file mode 100644 index 0000000000000000000000000000000000000000..100e8f30a60a104f3777a525ba72efd49682c635 --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b202eb7713b952246a16f95da4fd72eaae493daf2bd69fd93b6f9f5c2639c34 +size 371 diff --git a/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-14.png b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-14.png new file mode 100644 index 0000000000000000000000000000000000000000..d0ff6768aa1afa7f84779ada6e6e1448eb23b64d --- /dev/null +++ b/benchmark/MIT_Mystery_Hunt/puzzles/by_tsv/2003/2003_www.acme-corp.com_teamGuest_R_4_943_index.html/biogarden-14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99d8e1cd5320ce9e0c6125e8f2293cf3eb60963d3a497a92a4bd37130a8b62d3 +size 490 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/py3k.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/py3k.py new file mode 100644 index 0000000000000000000000000000000000000000..067292776e20b8f0d271fc62590307e0748a6de4 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/py3k.py @@ -0,0 +1,243 @@ +""" +Python 3 compatibility tools. + +""" +from __future__ import division, absolute_import, print_function + +__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', + 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', + 'asstr', 'open_latin1', 'long', 'basestring', 'sixu', + 'integer_types', 'is_pathlib_path', 'npy_load_module', 'Path', + 'contextlib_nullcontext', 'os_fspath', 'os_PathLike'] + +import sys +try: + from pathlib import Path, PurePath +except ImportError: + Path = PurePath = None + +if sys.version_info[0] >= 3: + import io + + long = int + integer_types = (int,) + basestring = str + unicode = str + bytes = bytes + + def asunicode(s): + if isinstance(s, bytes): + return s.decode('latin1') + return str(s) + + def asbytes(s): + if isinstance(s, bytes): + return s + return str(s).encode('latin1') + + def asstr(s): + if isinstance(s, bytes): + return s.decode('latin1') + return str(s) + + def isfileobj(f): + return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)) + + def open_latin1(filename, mode='r'): + return open(filename, mode=mode, encoding='iso-8859-1') + + def sixu(s): + return s + + strchar = 'U' + + +else: + bytes = str + long = long + basestring = basestring + unicode = unicode + integer_types = (int, long) + asbytes = str + asstr = str + strchar = 'S' + + def isfileobj(f): + return isinstance(f, file) + + def asunicode(s): + if isinstance(s, unicode): + return s + return str(s).decode('ascii') + + def open_latin1(filename, mode='r'): + return open(filename, mode=mode) + + def sixu(s): + return unicode(s, 'unicode_escape') + + +def getexception(): + return sys.exc_info()[1] + +def asbytes_nested(x): + if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): + return [asbytes_nested(y) for y in x] + else: + return asbytes(x) + +def asunicode_nested(x): + if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): + return [asunicode_nested(y) for y in x] + else: + return asunicode(x) + +def is_pathlib_path(obj): + """ + Check whether obj is a pathlib.Path object. + + Prefer using `isinstance(obj, os_PathLike)` instead of this function. + """ + return Path is not None and isinstance(obj, Path) + +# from Python 3.7 +class contextlib_nullcontext(object): + """Context manager that does no additional processing. + + Used as a stand-in for a normal context manager, when a particular + block of code is only sometimes used with a normal context manager: + + cm = optional_cm if condition else nullcontext() + with cm: + # Perform operation, using optional_cm if condition is True + """ + + def __init__(self, enter_result=None): + self.enter_result = enter_result + + def __enter__(self): + return self.enter_result + + def __exit__(self, *excinfo): + pass + + +if sys.version_info[0] >= 3 and sys.version_info[1] >= 4: + def npy_load_module(name, fn, info=None): + """ + Load a module. + + .. versionadded:: 1.11.2 + + Parameters + ---------- + name : str + Full module name. + fn : str + Path to module file. + info : tuple, optional + Only here for backward compatibility with Python 2.*. + + Returns + ------- + mod : module + + """ + import importlib.machinery + return importlib.machinery.SourceFileLoader(name, fn).load_module() +else: + def npy_load_module(name, fn, info=None): + """ + Load a module. + + .. versionadded:: 1.11.2 + + Parameters + ---------- + name : str + Full module name. + fn : str + Path to module file. + info : tuple, optional + Information as returned by `imp.find_module` + (suffix, mode, type). + + Returns + ------- + mod : module + + """ + import imp + import os + if info is None: + path = os.path.dirname(fn) + fo, fn, info = imp.find_module(name, [path]) + else: + fo = open(fn, info[1]) + try: + mod = imp.load_module(name, fo, fn, info) + finally: + fo.close() + return mod + +# backport abc.ABC +import abc +if sys.version_info[:2] >= (3, 4): + abc_ABC = abc.ABC +else: + abc_ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) + + +# Backport os.fs_path, os.PathLike, and PurePath.__fspath__ +if sys.version_info[:2] >= (3, 6): + import os + os_fspath = os.fspath + os_PathLike = os.PathLike +else: + def _PurePath__fspath__(self): + return str(self) + + class os_PathLike(abc_ABC): + """Abstract base class for implementing the file system path protocol.""" + + @abc.abstractmethod + def __fspath__(self): + """Return the file system path representation of the object.""" + raise NotImplementedError + + @classmethod + def __subclasshook__(cls, subclass): + if PurePath is not None and issubclass(subclass, PurePath): + return True + return hasattr(subclass, '__fspath__') + + + def os_fspath(path): + """Return the path representation of a path-like object. + If str or bytes is passed in, it is returned unchanged. Otherwise the + os.PathLike interface is used to get the path representation. If the + path representation is not str or bytes, TypeError is raised. If the + provided path is not str, bytes, or os.PathLike, TypeError is raised. + """ + if isinstance(path, (unicode, bytes)): + return path + + # Work from the object's type to match method resolution of other magic + # methods. + path_type = type(path) + try: + path_repr = path_type.__fspath__(path) + except AttributeError: + if hasattr(path_type, '__fspath__'): + raise + elif PurePath is not None and issubclass(path_type, PurePath): + return _PurePath__fspath__(path) + else: + raise TypeError("expected str, bytes or os.PathLike object, " + "not " + path_type.__name__) + if isinstance(path_repr, (unicode, bytes)): + return path_repr + else: + raise TypeError("expected {}.__fspath__() to return str or bytes, " + "not {}".format(path_type.__name__, + type(path_repr).__name__)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/setup.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..882857428cdf0dcfa9a4cc386c1e0591ab7f5f91 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/numpy/compat/setup.py @@ -0,0 +1,12 @@ +from __future__ import division, print_function + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + + config = Configuration('compat', parent_package, top_path) + config.add_data_dir('tests') + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(configuration=configuration) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/eval.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..b768ed6df303e724ec7e60fa1268b89c799ce4ac --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/core/computation/eval.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python + +"""Top level ``eval`` module. +""" + +import tokenize +import warnings + +from pandas.compat import string_types +from pandas.util._validators import validate_bool_kwarg + +from pandas.core.computation.engines import _engines +from pandas.core.computation.scope import _ensure_scope + +from pandas.io.formats.printing import pprint_thing + + +def _check_engine(engine): + """Make sure a valid engine is passed. + + Parameters + ---------- + engine : str + + Raises + ------ + KeyError + * If an invalid engine is passed + ImportError + * If numexpr was requested but doesn't exist + + Returns + ------- + string engine + + """ + from pandas.core.computation.check import _NUMEXPR_INSTALLED + + if engine is None: + if _NUMEXPR_INSTALLED: + engine = 'numexpr' + else: + engine = 'python' + + if engine not in _engines: + valid = list(_engines.keys()) + raise KeyError('Invalid engine {engine!r} passed, valid engines are' + ' {valid}'.format(engine=engine, valid=valid)) + + # TODO: validate this in a more general way (thinking of future engines + # that won't necessarily be import-able) + # Could potentially be done on engine instantiation + if engine == 'numexpr': + if not _NUMEXPR_INSTALLED: + raise ImportError("'numexpr' is not installed or an " + "unsupported version. Cannot use " + "engine='numexpr' for query/eval " + "if 'numexpr' is not installed") + + return engine + + +def _check_parser(parser): + """Make sure a valid parser is passed. + + Parameters + ---------- + parser : str + + Raises + ------ + KeyError + * If an invalid parser is passed + """ + from pandas.core.computation.expr import _parsers + + if parser not in _parsers: + raise KeyError('Invalid parser {parser!r} passed, valid parsers are' + ' {valid}'.format(parser=parser, valid=_parsers.keys())) + + +def _check_resolvers(resolvers): + if resolvers is not None: + for resolver in resolvers: + if not hasattr(resolver, '__getitem__'): + name = type(resolver).__name__ + raise TypeError('Resolver of type {name!r} does not implement ' + 'the __getitem__ method'.format(name=name)) + + +def _check_expression(expr): + """Make sure an expression is not an empty string + + Parameters + ---------- + expr : object + An object that can be converted to a string + + Raises + ------ + ValueError + * If expr is an empty string + """ + if not expr: + raise ValueError("expr cannot be an empty string") + + +def _convert_expression(expr): + """Convert an object to an expression. + + Thus function converts an object to an expression (a unicode string) and + checks to make sure it isn't empty after conversion. This is used to + convert operators to their string representation for recursive calls to + :func:`~pandas.eval`. + + Parameters + ---------- + expr : object + The object to be converted to a string. + + Returns + ------- + s : unicode + The string representation of an object. + + Raises + ------ + ValueError + * If the expression is empty. + """ + s = pprint_thing(expr) + _check_expression(s) + return s + + +def _check_for_locals(expr, stack_level, parser): + from pandas.core.computation.expr import tokenize_string + + at_top_of_stack = stack_level == 0 + not_pandas_parser = parser != 'pandas' + + if not_pandas_parser: + msg = "The '@' prefix is only supported by the pandas parser" + elif at_top_of_stack: + msg = ("The '@' prefix is not allowed in " + "top-level eval calls, \nplease refer to " + "your variables by name without the '@' " + "prefix") + + if at_top_of_stack or not_pandas_parser: + for toknum, tokval in tokenize_string(expr): + if toknum == tokenize.OP and tokval == '@': + raise SyntaxError(msg) + + +def eval(expr, parser='pandas', engine=None, truediv=True, + local_dict=None, global_dict=None, resolvers=(), level=0, + target=None, inplace=False): + """Evaluate a Python expression as a string using various backends. + + The following arithmetic operations are supported: ``+``, ``-``, ``*``, + ``/``, ``**``, ``%``, ``//`` (python engine only) along with the following + boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not). + Additionally, the ``'pandas'`` parser allows the use of :keyword:`and`, + :keyword:`or`, and :keyword:`not` with the same semantics as the + corresponding bitwise operators. :class:`~pandas.Series` and + :class:`~pandas.DataFrame` objects are supported and behave as they would + with plain ol' Python evaluation. + + Parameters + ---------- + expr : str or unicode + The expression to evaluate. This string cannot contain any Python + `statements + `__, + only Python `expressions + `__. + parser : string, default 'pandas', {'pandas', 'python'} + The parser to use to construct the syntax tree from the expression. The + default of ``'pandas'`` parses code slightly different than standard + Python. Alternatively, you can parse an expression using the + ``'python'`` parser to retain strict Python semantics. See the + :ref:`enhancing performance ` documentation for + more details. + engine : string or None, default 'numexpr', {'python', 'numexpr'} + + The engine used to evaluate the expression. Supported engines are + + - None : tries to use ``numexpr``, falls back to ``python`` + - ``'numexpr'``: This default engine evaluates pandas objects using + numexpr for large speed ups in complex expressions + with large frames. + - ``'python'``: Performs operations as if you had ``eval``'d in top + level python. This engine is generally not that useful. + + More backends may be available in the future. + + truediv : bool, optional + Whether to use true division, like in Python >= 3 + local_dict : dict or None, optional + A dictionary of local variables, taken from locals() by default. + global_dict : dict or None, optional + A dictionary of global variables, taken from globals() by default. + resolvers : list of dict-like or None, optional + A list of objects implementing the ``__getitem__`` special method that + you can use to inject an additional collection of namespaces to use for + variable lookup. For example, this is used in the + :meth:`~pandas.DataFrame.query` method to inject the + ``DataFrame.index`` and ``DataFrame.columns`` + variables that refer to their respective :class:`~pandas.DataFrame` + instance attributes. + level : int, optional + The number of prior stack frames to traverse and add to the current + scope. Most users will **not** need to change this parameter. + target : object, optional, default None + This is the target object for assignment. It is used when there is + variable assignment in the expression. If so, then `target` must + support item assignment with string keys, and if a copy is being + returned, it must also support `.copy()`. + inplace : bool, default False + If `target` is provided, and the expression mutates `target`, whether + to modify `target` inplace. Otherwise, return a copy of `target` with + the mutation. + + Returns + ------- + ndarray, numeric scalar, DataFrame, Series + + Raises + ------ + ValueError + There are many instances where such an error can be raised: + + - `target=None`, but the expression is multiline. + - The expression is multiline, but not all them have item assignment. + An example of such an arrangement is this: + + a = b + 1 + a + 2 + + Here, there are expressions on different lines, making it multiline, + but the last line has no variable assigned to the output of `a + 2`. + - `inplace=True`, but the expression is missing item assignment. + - Item assignment is provided, but the `target` does not support + string item assignment. + - Item assignment is provided and `inplace=False`, but the `target` + does not support the `.copy()` method + + See Also + -------- + pandas.DataFrame.query + pandas.DataFrame.eval + + Notes + ----- + The ``dtype`` of any objects involved in an arithmetic ``%`` operation are + recursively cast to ``float64``. + + See the :ref:`enhancing performance ` documentation for + more details. + """ + from pandas.core.computation.expr import Expr + + inplace = validate_bool_kwarg(inplace, "inplace") + + if isinstance(expr, string_types): + _check_expression(expr) + exprs = [e.strip() for e in expr.splitlines() if e.strip() != ''] + else: + exprs = [expr] + multi_line = len(exprs) > 1 + + if multi_line and target is None: + raise ValueError("multi-line expressions are only valid in the " + "context of data, use DataFrame.eval") + + ret = None + first_expr = True + target_modified = False + + for expr in exprs: + expr = _convert_expression(expr) + engine = _check_engine(engine) + _check_parser(parser) + _check_resolvers(resolvers) + _check_for_locals(expr, level, parser) + + # get our (possibly passed-in) scope + env = _ensure_scope(level + 1, global_dict=global_dict, + local_dict=local_dict, resolvers=resolvers, + target=target) + + parsed_expr = Expr(expr, engine=engine, parser=parser, env=env, + truediv=truediv) + + # construct the engine and evaluate the parsed expression + eng = _engines[engine] + eng_inst = eng(parsed_expr) + ret = eng_inst.evaluate() + + if parsed_expr.assigner is None: + if multi_line: + raise ValueError("Multi-line expressions are only valid" + " if all expressions contain an assignment") + elif inplace: + raise ValueError("Cannot operate inplace " + "if there is no assignment") + + # assign if needed + assigner = parsed_expr.assigner + if env.target is not None and assigner is not None: + target_modified = True + + # if returning a copy, copy only on the first assignment + if not inplace and first_expr: + try: + target = env.target.copy() + except AttributeError: + raise ValueError("Cannot return a copy of the target") + else: + target = env.target + + # TypeError is most commonly raised (e.g. int, list), but you + # get IndexError if you try to do this assignment on np.ndarray. + # we will ignore numpy warnings here; e.g. if trying + # to use a non-numeric indexer + try: + with warnings.catch_warnings(record=True): + # TODO: Filter the warnings we actually care about here. + target[assigner] = ret + except (TypeError, IndexError): + raise ValueError("Cannot assign expression output to target") + + if not resolvers: + resolvers = ({assigner: ret},) + else: + # existing resolver needs updated to handle + # case of mutating existing column in copy + for resolver in resolvers: + if assigner in resolver: + resolver[assigner] = ret + break + else: + resolvers += ({assigner: ret},) + + ret = None + first_expr = False + + # We want to exclude `inplace=None` as being False. + if inplace is False: + return target if target_modified else ret diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/clipboard/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/clipboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b76a843e3e7f2f20964f77a2b7ddb8eb9d734bbe --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/clipboard/__init__.py @@ -0,0 +1,125 @@ +""" +Pyperclip + +A cross-platform clipboard module for Python. (only handles plain text for now) +By Al Sweigart al@inventwithpython.com +BSD License + +Usage: + import pyperclip + pyperclip.copy('The text to be copied to the clipboard.') + spam = pyperclip.paste() + + if not pyperclip.copy: + print("Copy functionality unavailable!") + +On Windows, no additional modules are needed. +On Mac, the module uses pbcopy and pbpaste, which should come with the os. +On Linux, install xclip or xsel via package manager. For example, in Debian: +sudo apt-get install xclip + +Otherwise on Linux, you will need the gtk, qtpy or PyQt modules installed. +qtpy also requires a python-qt-bindings module: PyQt4, PyQt5, PySide, PySide2 + +gtk and PyQt4 modules are not available for Python 3, +and this module does not work with PyGObject yet. +""" +__version__ = '1.5.27' + +import platform +import os +import subprocess +from .clipboards import (init_osx_clipboard, + init_gtk_clipboard, init_qt_clipboard, + init_xclip_clipboard, init_xsel_clipboard, + init_klipper_clipboard, init_no_clipboard) +from .windows import init_windows_clipboard + +# `import qtpy` sys.exit()s if DISPLAY is not in the environment. +# Thus, we need to detect the presence of $DISPLAY manually +# and not load qtpy if it is absent. +HAS_DISPLAY = os.getenv("DISPLAY", False) +CHECK_CMD = "where" if platform.system() == "Windows" else "which" + + +def _executable_exists(name): + return subprocess.call([CHECK_CMD, name], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 + + +def determine_clipboard(): + # Determine the OS/platform and set + # the copy() and paste() functions accordingly. + if 'cygwin' in platform.system().lower(): + # FIXME: pyperclip currently does not support Cygwin, + # see https://github.com/asweigart/pyperclip/issues/55 + pass + elif os.name == 'nt' or platform.system() == 'Windows': + return init_windows_clipboard() + if os.name == 'mac' or platform.system() == 'Darwin': + return init_osx_clipboard() + if HAS_DISPLAY: + # Determine which command/module is installed, if any. + try: + # Check if gtk is installed + import gtk # noqa + except ImportError: + pass + else: + return init_gtk_clipboard() + + try: + # qtpy is a small abstraction layer that lets you write + # applications using a single api call to either PyQt or PySide + # https://pypi.org/project/QtPy + import qtpy # noqa + except ImportError: + # If qtpy isn't installed, fall back on importing PyQt5, or PyQt5 + try: + import PyQt5 # noqa + except ImportError: + try: + import PyQt4 # noqa + except ImportError: + pass # fail fast for all non-ImportError exceptions. + else: + return init_qt_clipboard() + else: + return init_qt_clipboard() + pass + else: + return init_qt_clipboard() + + if _executable_exists("xclip"): + return init_xclip_clipboard() + if _executable_exists("xsel"): + return init_xsel_clipboard() + if _executable_exists("klipper") and _executable_exists("qdbus"): + return init_klipper_clipboard() + + return init_no_clipboard() + + +def set_clipboard(clipboard): + global copy, paste + + clipboard_types = {'osx': init_osx_clipboard, + 'gtk': init_gtk_clipboard, + 'qt': init_qt_clipboard, + 'xclip': init_xclip_clipboard, + 'xsel': init_xsel_clipboard, + 'klipper': init_klipper_clipboard, + 'windows': init_windows_clipboard, + 'no': init_no_clipboard} + + copy, paste = clipboard_types[clipboard]() + + +copy, paste = determine_clipboard() + +__all__ = ["copy", "paste"] + + +# pandas aliases +clipboard_get = paste +clipboard_set = copy diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/console.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/console.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ef9f61bc132867ae21c35587e99d83f8d97ceb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/console.py @@ -0,0 +1,159 @@ +""" +Internal module for console introspection +""" + +import locale +import sys + +from pandas.io.formats.terminal import get_terminal_size + +# ----------------------------------------------------------------------------- +# Global formatting options +_initial_defencoding = None + + +def detect_console_encoding(): + """ + Try to find the most capable encoding supported by the console. + slightly modified from the way IPython handles the same issue. + """ + global _initial_defencoding + + encoding = None + try: + encoding = sys.stdout.encoding or sys.stdin.encoding + except (AttributeError, IOError): + pass + + # try again for something better + if not encoding or 'ascii' in encoding.lower(): + try: + encoding = locale.getpreferredencoding() + except Exception: + pass + + # when all else fails. this will usually be "ascii" + if not encoding or 'ascii' in encoding.lower(): + encoding = sys.getdefaultencoding() + + # GH3360, save the reported defencoding at import time + # MPL backends may change it. Make available for debugging. + if not _initial_defencoding: + _initial_defencoding = sys.getdefaultencoding() + + return encoding + + +def get_console_size(): + """Return console size as tuple = (width, height). + + Returns (None,None) in non-interactive session. + """ + from pandas import get_option + + display_width = get_option('display.width') + # deprecated. + display_height = get_option('display.max_rows') + + # Consider + # interactive shell terminal, can detect term size + # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term + # size non-interactive script, should disregard term size + + # in addition + # width,height have default values, but setting to 'None' signals + # should use Auto-Detection, But only in interactive shell-terminal. + # Simple. yeah. + + if in_interactive_session(): + if in_ipython_frontend(): + # sane defaults for interactive non-shell terminal + # match default for width,height in config_init + from pandas.core.config import get_default_val + terminal_width = get_default_val('display.width') + terminal_height = get_default_val('display.max_rows') + else: + # pure terminal + terminal_width, terminal_height = get_terminal_size() + else: + terminal_width, terminal_height = None, None + + # Note if the User sets width/Height to None (auto-detection) + # and we're in a script (non-inter), this will return (None,None) + # caller needs to deal. + return (display_width or terminal_width, display_height or terminal_height) + + +# ---------------------------------------------------------------------- +# Detect our environment + +def in_interactive_session(): + """ check if we're running in an interactive shell + + returns True if running under python/ipython interactive shell + """ + from pandas import get_option + + def check_main(): + try: + import __main__ as main + except ModuleNotFoundError: + return get_option('mode.sim_interactive') + return (not hasattr(main, '__file__') or + get_option('mode.sim_interactive')) + + try: + return __IPYTHON__ or check_main() # noqa + except NameError: + return check_main() + + +def in_qtconsole(): + """ + check if we're inside an IPython qtconsole + + .. deprecated:: 0.14.1 + This is no longer needed, or working, in IPython 3 and above. + """ + try: + ip = get_ipython() # noqa + front_end = ( + ip.config.get('KernelApp', {}).get('parent_appname', "") or + ip.config.get('IPKernelApp', {}).get('parent_appname', "")) + if 'qtconsole' in front_end.lower(): + return True + except NameError: + return False + return False + + +def in_ipnb(): + """ + check if we're inside an IPython Notebook + + .. deprecated:: 0.14.1 + This is no longer needed, or working, in IPython 3 and above. + """ + try: + ip = get_ipython() # noqa + front_end = ( + ip.config.get('KernelApp', {}).get('parent_appname', "") or + ip.config.get('IPKernelApp', {}).get('parent_appname', "")) + if 'notebook' in front_end.lower(): + return True + except NameError: + return False + return False + + +def in_ipython_frontend(): + """ + check if we're inside an an IPython zmq frontend + """ + try: + ip = get_ipython() # noqa + return 'zmq' in str(type(ip)).lower() + except NameError: + pass + + return False diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/css.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/css.py new file mode 100644 index 0000000000000000000000000000000000000000..429c98b579ca09323d94fefb3f19edc183e4ee9b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/css.py @@ -0,0 +1,250 @@ +"""Utilities for interpreting CSS from Stylers for formatting non-HTML outputs +""" + +import re +import warnings + + +class CSSWarning(UserWarning): + """This CSS syntax cannot currently be parsed""" + pass + + +class CSSResolver(object): + """A callable for parsing and resolving CSS to atomic properties + + """ + + INITIAL_STYLE = { + } + + def __call__(self, declarations_str, inherited=None): + """ the given declarations to atomic properties + + Parameters + ---------- + declarations_str : str + A list of CSS declarations + inherited : dict, optional + Atomic properties indicating the inherited style context in which + declarations_str is to be resolved. ``inherited`` should already + be resolved, i.e. valid output of this method. + + Returns + ------- + props : dict + Atomic CSS 2.2 properties + + Examples + -------- + >>> resolve = CSSResolver() + >>> inherited = {'font-family': 'serif', 'font-weight': 'bold'} + >>> out = resolve(''' + ... border-color: BLUE RED; + ... font-size: 1em; + ... font-size: 2em; + ... font-weight: normal; + ... font-weight: inherit; + ... ''', inherited) + >>> sorted(out.items()) # doctest: +NORMALIZE_WHITESPACE + [('border-bottom-color', 'blue'), + ('border-left-color', 'red'), + ('border-right-color', 'red'), + ('border-top-color', 'blue'), + ('font-family', 'serif'), + ('font-size', '24pt'), + ('font-weight', 'bold')] + """ + + props = dict(self.atomize(self.parse(declarations_str))) + if inherited is None: + inherited = {} + + # 1. resolve inherited, initial + for prop, val in inherited.items(): + if prop not in props: + props[prop] = val + + for prop, val in list(props.items()): + if val == 'inherit': + val = inherited.get(prop, 'initial') + if val == 'initial': + val = self.INITIAL_STYLE.get(prop) + + if val is None: + # we do not define a complete initial stylesheet + del props[prop] + else: + props[prop] = val + + # 2. resolve relative font size + if props.get('font-size'): + if 'font-size' in inherited: + em_pt = inherited['font-size'] + assert em_pt[-2:] == 'pt' + em_pt = float(em_pt[:-2]) + else: + em_pt = None + props['font-size'] = self.size_to_pt( + props['font-size'], em_pt, conversions=self.FONT_SIZE_RATIOS) + + font_size = float(props['font-size'][:-2]) + else: + font_size = None + + # 3. TODO: resolve other font-relative units + for side in self.SIDES: + prop = 'border-{side}-width'.format(side=side) + if prop in props: + props[prop] = self.size_to_pt( + props[prop], em_pt=font_size, + conversions=self.BORDER_WIDTH_RATIOS) + for prop in ['margin-{side}'.format(side=side), + 'padding-{side}'.format(side=side)]: + if prop in props: + # TODO: support % + props[prop] = self.size_to_pt( + props[prop], em_pt=font_size, + conversions=self.MARGIN_RATIOS) + + return props + + UNIT_RATIOS = { + 'rem': ('pt', 12), + 'ex': ('em', .5), + # 'ch': + 'px': ('pt', .75), + 'pc': ('pt', 12), + 'in': ('pt', 72), + 'cm': ('in', 1 / 2.54), + 'mm': ('in', 1 / 25.4), + 'q': ('mm', .25), + '!!default': ('em', 0), + } + + FONT_SIZE_RATIOS = UNIT_RATIOS.copy() + FONT_SIZE_RATIOS.update({ + '%': ('em', .01), + 'xx-small': ('rem', .5), + 'x-small': ('rem', .625), + 'small': ('rem', .8), + 'medium': ('rem', 1), + 'large': ('rem', 1.125), + 'x-large': ('rem', 1.5), + 'xx-large': ('rem', 2), + 'smaller': ('em', 1 / 1.2), + 'larger': ('em', 1.2), + '!!default': ('em', 1), + }) + + MARGIN_RATIOS = UNIT_RATIOS.copy() + MARGIN_RATIOS.update({ + 'none': ('pt', 0), + }) + + BORDER_WIDTH_RATIOS = UNIT_RATIOS.copy() + BORDER_WIDTH_RATIOS.update({ + 'none': ('pt', 0), + 'thick': ('px', 4), + 'medium': ('px', 2), + 'thin': ('px', 1), + # Default: medium only if solid + }) + + def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS): + def _error(): + warnings.warn('Unhandled size: {val!r}'.format(val=in_val), + CSSWarning) + return self.size_to_pt('1!!default', conversions=conversions) + + try: + val, unit = re.match(r'^(\S*?)([a-zA-Z%!].*)', in_val).groups() + except AttributeError: + return _error() + if val == '': + # hack for 'large' etc. + val = 1 + else: + try: + val = float(val) + except ValueError: + return _error() + + while unit != 'pt': + if unit == 'em': + if em_pt is None: + unit = 'rem' + else: + val *= em_pt + unit = 'pt' + continue + + try: + unit, mul = conversions[unit] + except KeyError: + return _error() + val *= mul + + val = round(val, 5) + if int(val) == val: + size_fmt = '{fmt:d}pt'.format(fmt=int(val)) + else: + size_fmt = '{fmt:f}pt'.format(fmt=val) + return size_fmt + + def atomize(self, declarations): + for prop, value in declarations: + attr = 'expand_' + prop.replace('-', '_') + try: + expand = getattr(self, attr) + except AttributeError: + yield prop, value + else: + for prop, value in expand(prop, value): + yield prop, value + + SIDE_SHORTHANDS = { + 1: [0, 0, 0, 0], + 2: [0, 1, 0, 1], + 3: [0, 1, 2, 1], + 4: [0, 1, 2, 3], + } + SIDES = ('top', 'right', 'bottom', 'left') + + def _side_expander(prop_fmt): + def expand(self, prop, value): + tokens = value.split() + try: + mapping = self.SIDE_SHORTHANDS[len(tokens)] + except KeyError: + warnings.warn('Could not expand "{prop}: {val}"' + .format(prop=prop, val=value), CSSWarning) + return + for key, idx in zip(self.SIDES, mapping): + yield prop_fmt.format(key), tokens[idx] + + return expand + + expand_border_color = _side_expander('border-{:s}-color') + expand_border_style = _side_expander('border-{:s}-style') + expand_border_width = _side_expander('border-{:s}-width') + expand_margin = _side_expander('margin-{:s}') + expand_padding = _side_expander('padding-{:s}') + + def parse(self, declarations_str): + """Generates (prop, value) pairs from declarations + + In a future version may generate parsed tokens from tinycss/tinycss2 + """ + for decl in declarations_str.split(';'): + if not decl.strip(): + continue + prop, sep, val = decl.partition(':') + prop = prop.strip().lower() + # TODO: don't lowercase case sensitive parts of values (strings) + val = val.strip().lower() + if sep: + yield prop, val + else: + warnings.warn('Ill-formatted attribute: expected a colon ' + 'in {decl!r}'.format(decl=decl), CSSWarning) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/csvs.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/csvs.py new file mode 100644 index 0000000000000000000000000000000000000000..46c843af043e7394f5afcda45980d7d707abe158 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/csvs.py @@ -0,0 +1,315 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data into CSV files. +""" + +from __future__ import print_function + +import csv as csvlib +import os +import warnings +from zipfile import ZipFile + +import numpy as np + +from pandas._libs import writers as libwriters +from pandas.compat import StringIO, range, zip + +from pandas.core.dtypes.generic import ( + ABCDatetimeIndex, ABCIndexClass, ABCMultiIndex, ABCPeriodIndex) +from pandas.core.dtypes.missing import notna + +from pandas import compat + +from pandas.io.common import ( + UnicodeWriter, _get_handle, _infer_compression, get_filepath_or_buffer) + + +class CSVFormatter(object): + + def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', + float_format=None, cols=None, header=True, index=True, + index_label=None, mode='w', nanRep=None, encoding=None, + compression='infer', quoting=None, line_terminator='\n', + chunksize=None, tupleize_cols=False, quotechar='"', + date_format=None, doublequote=True, escapechar=None, + decimal='.'): + + self.obj = obj + + if path_or_buf is None: + path_or_buf = StringIO() + + self.path_or_buf, _, _, _ = get_filepath_or_buffer( + path_or_buf, encoding=encoding, compression=compression, mode=mode + ) + self.sep = sep + self.na_rep = na_rep + self.float_format = float_format + self.decimal = decimal + + self.header = header + self.index = index + self.index_label = index_label + self.mode = mode + if encoding is None: + encoding = 'ascii' if compat.PY2 else 'utf-8' + self.encoding = encoding + self.compression = _infer_compression(self.path_or_buf, compression) + + if quoting is None: + quoting = csvlib.QUOTE_MINIMAL + self.quoting = quoting + + if quoting == csvlib.QUOTE_NONE: + # prevents crash in _csv + quotechar = None + self.quotechar = quotechar + + self.doublequote = doublequote + self.escapechar = escapechar + + self.line_terminator = line_terminator or os.linesep + + self.date_format = date_format + + self.tupleize_cols = tupleize_cols + self.has_mi_columns = (isinstance(obj.columns, ABCMultiIndex) and + not self.tupleize_cols) + + # validate mi options + if self.has_mi_columns: + if cols is not None: + raise TypeError("cannot specify cols with a MultiIndex on the " + "columns") + + if cols is not None: + if isinstance(cols, ABCIndexClass): + cols = cols.to_native_types(na_rep=na_rep, + float_format=float_format, + date_format=date_format, + quoting=self.quoting) + else: + cols = list(cols) + self.obj = self.obj.loc[:, cols] + + # update columns to include possible multiplicity of dupes + # and make sure sure cols is just a list of labels + cols = self.obj.columns + if isinstance(cols, ABCIndexClass): + cols = cols.to_native_types(na_rep=na_rep, + float_format=float_format, + date_format=date_format, + quoting=self.quoting) + else: + cols = list(cols) + + # save it + self.cols = cols + + # preallocate data 2d list + self.blocks = self.obj._data.blocks + ncols = sum(b.shape[0] for b in self.blocks) + self.data = [None] * ncols + + if chunksize is None: + chunksize = (100000 // (len(self.cols) or 1)) or 1 + self.chunksize = int(chunksize) + + self.data_index = obj.index + if (isinstance(self.data_index, (ABCDatetimeIndex, ABCPeriodIndex)) and + date_format is not None): + from pandas import Index + self.data_index = Index([x.strftime(date_format) if notna(x) else + '' for x in self.data_index]) + + self.nlevels = getattr(self.data_index, 'nlevels', 1) + if not index: + self.nlevels = 0 + + def save(self): + """ + Create the writer & save + """ + # GH21227 internal compression is not used when file-like passed. + if self.compression and hasattr(self.path_or_buf, 'write'): + msg = ("compression has no effect when passing file-like " + "object as input.") + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + # when zip compression is called. + is_zip = isinstance(self.path_or_buf, ZipFile) or ( + not hasattr(self.path_or_buf, 'write') + and self.compression == 'zip') + + if is_zip: + # zipfile doesn't support writing string to archive. uses string + # buffer to receive csv writing and dump into zip compression + # file handle. GH21241, GH21118 + f = StringIO() + close = False + elif hasattr(self.path_or_buf, 'write'): + f = self.path_or_buf + close = False + else: + f, handles = _get_handle(self.path_or_buf, self.mode, + encoding=self.encoding, + compression=self.compression) + close = True + + try: + writer_kwargs = dict(lineterminator=self.line_terminator, + delimiter=self.sep, quoting=self.quoting, + doublequote=self.doublequote, + escapechar=self.escapechar, + quotechar=self.quotechar) + if self.encoding == 'ascii': + self.writer = csvlib.writer(f, **writer_kwargs) + else: + writer_kwargs['encoding'] = self.encoding + self.writer = UnicodeWriter(f, **writer_kwargs) + + self._save() + + finally: + if is_zip: + # GH17778 handles zip compression separately. + buf = f.getvalue() + if hasattr(self.path_or_buf, 'write'): + self.path_or_buf.write(buf) + else: + f, handles = _get_handle(self.path_or_buf, self.mode, + encoding=self.encoding, + compression=self.compression) + f.write(buf) + close = True + if close: + f.close() + for _fh in handles: + _fh.close() + + def _save_header(self): + + writer = self.writer + obj = self.obj + index_label = self.index_label + cols = self.cols + has_mi_columns = self.has_mi_columns + header = self.header + encoded_labels = [] + + has_aliases = isinstance(header, (tuple, list, np.ndarray, + ABCIndexClass)) + if not (has_aliases or self.header): + return + if has_aliases: + if len(header) != len(cols): + raise ValueError(('Writing {ncols} cols but got {nalias} ' + 'aliases'.format(ncols=len(cols), + nalias=len(header)))) + else: + write_cols = header + else: + write_cols = cols + + if self.index: + # should write something for index label + if index_label is not False: + if index_label is None: + if isinstance(obj.index, ABCMultiIndex): + index_label = [] + for i, name in enumerate(obj.index.names): + if name is None: + name = '' + index_label.append(name) + else: + index_label = obj.index.name + if index_label is None: + index_label = [''] + else: + index_label = [index_label] + elif not isinstance(index_label, + (list, tuple, np.ndarray, ABCIndexClass)): + # given a string for a DF with Index + index_label = [index_label] + + encoded_labels = list(index_label) + else: + encoded_labels = [] + + if not has_mi_columns or has_aliases: + encoded_labels += list(write_cols) + writer.writerow(encoded_labels) + else: + # write out the mi + columns = obj.columns + + # write out the names for each level, then ALL of the values for + # each level + for i in range(columns.nlevels): + + # we need at least 1 index column to write our col names + col_line = [] + if self.index: + + # name is the first column + col_line.append(columns.names[i]) + + if isinstance(index_label, list) and len(index_label) > 1: + col_line.extend([''] * (len(index_label) - 1)) + + col_line.extend(columns._get_level_values(i)) + + writer.writerow(col_line) + + # Write out the index line if it's not empty. + # Otherwise, we will print out an extraneous + # blank line between the mi and the data rows. + if encoded_labels and set(encoded_labels) != {''}: + encoded_labels.extend([''] * len(columns)) + writer.writerow(encoded_labels) + + def _save(self): + + self._save_header() + + nrows = len(self.data_index) + + # write in chunksize bites + chunksize = self.chunksize + chunks = int(nrows / chunksize) + 1 + + for i in range(chunks): + start_i = i * chunksize + end_i = min((i + 1) * chunksize, nrows) + if start_i >= end_i: + break + + self._save_chunk(start_i, end_i) + + def _save_chunk(self, start_i, end_i): + + data_index = self.data_index + + # create the data for a chunk + slicer = slice(start_i, end_i) + for i in range(len(self.blocks)): + b = self.blocks[i] + d = b.to_native_types(slicer=slicer, na_rep=self.na_rep, + float_format=self.float_format, + decimal=self.decimal, + date_format=self.date_format, + quoting=self.quoting) + + for col_loc, col in zip(b.mgr_locs, d): + # self.data is a preallocated list + self.data[col_loc] = col + + ix = data_index.to_native_types(slicer=slicer, na_rep=self.na_rep, + float_format=self.float_format, + decimal=self.decimal, + date_format=self.date_format, + quoting=self.quoting) + + libwriters.write_csv_rows(self.data, ix, self.nlevels, + self.cols, self.writer) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/excel.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/excel.py new file mode 100644 index 0000000000000000000000000000000000000000..d74722996a660c9cab4a48846b1f2c8ffb391ca9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/excel.py @@ -0,0 +1,664 @@ +"""Utilities for conversion to writer-agnostic Excel representation +""" + +import itertools +import re +import warnings + +import numpy as np + +from pandas.compat import reduce + +from pandas.core.dtypes import missing +from pandas.core.dtypes.common import is_float, is_scalar +from pandas.core.dtypes.generic import ABCMultiIndex, ABCPeriodIndex + +from pandas import Index +import pandas.core.common as com + +from pandas.io.formats.css import CSSResolver, CSSWarning +from pandas.io.formats.format import get_level_lengths +from pandas.io.formats.printing import pprint_thing + + +class ExcelCell(object): + __fields__ = ('row', 'col', 'val', 'style', 'mergestart', 'mergeend') + __slots__ = __fields__ + + def __init__(self, row, col, val, style=None, mergestart=None, + mergeend=None): + self.row = row + self.col = col + self.val = val + self.style = style + self.mergestart = mergestart + self.mergeend = mergeend + + +class CSSToExcelConverter(object): + """A callable for converting CSS declarations to ExcelWriter styles + + Supports parts of CSS 2.2, with minimal CSS 3.0 support (e.g. text-shadow), + focusing on font styling, backgrounds, borders and alignment. + + Operates by first computing CSS styles in a fairly generic + way (see :meth:`compute_css`) then determining Excel style + properties from CSS properties (see :meth:`build_xlstyle`). + + Parameters + ---------- + inherited : str, optional + CSS declarations understood to be the containing scope for the + CSS processed by :meth:`__call__`. + """ + # NB: Most of the methods here could be classmethods, as only __init__ + # and __call__ make use of instance attributes. We leave them as + # instancemethods so that users can easily experiment with extensions + # without monkey-patching. + + def __init__(self, inherited=None): + if inherited is not None: + inherited = self.compute_css(inherited, + self.compute_css.INITIAL_STYLE) + + self.inherited = inherited + + compute_css = CSSResolver() + + def __call__(self, declarations_str): + """Convert CSS declarations to ExcelWriter style + + Parameters + ---------- + declarations_str : str + List of CSS declarations. + e.g. "font-weight: bold; background: blue" + + Returns + ------- + xlstyle : dict + A style as interpreted by ExcelWriter when found in + ExcelCell.style. + """ + # TODO: memoize? + properties = self.compute_css(declarations_str, self.inherited) + return self.build_xlstyle(properties) + + def build_xlstyle(self, props): + out = { + 'alignment': self.build_alignment(props), + 'border': self.build_border(props), + 'fill': self.build_fill(props), + 'font': self.build_font(props), + 'number_format': self.build_number_format(props), + } + # TODO: handle cell width and height: needs support in pandas.io.excel + + def remove_none(d): + """Remove key where value is None, through nested dicts""" + for k, v in list(d.items()): + if v is None: + del d[k] + elif isinstance(v, dict): + remove_none(v) + if not v: + del d[k] + + remove_none(out) + return out + + VERTICAL_MAP = { + 'top': 'top', + 'text-top': 'top', + 'middle': 'center', + 'baseline': 'bottom', + 'bottom': 'bottom', + 'text-bottom': 'bottom', + # OpenXML also has 'justify', 'distributed' + } + + def build_alignment(self, props): + # TODO: text-indent, padding-left -> alignment.indent + return {'horizontal': props.get('text-align'), + 'vertical': self.VERTICAL_MAP.get(props.get('vertical-align')), + 'wrap_text': (None if props.get('white-space') is None else + props['white-space'] not in + ('nowrap', 'pre', 'pre-line')) + } + + def build_border(self, props): + return {side: { + 'style': self._border_style(props.get('border-{side}-style' + .format(side=side)), + props.get('border-{side}-width' + .format(side=side))), + 'color': self.color_to_excel( + props.get('border-{side}-color'.format(side=side))), + } for side in ['top', 'right', 'bottom', 'left']} + + def _border_style(self, style, width): + # convert styles and widths to openxml, one of: + # 'dashDot' + # 'dashDotDot' + # 'dashed' + # 'dotted' + # 'double' + # 'hair' + # 'medium' + # 'mediumDashDot' + # 'mediumDashDotDot' + # 'mediumDashed' + # 'slantDashDot' + # 'thick' + # 'thin' + if width is None and style is None: + return None + if style == 'none' or style == 'hidden': + return None + + if width is None: + width = '2pt' + width = float(width[:-2]) + if width < 1e-5: + return None + elif width < 1.3: + width_name = 'thin' + elif width < 2.8: + width_name = 'medium' + else: + width_name = 'thick' + + if style in (None, 'groove', 'ridge', 'inset', 'outset'): + # not handled + style = 'solid' + + if style == 'double': + return 'double' + if style == 'solid': + return width_name + if style == 'dotted': + if width_name in ('hair', 'thin'): + return 'dotted' + return 'mediumDashDotDot' + if style == 'dashed': + if width_name in ('hair', 'thin'): + return 'dashed' + return 'mediumDashed' + + def build_fill(self, props): + # TODO: perhaps allow for special properties + # -excel-pattern-bgcolor and -excel-pattern-type + fill_color = props.get('background-color') + if fill_color not in (None, 'transparent', 'none'): + return { + 'fgColor': self.color_to_excel(fill_color), + 'patternType': 'solid', + } + + BOLD_MAP = {'bold': True, 'bolder': True, '600': True, '700': True, + '800': True, '900': True, + 'normal': False, 'lighter': False, '100': False, '200': False, + '300': False, '400': False, '500': False} + ITALIC_MAP = {'normal': False, 'italic': True, 'oblique': True} + + def build_font(self, props): + size = props.get('font-size') + if size is not None: + assert size.endswith('pt') + size = float(size[:-2]) + + font_names_tmp = re.findall(r'''(?x) + ( + "(?:[^"]|\\")+" + | + '(?:[^']|\\')+' + | + [^'",]+ + )(?=,|\s*$) + ''', props.get('font-family', '')) + font_names = [] + for name in font_names_tmp: + if name[:1] == '"': + name = name[1:-1].replace('\\"', '"') + elif name[:1] == '\'': + name = name[1:-1].replace('\\\'', '\'') + else: + name = name.strip() + if name: + font_names.append(name) + + family = None + for name in font_names: + if name == 'serif': + family = 1 # roman + break + elif name == 'sans-serif': + family = 2 # swiss + break + elif name == 'cursive': + family = 4 # script + break + elif name == 'fantasy': + family = 5 # decorative + break + + decoration = props.get('text-decoration') + if decoration is not None: + decoration = decoration.split() + else: + decoration = () + + return { + 'name': font_names[0] if font_names else None, + 'family': family, + 'size': size, + 'bold': self.BOLD_MAP.get(props.get('font-weight')), + 'italic': self.ITALIC_MAP.get(props.get('font-style')), + 'underline': ('single' if + 'underline' in decoration + else None), + 'strike': ('line-through' in decoration) or None, + 'color': self.color_to_excel(props.get('color')), + # shadow if nonzero digit before shadow color + 'shadow': (bool(re.search('^[^#(]*[1-9]', + props['text-shadow'])) + if 'text-shadow' in props else None), + # 'vertAlign':, + # 'charset': , + # 'scheme': , + # 'outline': , + # 'condense': , + } + + NAMED_COLORS = { + 'maroon': '800000', + 'brown': 'A52A2A', + 'red': 'FF0000', + 'pink': 'FFC0CB', + 'orange': 'FFA500', + 'yellow': 'FFFF00', + 'olive': '808000', + 'green': '008000', + 'purple': '800080', + 'fuchsia': 'FF00FF', + 'lime': '00FF00', + 'teal': '008080', + 'aqua': '00FFFF', + 'blue': '0000FF', + 'navy': '000080', + 'black': '000000', + 'gray': '808080', + 'grey': '808080', + 'silver': 'C0C0C0', + 'white': 'FFFFFF', + } + + def color_to_excel(self, val): + if val is None: + return None + if val.startswith('#') and len(val) == 7: + return val[1:].upper() + if val.startswith('#') and len(val) == 4: + return (val[1] * 2 + val[2] * 2 + val[3] * 2).upper() + try: + return self.NAMED_COLORS[val] + except KeyError: + warnings.warn('Unhandled color format: {val!r}'.format(val=val), + CSSWarning) + + def build_number_format(self, props): + return {'format_code': props.get('number-format')} + + +class ExcelFormatter(object): + """ + Class for formatting a DataFrame to a list of ExcelCells, + + Parameters + ---------- + df : DataFrame or Styler + na_rep: na representation + float_format : string, default None + Format string for floating point numbers + cols : sequence, optional + Columns to write + header : boolean or list of string, default True + Write out column names. If a list of string is given it is + assumed to be aliases for the column names + index : boolean, default True + output row names (index) + index_label : string or sequence, default None + Column label for index column(s) if desired. If None is given, and + `header` and `index` are True, then the index names are used. A + sequence should be given if the DataFrame uses MultiIndex. + merge_cells : boolean, default False + Format MultiIndex and Hierarchical Rows as merged cells. + inf_rep : string, default `'inf'` + representation for np.inf values (which aren't representable in Excel) + A `'-'` sign will be added in front of -inf. + style_converter : callable, optional + This translates Styler styles (CSS) into ExcelWriter styles. + Defaults to ``CSSToExcelConverter()``. + It should have signature css_declarations string -> excel style. + This is only called for body cells. + """ + + def __init__(self, df, na_rep='', float_format=None, cols=None, + header=True, index=True, index_label=None, merge_cells=False, + inf_rep='inf', style_converter=None): + self.rowcounter = 0 + self.na_rep = na_rep + if hasattr(df, 'render'): + self.styler = df + df = df.data + if style_converter is None: + style_converter = CSSToExcelConverter() + self.style_converter = style_converter + else: + self.styler = None + self.df = df + if cols is not None: + + # all missing, raise + if not len(Index(cols) & df.columns): + raise KeyError( + "passes columns are not ALL present dataframe") + + # deprecatedin gh-17295 + # 1 missing is ok (for now) + if len(Index(cols) & df.columns) != len(cols): + warnings.warn( + "Not all names specified in 'columns' are found; " + "this will raise a KeyError in the future", + FutureWarning) + + self.df = df.reindex(columns=cols) + self.columns = self.df.columns + self.float_format = float_format + self.index = index + self.index_label = index_label + self.header = header + self.merge_cells = merge_cells + self.inf_rep = inf_rep + + @property + def header_style(self): + return {"font": {"bold": True}, + "borders": {"top": "thin", + "right": "thin", + "bottom": "thin", + "left": "thin"}, + "alignment": {"horizontal": "center", + "vertical": "top"}} + + def _format_value(self, val): + if is_scalar(val) and missing.isna(val): + val = self.na_rep + elif is_float(val): + if missing.isposinf_scalar(val): + val = self.inf_rep + elif missing.isneginf_scalar(val): + val = '-{inf}'.format(inf=self.inf_rep) + elif self.float_format is not None: + val = float(self.float_format % val) + return val + + def _format_header_mi(self): + if self.columns.nlevels > 1: + if not self.index: + raise NotImplementedError("Writing to Excel with MultiIndex" + " columns and no index " + "('index'=False) is not yet " + "implemented.") + + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) + if not (has_aliases or self.header): + return + + columns = self.columns + level_strs = columns.format(sparsify=self.merge_cells, adjoin=False, + names=False) + level_lengths = get_level_lengths(level_strs) + coloffset = 0 + lnum = 0 + + if self.index and isinstance(self.df.index, ABCMultiIndex): + coloffset = len(self.df.index[0]) - 1 + + if self.merge_cells: + # Format multi-index as a merged cells. + for lnum in range(len(level_lengths)): + name = columns.names[lnum] + yield ExcelCell(lnum, coloffset, name, self.header_style) + + for lnum, (spans, levels, level_codes) in enumerate(zip( + level_lengths, columns.levels, columns.codes)): + values = levels.take(level_codes) + for i in spans: + if spans[i] > 1: + yield ExcelCell(lnum, coloffset + i + 1, values[i], + self.header_style, lnum, + coloffset + i + spans[i]) + else: + yield ExcelCell(lnum, coloffset + i + 1, values[i], + self.header_style) + else: + # Format in legacy format with dots to indicate levels. + for i, values in enumerate(zip(*level_strs)): + v = ".".join(map(pprint_thing, values)) + yield ExcelCell(lnum, coloffset + i + 1, v, self.header_style) + + self.rowcounter = lnum + + def _format_header_regular(self): + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) + if has_aliases or self.header: + coloffset = 0 + + if self.index: + coloffset = 1 + if isinstance(self.df.index, ABCMultiIndex): + coloffset = len(self.df.index[0]) + + colnames = self.columns + if has_aliases: + if len(self.header) != len(self.columns): + raise ValueError('Writing {cols} cols but got {alias} ' + 'aliases'.format(cols=len(self.columns), + alias=len(self.header))) + else: + colnames = self.header + + for colindex, colname in enumerate(colnames): + yield ExcelCell(self.rowcounter, colindex + coloffset, colname, + self.header_style) + + def _format_header(self): + if isinstance(self.columns, ABCMultiIndex): + gen = self._format_header_mi() + else: + gen = self._format_header_regular() + + gen2 = () + if self.df.index.names: + row = [x if x is not None else '' + for x in self.df.index.names] + [''] * len(self.columns) + if reduce(lambda x, y: x and y, map(lambda x: x != '', row)): + gen2 = (ExcelCell(self.rowcounter, colindex, val, + self.header_style) + for colindex, val in enumerate(row)) + self.rowcounter += 1 + return itertools.chain(gen, gen2) + + def _format_body(self): + + if isinstance(self.df.index, ABCMultiIndex): + return self._format_hierarchical_rows() + else: + return self._format_regular_rows() + + def _format_regular_rows(self): + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) + if has_aliases or self.header: + self.rowcounter += 1 + + # output index and index_label? + if self.index: + # check aliases + # if list only take first as this is not a MultiIndex + if (self.index_label and + isinstance(self.index_label, (list, tuple, np.ndarray, + Index))): + index_label = self.index_label[0] + # if string good to go + elif self.index_label and isinstance(self.index_label, str): + index_label = self.index_label + else: + index_label = self.df.index.names[0] + + if isinstance(self.columns, ABCMultiIndex): + self.rowcounter += 1 + + if index_label and self.header is not False: + yield ExcelCell(self.rowcounter - 1, 0, index_label, + self.header_style) + + # write index_values + index_values = self.df.index + if isinstance(self.df.index, ABCPeriodIndex): + index_values = self.df.index.to_timestamp() + + for idx, idxval in enumerate(index_values): + yield ExcelCell(self.rowcounter + idx, 0, idxval, + self.header_style) + + coloffset = 1 + else: + coloffset = 0 + + for cell in self._generate_body(coloffset): + yield cell + + def _format_hierarchical_rows(self): + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) + if has_aliases or self.header: + self.rowcounter += 1 + + gcolidx = 0 + + if self.index: + index_labels = self.df.index.names + # check for aliases + if (self.index_label and + isinstance(self.index_label, (list, tuple, np.ndarray, + Index))): + index_labels = self.index_label + + # MultiIndex columns require an extra row + # with index names (blank if None) for + # unambigous round-trip, unless not merging, + # in which case the names all go on one row Issue #11328 + if isinstance(self.columns, ABCMultiIndex) and self.merge_cells: + self.rowcounter += 1 + + # if index labels are not empty go ahead and dump + if com._any_not_none(*index_labels) and self.header is not False: + + for cidx, name in enumerate(index_labels): + yield ExcelCell(self.rowcounter - 1, cidx, name, + self.header_style) + + if self.merge_cells: + # Format hierarchical rows as merged cells. + level_strs = self.df.index.format(sparsify=True, adjoin=False, + names=False) + level_lengths = get_level_lengths(level_strs) + + for spans, levels, level_codes in zip(level_lengths, + self.df.index.levels, + self.df.index.codes): + + values = levels.take(level_codes, + allow_fill=levels._can_hold_na, + fill_value=True) + + for i in spans: + if spans[i] > 1: + yield ExcelCell(self.rowcounter + i, gcolidx, + values[i], self.header_style, + self.rowcounter + i + spans[i] - 1, + gcolidx) + else: + yield ExcelCell(self.rowcounter + i, gcolidx, + values[i], self.header_style) + gcolidx += 1 + + else: + # Format hierarchical rows with non-merged values. + for indexcolvals in zip(*self.df.index): + for idx, indexcolval in enumerate(indexcolvals): + yield ExcelCell(self.rowcounter + idx, gcolidx, + indexcolval, self.header_style) + gcolidx += 1 + + for cell in self._generate_body(gcolidx): + yield cell + + def _generate_body(self, coloffset): + if self.styler is None: + styles = None + else: + styles = self.styler._compute().ctx + if not styles: + styles = None + xlstyle = None + + # Write the body of the frame data series by series. + for colidx in range(len(self.columns)): + series = self.df.iloc[:, colidx] + for i, val in enumerate(series): + if styles is not None: + xlstyle = self.style_converter(';'.join(styles[i, colidx])) + yield ExcelCell(self.rowcounter + i, colidx + coloffset, val, + xlstyle) + + def get_formatted_cells(self): + for cell in itertools.chain(self._format_header(), + self._format_body()): + cell.val = self._format_value(cell.val) + yield cell + + def write(self, writer, sheet_name='Sheet1', startrow=0, + startcol=0, freeze_panes=None, engine=None): + """ + writer : string or ExcelWriter object + File path or existing ExcelWriter + sheet_name : string, default 'Sheet1' + Name of sheet which will contain DataFrame + startrow : + upper left cell row to dump data frame + startcol : + upper left cell column to dump data frame + freeze_panes : tuple of integer (length 2), default None + Specifies the one-based bottommost row and rightmost column that + is to be frozen + engine : string, default None + write engine to use if writer is a path - you can also set this + via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, + and ``io.excel.xlsm.writer``. + """ + from pandas.io.excel import ExcelWriter + from pandas.io.common import _stringify_path + + if isinstance(writer, ExcelWriter): + need_save = False + else: + writer = ExcelWriter(_stringify_path(writer), engine=engine) + need_save = True + + formatted_cells = self.get_formatted_cells() + writer.write_cells(formatted_cells, sheet_name, + startrow=startrow, startcol=startcol, + freeze_panes=freeze_panes) + if need_save: + writer.save() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/format.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/format.py new file mode 100644 index 0000000000000000000000000000000000000000..f68ef2cc390064146b206e4caf8cdc172e431dfa --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/format.py @@ -0,0 +1,1626 @@ +# -*- coding: utf-8 -*- +""" +Internal module for formatting output data in csv, html, +and latex files. This module also applies to display formatting. +""" + +from __future__ import print_function + +from functools import partial + +import numpy as np + +from pandas._libs import lib +from pandas._libs.tslib import format_array_from_datetime +from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT +from pandas.compat import StringIO, lzip, map, u, zip + +from pandas.core.dtypes.common import ( + is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, + is_extension_array_dtype, is_float, is_float_dtype, is_integer, + is_integer_dtype, is_list_like, is_numeric_dtype, is_scalar, + is_timedelta64_dtype) +from pandas.core.dtypes.generic import ( + ABCIndexClass, ABCMultiIndex, ABCSeries, ABCSparseArray) +from pandas.core.dtypes.missing import isna, notna + +from pandas import compat +from pandas.core.base import PandasObject +import pandas.core.common as com +from pandas.core.config import get_option, set_option +from pandas.core.index import Index, ensure_index +from pandas.core.indexes.datetimes import DatetimeIndex + +from pandas.io.common import _expand_user, _stringify_path +from pandas.io.formats.printing import adjoin, justify, pprint_thing +from pandas.io.formats.terminal import get_terminal_size + +# pylint: disable=W0141 + + +common_docstring = """ + Parameters + ---------- + buf : StringIO-like, optional + Buffer to write to. + columns : sequence, optional, default None + The subset of columns to write. Writes all columns by default. + col_space : int, optional + The minimum width of each column. + header : bool, optional + %(header)s. + index : bool, optional, default True + Whether to print index (row) labels. + na_rep : str, optional, default 'NaN' + String representation of NAN to use. + formatters : list or dict of one-param. functions, optional + Formatter functions to apply to columns' elements by position or + name. + The result of each function must be a unicode string. + List must be of length equal to the number of columns. + float_format : one-parameter function, optional, default None + Formatter function to apply to columns' elements if they are + floats. The result of this function must be a unicode string. + sparsify : bool, optional, default True + Set to False for a DataFrame with a hierarchical index to print + every multiindex key at each row. + index_names : bool, optional, default True + Prints the names of the indexes. + justify : str, default None + How to justify the column labels. If None uses the option from + the print configuration (controlled by set_option), 'right' out + of the box. Valid values are + + * left + * right + * center + * justify + * justify-all + * start + * end + * inherit + * match-parent + * initial + * unset. + max_rows : int, optional + Maximum number of rows to display in the console. + max_cols : int, optional + Maximum number of columns to display in the console. + show_dimensions : bool, default False + Display DataFrame dimensions (number of rows by number of columns). + decimal : str, default '.' + Character recognized as decimal separator, e.g. ',' in Europe. + + .. versionadded:: 0.18.0 + """ + +_VALID_JUSTIFY_PARAMETERS = ("left", "right", "center", "justify", + "justify-all", "start", "end", "inherit", + "match-parent", "initial", "unset") + +return_docstring = """ + Returns + ------- + str (or unicode, depending on data and options) + String representation of the dataframe. + """ + + +class CategoricalFormatter(object): + + def __init__(self, categorical, buf=None, length=True, na_rep='NaN', + footer=True): + self.categorical = categorical + self.buf = buf if buf is not None else StringIO(u("")) + self.na_rep = na_rep + self.length = length + self.footer = footer + + def _get_footer(self): + footer = '' + + if self.length: + if footer: + footer += ', ' + footer += "Length: {length}".format(length=len(self.categorical)) + + level_info = self.categorical._repr_categories_info() + + # Levels are added in a newline + if footer: + footer += '\n' + footer += level_info + + return compat.text_type(footer) + + def _get_formatted_values(self): + return format_array(self.categorical.get_values(), None, + float_format=None, na_rep=self.na_rep) + + def to_string(self): + categorical = self.categorical + + if len(categorical) == 0: + if self.footer: + return self._get_footer() + else: + return u('') + + fmt_values = self._get_formatted_values() + + result = [u('{i}').format(i=i) for i in fmt_values] + result = [i.strip() for i in result] + result = u(', ').join(result) + result = [u('[') + result + u(']')] + if self.footer: + footer = self._get_footer() + if footer: + result.append(footer) + + return compat.text_type(u('\n').join(result)) + + +class SeriesFormatter(object): + + def __init__(self, series, buf=None, length=True, header=True, index=True, + na_rep='NaN', name=False, float_format=None, dtype=True, + max_rows=None): + self.series = series + self.buf = buf if buf is not None else StringIO() + self.name = name + self.na_rep = na_rep + self.header = header + self.length = length + self.index = index + self.max_rows = max_rows + + if float_format is None: + float_format = get_option("display.float_format") + self.float_format = float_format + self.dtype = dtype + self.adj = _get_adjustment() + + self._chk_truncate() + + def _chk_truncate(self): + from pandas.core.reshape.concat import concat + max_rows = self.max_rows + truncate_v = max_rows and (len(self.series) > max_rows) + series = self.series + if truncate_v: + if max_rows == 1: + row_num = max_rows + series = series.iloc[:max_rows] + else: + row_num = max_rows // 2 + series = concat((series.iloc[:row_num], + series.iloc[-row_num:])) + self.tr_row_num = row_num + self.tr_series = series + self.truncate_v = truncate_v + + def _get_footer(self): + name = self.series.name + footer = u('') + + if getattr(self.series.index, 'freq', None) is not None: + footer += 'Freq: {freq}'.format(freq=self.series.index.freqstr) + + if self.name is not False and name is not None: + if footer: + footer += ', ' + + series_name = pprint_thing(name, + escape_chars=('\t', '\r', '\n')) + footer += ((u"Name: {sname}".format(sname=series_name)) + if name is not None else "") + + if (self.length is True or + (self.length == 'truncate' and self.truncate_v)): + if footer: + footer += ', ' + footer += 'Length: {length}'.format(length=len(self.series)) + + if self.dtype is not False and self.dtype is not None: + name = getattr(self.tr_series.dtype, 'name', None) + if name: + if footer: + footer += ', ' + footer += u'dtype: {typ}'.format(typ=pprint_thing(name)) + + # level infos are added to the end and in a new line, like it is done + # for Categoricals + if is_categorical_dtype(self.tr_series.dtype): + level_info = self.tr_series._values._repr_categories_info() + if footer: + footer += "\n" + footer += level_info + + return compat.text_type(footer) + + def _get_formatted_index(self): + index = self.tr_series.index + is_multi = isinstance(index, ABCMultiIndex) + + if is_multi: + have_header = any(name for name in index.names) + fmt_index = index.format(names=True) + else: + have_header = index.name is not None + fmt_index = index.format(name=True) + return fmt_index, have_header + + def _get_formatted_values(self): + values_to_format = self.tr_series._formatting_values() + return format_array(values_to_format, None, + float_format=self.float_format, na_rep=self.na_rep) + + def to_string(self): + series = self.tr_series + footer = self._get_footer() + + if len(series) == 0: + return 'Series([], ' + footer + ')' + + fmt_index, have_header = self._get_formatted_index() + fmt_values = self._get_formatted_values() + + if self.truncate_v: + n_header_rows = 0 + row_num = self.tr_row_num + width = self.adj.len(fmt_values[row_num - 1]) + if width > 3: + dot_str = '...' + else: + dot_str = '..' + # Series uses mode=center because it has single value columns + # DataFrame uses mode=left + dot_str = self.adj.justify([dot_str], width, mode='center')[0] + fmt_values.insert(row_num + n_header_rows, dot_str) + fmt_index.insert(row_num + 1, '') + + if self.index: + result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values]) + else: + result = self.adj.adjoin(3, fmt_values) + + if self.header and have_header: + result = fmt_index[0] + '\n' + result + + if footer: + result += '\n' + footer + + return compat.text_type(u('').join(result)) + + +class TextAdjustment(object): + + def __init__(self): + self.encoding = get_option("display.encoding") + + def len(self, text): + return compat.strlen(text, encoding=self.encoding) + + def justify(self, texts, max_len, mode='right'): + return justify(texts, max_len, mode=mode) + + def adjoin(self, space, *lists, **kwargs): + return adjoin(space, *lists, strlen=self.len, + justfunc=self.justify, **kwargs) + + +class EastAsianTextAdjustment(TextAdjustment): + + def __init__(self): + super(EastAsianTextAdjustment, self).__init__() + if get_option("display.unicode.ambiguous_as_wide"): + self.ambiguous_width = 2 + else: + self.ambiguous_width = 1 + + def len(self, text): + return compat.east_asian_len(text, encoding=self.encoding, + ambiguous_width=self.ambiguous_width) + + def justify(self, texts, max_len, mode='right'): + # re-calculate padding space per str considering East Asian Width + def _get_pad(t): + return max_len - self.len(t) + len(t) + + if mode == 'left': + return [x.ljust(_get_pad(x)) for x in texts] + elif mode == 'center': + return [x.center(_get_pad(x)) for x in texts] + else: + return [x.rjust(_get_pad(x)) for x in texts] + + +def _get_adjustment(): + use_east_asian_width = get_option("display.unicode.east_asian_width") + if use_east_asian_width: + return EastAsianTextAdjustment() + else: + return TextAdjustment() + + +class TableFormatter(object): + + is_truncated = False + show_dimensions = None + + @property + def should_show_dimensions(self): + return (self.show_dimensions is True or + (self.show_dimensions == 'truncate' and self.is_truncated)) + + def _get_formatter(self, i): + if isinstance(self.formatters, (list, tuple)): + if is_integer(i): + return self.formatters[i] + else: + return None + else: + if is_integer(i) and i not in self.columns: + i = self.columns[i] + return self.formatters.get(i, None) + + +class DataFrameFormatter(TableFormatter): + """ + Render a DataFrame + + self.to_string() : console-friendly tabular output + self.to_html() : html table + self.to_latex() : LaTeX tabular environment table + + """ + + __doc__ = __doc__ if __doc__ else '' + __doc__ += common_docstring + return_docstring + + def __init__(self, frame, buf=None, columns=None, col_space=None, + header=True, index=True, na_rep='NaN', formatters=None, + justify=None, float_format=None, sparsify=None, + index_names=True, line_width=None, max_rows=None, + max_cols=None, show_dimensions=False, decimal='.', + table_id=None, render_links=False, **kwds): + self.frame = frame + if buf is not None: + self.buf = _expand_user(_stringify_path(buf)) + else: + self.buf = StringIO() + self.show_index_names = index_names + + if sparsify is None: + sparsify = get_option("display.multi_sparse") + + self.sparsify = sparsify + + self.float_format = float_format + self.formatters = formatters if formatters is not None else {} + self.na_rep = na_rep + self.decimal = decimal + self.col_space = col_space + self.header = header + self.index = index + self.line_width = line_width + self.max_rows = max_rows + self.max_cols = max_cols + self.max_rows_displayed = min(max_rows or len(self.frame), + len(self.frame)) + self.show_dimensions = show_dimensions + self.table_id = table_id + self.render_links = render_links + + if justify is None: + self.justify = get_option("display.colheader_justify") + else: + self.justify = justify + + self.kwds = kwds + + if columns is not None: + self.columns = ensure_index(columns) + self.frame = self.frame[self.columns] + else: + self.columns = frame.columns + + self._chk_truncate() + self.adj = _get_adjustment() + + def _chk_truncate(self): + """ + Checks whether the frame should be truncated. If so, slices + the frame up. + """ + from pandas.core.reshape.concat import concat + + # Cut the data to the information actually printed + max_cols = self.max_cols + max_rows = self.max_rows + + if max_cols == 0 or max_rows == 0: # assume we are in the terminal + # (why else = 0) + (w, h) = get_terminal_size() + self.w = w + self.h = h + if self.max_rows == 0: + dot_row = 1 + prompt_row = 1 + if self.show_dimensions: + show_dimension_rows = 3 + n_add_rows = (self.header + dot_row + show_dimension_rows + + prompt_row) + # rows available to fill with actual data + max_rows_adj = self.h - n_add_rows + self.max_rows_adj = max_rows_adj + + # Format only rows and columns that could potentially fit the + # screen + if max_cols == 0 and len(self.frame.columns) > w: + max_cols = w + if max_rows == 0 and len(self.frame) > h: + max_rows = h + + if not hasattr(self, 'max_rows_adj'): + self.max_rows_adj = max_rows + if not hasattr(self, 'max_cols_adj'): + self.max_cols_adj = max_cols + + max_cols_adj = self.max_cols_adj + max_rows_adj = self.max_rows_adj + + truncate_h = max_cols_adj and (len(self.columns) > max_cols_adj) + truncate_v = max_rows_adj and (len(self.frame) > max_rows_adj) + + frame = self.frame + if truncate_h: + if max_cols_adj == 0: + col_num = len(frame.columns) + elif max_cols_adj == 1: + frame = frame.iloc[:, :max_cols] + col_num = max_cols + else: + col_num = (max_cols_adj // 2) + frame = concat((frame.iloc[:, :col_num], + frame.iloc[:, -col_num:]), axis=1) + self.tr_col_num = col_num + if truncate_v: + if max_rows_adj == 1: + row_num = max_rows + frame = frame.iloc[:max_rows, :] + else: + row_num = max_rows_adj // 2 + frame = concat((frame.iloc[:row_num, :], + frame.iloc[-row_num:, :])) + self.tr_row_num = row_num + + self.tr_frame = frame + self.truncate_h = truncate_h + self.truncate_v = truncate_v + self.is_truncated = self.truncate_h or self.truncate_v + + def _to_str_columns(self): + """ + Render a DataFrame to a list of columns (as lists of strings). + """ + frame = self.tr_frame + # may include levels names also + + str_index = self._get_formatted_index(frame) + + if not is_list_like(self.header) and not self.header: + stringified = [] + for i, c in enumerate(frame): + fmt_values = self._format_col(i) + fmt_values = _make_fixed_width(fmt_values, self.justify, + minimum=(self.col_space or 0), + adj=self.adj) + stringified.append(fmt_values) + else: + if is_list_like(self.header): + if len(self.header) != len(self.columns): + raise ValueError(('Writing {ncols} cols but got {nalias} ' + 'aliases' + .format(ncols=len(self.columns), + nalias=len(self.header)))) + str_columns = [[label] for label in self.header] + else: + str_columns = self._get_formatted_column_labels(frame) + + stringified = [] + for i, c in enumerate(frame): + cheader = str_columns[i] + header_colwidth = max(self.col_space or 0, + *(self.adj.len(x) for x in cheader)) + fmt_values = self._format_col(i) + fmt_values = _make_fixed_width(fmt_values, self.justify, + minimum=header_colwidth, + adj=self.adj) + + max_len = max(max(self.adj.len(x) for x in fmt_values), + header_colwidth) + cheader = self.adj.justify(cheader, max_len, mode=self.justify) + stringified.append(cheader + fmt_values) + + strcols = stringified + if self.index: + strcols.insert(0, str_index) + + # Add ... to signal truncated + truncate_h = self.truncate_h + truncate_v = self.truncate_v + + if truncate_h: + col_num = self.tr_col_num + strcols.insert(self.tr_col_num + 1, [' ...'] * (len(str_index))) + if truncate_v: + n_header_rows = len(str_index) - len(frame) + row_num = self.tr_row_num + for ix, col in enumerate(strcols): + # infer from above row + cwidth = self.adj.len(strcols[ix][row_num]) + is_dot_col = False + if truncate_h: + is_dot_col = ix == col_num + 1 + if cwidth > 3 or is_dot_col: + my_str = '...' + else: + my_str = '..' + + if ix == 0: + dot_mode = 'left' + elif is_dot_col: + cwidth = 4 + dot_mode = 'right' + else: + dot_mode = 'right' + dot_str = self.adj.justify([my_str], cwidth, mode=dot_mode)[0] + strcols[ix].insert(row_num + n_header_rows, dot_str) + return strcols + + def to_string(self): + """ + Render a DataFrame to a console-friendly tabular output. + """ + from pandas import Series + + frame = self.frame + + if len(frame.columns) == 0 or len(frame.index) == 0: + info_line = (u('Empty {name}\nColumns: {col}\nIndex: {idx}') + .format(name=type(self.frame).__name__, + col=pprint_thing(frame.columns), + idx=pprint_thing(frame.index))) + text = info_line + else: + + strcols = self._to_str_columns() + if self.line_width is None: # no need to wrap around just print + # the whole frame + text = self.adj.adjoin(1, *strcols) + elif (not isinstance(self.max_cols, int) or + self.max_cols > 0): # need to wrap around + text = self._join_multiline(*strcols) + else: # max_cols == 0. Try to fit frame to terminal + text = self.adj.adjoin(1, *strcols).split('\n') + max_len = Series(text).str.len().max() + # plus truncate dot col + dif = max_len - self.w + # '+ 1' to avoid too wide repr (GH PR #17023) + adj_dif = dif + 1 + col_lens = Series([Series(ele).apply(len).max() + for ele in strcols]) + n_cols = len(col_lens) + counter = 0 + while adj_dif > 0 and n_cols > 1: + counter += 1 + mid = int(round(n_cols / 2.)) + mid_ix = col_lens.index[mid] + col_len = col_lens[mid_ix] + # adjoin adds one + adj_dif -= (col_len + 1) + col_lens = col_lens.drop(mid_ix) + n_cols = len(col_lens) + # subtract index column + max_cols_adj = n_cols - self.index + # GH-21180. Ensure that we print at least two. + max_cols_adj = max(max_cols_adj, 2) + self.max_cols_adj = max_cols_adj + + # Call again _chk_truncate to cut frame appropriately + # and then generate string representation + self._chk_truncate() + strcols = self._to_str_columns() + text = self.adj.adjoin(1, *strcols) + self.buf.writelines(text) + + if self.should_show_dimensions: + self.buf.write("\n\n[{nrows} rows x {ncols} columns]" + .format(nrows=len(frame), ncols=len(frame.columns))) + + def _join_multiline(self, *strcols): + lwidth = self.line_width + adjoin_width = 1 + strcols = list(strcols) + if self.index: + idx = strcols.pop(0) + lwidth -= np.array([self.adj.len(x) + for x in idx]).max() + adjoin_width + + col_widths = [np.array([self.adj.len(x) for x in col]).max() if + len(col) > 0 else 0 for col in strcols] + col_bins = _binify(col_widths, lwidth) + nbins = len(col_bins) + + if self.truncate_v: + nrows = self.max_rows_adj + 1 + else: + nrows = len(self.frame) + + str_lst = [] + st = 0 + for i, ed in enumerate(col_bins): + row = strcols[st:ed] + if self.index: + row.insert(0, idx) + if nbins > 1: + if ed <= len(strcols) and i < nbins - 1: + row.append([' \\'] + [' '] * (nrows - 1)) + else: + row.append([' '] * nrows) + str_lst.append(self.adj.adjoin(adjoin_width, *row)) + st = ed + return '\n\n'.join(str_lst) + + def to_latex(self, column_format=None, longtable=False, encoding=None, + multicolumn=False, multicolumn_format=None, multirow=False): + """ + Render a DataFrame to a LaTeX tabular/longtable environment output. + """ + + from pandas.io.formats.latex import LatexFormatter + latex_renderer = LatexFormatter(self, column_format=column_format, + longtable=longtable, + multicolumn=multicolumn, + multicolumn_format=multicolumn_format, + multirow=multirow) + + if encoding is None: + encoding = 'ascii' if compat.PY2 else 'utf-8' + + if hasattr(self.buf, 'write'): + latex_renderer.write_result(self.buf) + elif isinstance(self.buf, compat.string_types): + import codecs + with codecs.open(self.buf, 'w', encoding=encoding) as f: + latex_renderer.write_result(f) + else: + raise TypeError('buf is not a file name and it has no write ' + 'method') + + def _format_col(self, i): + frame = self.tr_frame + formatter = self._get_formatter(i) + values_to_format = frame.iloc[:, i]._formatting_values() + return format_array(values_to_format, formatter, + float_format=self.float_format, na_rep=self.na_rep, + space=self.col_space, decimal=self.decimal) + + def to_html(self, classes=None, notebook=False, border=None): + """ + Render a DataFrame to a html table. + + Parameters + ---------- + classes : str or list-like + classes to include in the `class` attribute of the opening + ```` tag, in addition to the default "dataframe". + notebook : {True, False}, optional, default False + Whether the generated HTML is for IPython Notebook. + border : int + A ``border=border`` attribute is included in the opening + ``
`` tag. Default ``pd.options.html.border``. + + .. versionadded:: 0.19.0 + """ + from pandas.io.formats.html import HTMLFormatter, NotebookFormatter + Klass = NotebookFormatter if notebook else HTMLFormatter + html = Klass(self, classes=classes, border=border).render() + if hasattr(self.buf, 'write'): + buffer_put_lines(self.buf, html) + elif isinstance(self.buf, compat.string_types): + with open(self.buf, 'w') as f: + buffer_put_lines(f, html) + else: + raise TypeError('buf is not a file name and it has no write ' + ' method') + + def _get_formatted_column_labels(self, frame): + from pandas.core.index import _sparsify + + columns = frame.columns + + if isinstance(columns, ABCMultiIndex): + fmt_columns = columns.format(sparsify=False, adjoin=False) + fmt_columns = lzip(*fmt_columns) + dtypes = self.frame.dtypes._values + + # if we have a Float level, they don't use leading space at all + restrict_formatting = any(l.is_floating for l in columns.levels) + need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes))) + + def space_format(x, y): + if (y not in self.formatters and + need_leadsp[x] and not restrict_formatting): + return ' ' + y + return y + + str_columns = list(zip(*[[space_format(x, y) for y in x] + for x in fmt_columns])) + if self.sparsify and len(str_columns): + str_columns = _sparsify(str_columns) + + str_columns = [list(x) for x in zip(*str_columns)] + else: + fmt_columns = columns.format() + dtypes = self.frame.dtypes + need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes))) + str_columns = [[' ' + x if not self._get_formatter(i) and + need_leadsp[x] else x] + for i, (col, x) in enumerate(zip(columns, + fmt_columns))] + + if self.show_row_idx_names: + for x in str_columns: + x.append('') + + # self.str_columns = str_columns + return str_columns + + @property + def has_index_names(self): + return _has_names(self.frame.index) + + @property + def has_column_names(self): + return _has_names(self.frame.columns) + + @property + def show_row_idx_names(self): + return all((self.has_index_names, + self.index, + self.show_index_names)) + + @property + def show_col_idx_names(self): + return all((self.has_column_names, + self.show_index_names, + self.header)) + + def _get_formatted_index(self, frame): + # Note: this is only used by to_string() and to_latex(), not by + # to_html(). + index = frame.index + columns = frame.columns + fmt = self._get_formatter('__index__') + + if isinstance(index, ABCMultiIndex): + fmt_index = index.format( + sparsify=self.sparsify, adjoin=False, + names=self.show_row_idx_names, formatter=fmt) + else: + fmt_index = [index.format( + name=self.show_row_idx_names, formatter=fmt)] + + fmt_index = [tuple(_make_fixed_width(list(x), justify='left', + minimum=(self.col_space or 0), + adj=self.adj)) for x in fmt_index] + + adjoined = self.adj.adjoin(1, *fmt_index).split('\n') + + # empty space for columns + if self.show_col_idx_names: + col_header = ['{x}'.format(x=x) + for x in self._get_column_name_list()] + else: + col_header = [''] * columns.nlevels + + if self.header: + return col_header + adjoined + else: + return adjoined + + def _get_column_name_list(self): + names = [] + columns = self.frame.columns + if isinstance(columns, ABCMultiIndex): + names.extend('' if name is None else name + for name in columns.names) + else: + names.append('' if columns.name is None else columns.name) + return names + +# ---------------------------------------------------------------------- +# Array formatters + + +def format_array(values, formatter, float_format=None, na_rep='NaN', + digits=None, space=None, justify='right', decimal='.', + leading_space=None): + """ + Format an array for printing. + + Parameters + ---------- + values + formatter + float_format + na_rep + digits + space + justify + decimal + leading_space : bool, optional + Whether the array should be formatted with a leading space. + When an array as a column of a Series or DataFrame, we do want + the leading space to pad between columns. + + When formatting an Index subclass + (e.g. IntervalIndex._format_native_types), we don't want the + leading space since it should be left-aligned. + + Returns + ------- + List[str] + """ + + if is_datetime64_dtype(values.dtype): + fmt_klass = Datetime64Formatter + elif is_datetime64tz_dtype(values): + fmt_klass = Datetime64TZFormatter + elif is_timedelta64_dtype(values.dtype): + fmt_klass = Timedelta64Formatter + elif is_extension_array_dtype(values.dtype): + fmt_klass = ExtensionArrayFormatter + elif is_float_dtype(values.dtype): + fmt_klass = FloatArrayFormatter + elif is_integer_dtype(values.dtype): + fmt_klass = IntArrayFormatter + else: + fmt_klass = GenericArrayFormatter + + if space is None: + space = get_option("display.column_space") + + if float_format is None: + float_format = get_option("display.float_format") + + if digits is None: + digits = get_option("display.precision") + + fmt_obj = fmt_klass(values, digits=digits, na_rep=na_rep, + float_format=float_format, formatter=formatter, + space=space, justify=justify, decimal=decimal, + leading_space=leading_space) + + return fmt_obj.get_result() + + +class GenericArrayFormatter(object): + + def __init__(self, values, digits=7, formatter=None, na_rep='NaN', + space=12, float_format=None, justify='right', decimal='.', + quoting=None, fixed_width=True, leading_space=None): + self.values = values + self.digits = digits + self.na_rep = na_rep + self.space = space + self.formatter = formatter + self.float_format = float_format + self.justify = justify + self.decimal = decimal + self.quoting = quoting + self.fixed_width = fixed_width + self.leading_space = leading_space + + def get_result(self): + fmt_values = self._format_strings() + return _make_fixed_width(fmt_values, self.justify) + + def _format_strings(self): + if self.float_format is None: + float_format = get_option("display.float_format") + if float_format is None: + fmt_str = ('{{x: .{prec:d}g}}' + .format(prec=get_option("display.precision"))) + float_format = lambda x: fmt_str.format(x=x) + else: + float_format = self.float_format + + formatter = ( + self.formatter if self.formatter is not None else + (lambda x: pprint_thing(x, escape_chars=('\t', '\r', '\n')))) + + def _format(x): + if self.na_rep is not None and is_scalar(x) and isna(x): + if x is None: + return 'None' + elif x is NaT: + return 'NaT' + return self.na_rep + elif isinstance(x, PandasObject): + return u'{x}'.format(x=x) + else: + # object dtype + return u'{x}'.format(x=formatter(x)) + + vals = self.values + if isinstance(vals, Index): + vals = vals._values + elif isinstance(vals, ABCSparseArray): + vals = vals.values + + is_float_type = lib.map_infer(vals, is_float) & notna(vals) + leading_space = self.leading_space + if leading_space is None: + leading_space = is_float_type.any() + + fmt_values = [] + for i, v in enumerate(vals): + if not is_float_type[i] and leading_space: + fmt_values.append(u' {v}'.format(v=_format(v))) + elif is_float_type[i]: + fmt_values.append(float_format(v)) + else: + if leading_space is False: + # False specifically, so that the default is + # to include a space if we get here. + tpl = u'{v}' + else: + tpl = u' {v}' + fmt_values.append(tpl.format(v=_format(v))) + + return fmt_values + + +class FloatArrayFormatter(GenericArrayFormatter): + """ + + """ + + def __init__(self, *args, **kwargs): + GenericArrayFormatter.__init__(self, *args, **kwargs) + + # float_format is expected to be a string + # formatter should be used to pass a function + if self.float_format is not None and self.formatter is None: + # GH21625, GH22270 + self.fixed_width = False + if callable(self.float_format): + self.formatter = self.float_format + self.float_format = None + + def _value_formatter(self, float_format=None, threshold=None): + """Returns a function to be applied on each value to format it + """ + + # the float_format parameter supersedes self.float_format + if float_format is None: + float_format = self.float_format + + # we are going to compose different functions, to first convert to + # a string, then replace the decimal symbol, and finally chop according + # to the threshold + + # when there is no float_format, we use str instead of '%g' + # because str(0.0) = '0.0' while '%g' % 0.0 = '0' + if float_format: + def base_formatter(v): + return float_format(value=v) if notna(v) else self.na_rep + else: + def base_formatter(v): + return str(v) if notna(v) else self.na_rep + + if self.decimal != '.': + def decimal_formatter(v): + return base_formatter(v).replace('.', self.decimal, 1) + else: + decimal_formatter = base_formatter + + if threshold is None: + return decimal_formatter + + def formatter(value): + if notna(value): + if abs(value) > threshold: + return decimal_formatter(value) + else: + return decimal_formatter(0.0) + else: + return self.na_rep + + return formatter + + def get_result_as_array(self): + """ + Returns the float values converted into strings using + the parameters given at initialisation, as a numpy array + """ + + if self.formatter is not None: + return np.array([self.formatter(x) for x in self.values]) + + if self.fixed_width: + threshold = get_option("display.chop_threshold") + else: + threshold = None + + # if we have a fixed_width, we'll need to try different float_format + def format_values_with(float_format): + formatter = self._value_formatter(float_format, threshold) + + # default formatter leaves a space to the left when formatting + # floats, must be consistent for left-justifying NaNs (GH #25061) + if self.justify == 'left': + na_rep = ' ' + self.na_rep + else: + na_rep = self.na_rep + + # separate the wheat from the chaff + values = self.values + mask = isna(values) + if hasattr(values, 'to_dense'): # sparse numpy ndarray + values = values.to_dense() + values = np.array(values, dtype='object') + values[mask] = na_rep + imask = (~mask).ravel() + values.flat[imask] = np.array([formatter(val) + for val in values.ravel()[imask]]) + + if self.fixed_width: + return _trim_zeros(values, na_rep) + + return values + + # There is a special default string when we are fixed-width + # The default is otherwise to use str instead of a formatting string + if self.float_format is None: + if self.fixed_width: + float_format = partial('{value: .{digits:d}f}'.format, + digits=self.digits) + else: + float_format = self.float_format + else: + float_format = lambda value: self.float_format % value + + formatted_values = format_values_with(float_format) + + if not self.fixed_width: + return formatted_values + + # we need do convert to engineering format if some values are too small + # and would appear as 0, or if some values are too big and take too + # much space + + if len(formatted_values) > 0: + maxlen = max(len(x) for x in formatted_values) + too_long = maxlen > self.digits + 6 + else: + too_long = False + + with np.errstate(invalid='ignore'): + abs_vals = np.abs(self.values) + # this is pretty arbitrary for now + # large values: more that 8 characters including decimal symbol + # and first digit, hence > 1e6 + has_large_values = (abs_vals > 1e6).any() + has_small_values = ((abs_vals < 10**(-self.digits)) & + (abs_vals > 0)).any() + + if has_small_values or (too_long and has_large_values): + float_format = partial('{value: .{digits:d}e}'.format, + digits=self.digits) + formatted_values = format_values_with(float_format) + + return formatted_values + + def _format_strings(self): + # shortcut + if self.formatter is not None: + return [self.formatter(x) for x in self.values] + + return list(self.get_result_as_array()) + + +class IntArrayFormatter(GenericArrayFormatter): + + def _format_strings(self): + formatter = self.formatter or (lambda x: '{x: d}'.format(x=x)) + fmt_values = [formatter(x) for x in self.values] + return fmt_values + + +class Datetime64Formatter(GenericArrayFormatter): + + def __init__(self, values, nat_rep='NaT', date_format=None, **kwargs): + super(Datetime64Formatter, self).__init__(values, **kwargs) + self.nat_rep = nat_rep + self.date_format = date_format + + def _format_strings(self): + """ we by definition have DO NOT have a TZ """ + + values = self.values + + if not isinstance(values, DatetimeIndex): + values = DatetimeIndex(values) + + if self.formatter is not None and callable(self.formatter): + return [self.formatter(x) for x in values] + + fmt_values = format_array_from_datetime( + values.asi8.ravel(), + format=_get_format_datetime64_from_values(values, + self.date_format), + na_rep=self.nat_rep).reshape(values.shape) + return fmt_values.tolist() + + +class ExtensionArrayFormatter(GenericArrayFormatter): + def _format_strings(self): + values = self.values + if isinstance(values, (ABCIndexClass, ABCSeries)): + values = values._values + + formatter = values._formatter(boxed=True) + + if is_categorical_dtype(values.dtype): + # Categorical is special for now, so that we can preserve tzinfo + array = values.get_values() + else: + array = np.asarray(values) + + fmt_values = format_array(array, + formatter, + float_format=self.float_format, + na_rep=self.na_rep, digits=self.digits, + space=self.space, justify=self.justify, + leading_space=self.leading_space) + return fmt_values + + +def format_percentiles(percentiles): + """ + Outputs rounded and formatted percentiles. + + Parameters + ---------- + percentiles : list-like, containing floats from interval [0,1] + + Returns + ------- + formatted : list of strings + + Notes + ----- + Rounding precision is chosen so that: (1) if any two elements of + ``percentiles`` differ, they remain different after rounding + (2) no entry is *rounded* to 0% or 100%. + Any non-integer is always rounded to at least 1 decimal place. + + Examples + -------- + Keeps all entries different after rounding: + + >>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) + ['1.999%', '2.001%', '50%', '66.667%', '99.99%'] + + No element is rounded to 0% or 100% (unless already equal to it). + Duplicates are allowed: + + >>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) + ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] + """ + + percentiles = np.asarray(percentiles) + + # It checks for np.NaN as well + with np.errstate(invalid='ignore'): + if not is_numeric_dtype(percentiles) or not np.all(percentiles >= 0) \ + or not np.all(percentiles <= 1): + raise ValueError("percentiles should all be in the interval [0,1]") + + percentiles = 100 * percentiles + int_idx = (percentiles.astype(int) == percentiles) + + if np.all(int_idx): + out = percentiles.astype(int).astype(str) + return [i + '%' for i in out] + + unique_pcts = np.unique(percentiles) + to_begin = unique_pcts[0] if unique_pcts[0] > 0 else None + to_end = 100 - unique_pcts[-1] if unique_pcts[-1] < 100 else None + + # Least precision that keeps percentiles unique after rounding + prec = -np.floor(np.log10(np.min( + np.ediff1d(unique_pcts, to_begin=to_begin, to_end=to_end) + ))).astype(int) + prec = max(1, prec) + out = np.empty_like(percentiles, dtype=object) + out[int_idx] = percentiles[int_idx].astype(int).astype(str) + out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) + return [i + '%' for i in out] + + +def _is_dates_only(values): + # return a boolean if we are only dates (and don't have a timezone) + values = DatetimeIndex(values) + if values.tz is not None: + return False + + values_int = values.asi8 + consider_values = values_int != iNaT + one_day_nanos = (86400 * 1e9) + even_days = np.logical_and(consider_values, + values_int % int(one_day_nanos) != 0).sum() == 0 + if even_days: + return True + return False + + +def _format_datetime64(x, tz=None, nat_rep='NaT'): + if x is None or (is_scalar(x) and isna(x)): + return nat_rep + + if tz is not None or not isinstance(x, Timestamp): + if getattr(x, 'tzinfo', None) is not None: + x = Timestamp(x).tz_convert(tz) + else: + x = Timestamp(x).tz_localize(tz) + + return str(x) + + +def _format_datetime64_dateonly(x, nat_rep='NaT', date_format=None): + if x is None or (is_scalar(x) and isna(x)): + return nat_rep + + if not isinstance(x, Timestamp): + x = Timestamp(x) + + if date_format: + return x.strftime(date_format) + else: + return x._date_repr + + +def _get_format_datetime64(is_dates_only, nat_rep='NaT', date_format=None): + + if is_dates_only: + return lambda x, tz=None: _format_datetime64_dateonly( + x, nat_rep=nat_rep, date_format=date_format) + else: + return lambda x, tz=None: _format_datetime64(x, tz=tz, nat_rep=nat_rep) + + +def _get_format_datetime64_from_values(values, date_format): + """ given values and a date_format, return a string format """ + is_dates_only = _is_dates_only(values) + if is_dates_only: + return date_format or "%Y-%m-%d" + return date_format + + +class Datetime64TZFormatter(Datetime64Formatter): + + def _format_strings(self): + """ we by definition have a TZ """ + + values = self.values.astype(object) + is_dates_only = _is_dates_only(values) + formatter = (self.formatter or + _get_format_datetime64(is_dates_only, + date_format=self.date_format)) + fmt_values = [formatter(x) for x in values] + + return fmt_values + + +class Timedelta64Formatter(GenericArrayFormatter): + + def __init__(self, values, nat_rep='NaT', box=False, **kwargs): + super(Timedelta64Formatter, self).__init__(values, **kwargs) + self.nat_rep = nat_rep + self.box = box + + def _format_strings(self): + formatter = (self.formatter or + _get_format_timedelta64(self.values, nat_rep=self.nat_rep, + box=self.box)) + fmt_values = np.array([formatter(x) for x in self.values]) + return fmt_values + + +def _get_format_timedelta64(values, nat_rep='NaT', box=False): + """ + Return a formatter function for a range of timedeltas. + These will all have the same format argument + + If box, then show the return in quotes + """ + + values_int = values.astype(np.int64) + + consider_values = values_int != iNaT + + one_day_nanos = (86400 * 1e9) + even_days = np.logical_and(consider_values, + values_int % one_day_nanos != 0).sum() == 0 + all_sub_day = np.logical_and( + consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 + + if even_days: + format = None + elif all_sub_day: + format = 'sub_day' + else: + format = 'long' + + def _formatter(x): + if x is None or (is_scalar(x) and isna(x)): + return nat_rep + + if not isinstance(x, Timedelta): + x = Timedelta(x) + result = x._repr_base(format=format) + if box: + result = "'{res}'".format(res=result) + return result + + return _formatter + + +def _make_fixed_width(strings, justify='right', minimum=None, adj=None): + + if len(strings) == 0 or justify == 'all': + return strings + + if adj is None: + adj = _get_adjustment() + + max_len = max(adj.len(x) for x in strings) + + if minimum is not None: + max_len = max(minimum, max_len) + + conf_max = get_option("display.max_colwidth") + if conf_max is not None and max_len > conf_max: + max_len = conf_max + + def just(x): + if conf_max is not None: + if (conf_max > 3) & (adj.len(x) > max_len): + x = x[:max_len - 3] + '...' + return x + + strings = [just(x) for x in strings] + result = adj.justify(strings, max_len, mode=justify) + return result + + +def _trim_zeros(str_floats, na_rep='NaN'): + """ + Trims zeros, leaving just one before the decimal points if need be. + """ + trimmed = str_floats + + def _is_number(x): + return (x != na_rep and not x.endswith('inf')) + + def _cond(values): + finite = [x for x in values if _is_number(x)] + return (len(finite) > 0 and all(x.endswith('0') for x in finite) and + not (any(('e' in x) or ('E' in x) for x in finite))) + + while _cond(trimmed): + trimmed = [x[:-1] if _is_number(x) else x for x in trimmed] + + # leave one 0 after the decimal points if need be. + return [x + "0" if x.endswith('.') and _is_number(x) else x + for x in trimmed] + + +def _has_names(index): + if isinstance(index, ABCMultiIndex): + return com._any_not_none(*index.names) + else: + return index.name is not None + + +class EngFormatter(object): + """ + Formats float values according to engineering format. + + Based on matplotlib.ticker.EngFormatter + """ + + # The SI engineering prefixes + ENG_PREFIXES = { + -24: "y", + -21: "z", + -18: "a", + -15: "f", + -12: "p", + -9: "n", + -6: "u", + -3: "m", + 0: "", + 3: "k", + 6: "M", + 9: "G", + 12: "T", + 15: "P", + 18: "E", + 21: "Z", + 24: "Y" + } + + def __init__(self, accuracy=None, use_eng_prefix=False): + self.accuracy = accuracy + self.use_eng_prefix = use_eng_prefix + + def __call__(self, num): + """ Formats a number in engineering notation, appending a letter + representing the power of 1000 of the original number. Some examples: + + >>> format_eng(0) # for self.accuracy = 0 + ' 0' + + >>> format_eng(1000000) # for self.accuracy = 1, + # self.use_eng_prefix = True + ' 1.0M' + + >>> format_eng("-1e-6") # for self.accuracy = 2 + # self.use_eng_prefix = False + '-1.00E-06' + + @param num: the value to represent + @type num: either a numeric value or a string that can be converted to + a numeric value (as per decimal.Decimal constructor) + + @return: engineering formatted string + """ + import decimal + import math + dnum = decimal.Decimal(str(num)) + + if decimal.Decimal.is_nan(dnum): + return 'NaN' + + if decimal.Decimal.is_infinite(dnum): + return 'inf' + + sign = 1 + + if dnum < 0: # pragma: no cover + sign = -1 + dnum = -dnum + + if dnum != 0: + pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3)) + else: + pow10 = decimal.Decimal(0) + + pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) + pow10 = pow10.max(min(self.ENG_PREFIXES.keys())) + int_pow10 = int(pow10) + + if self.use_eng_prefix: + prefix = self.ENG_PREFIXES[int_pow10] + else: + if int_pow10 < 0: + prefix = 'E-{pow10:02d}'.format(pow10=-int_pow10) + else: + prefix = 'E+{pow10:02d}'.format(pow10=int_pow10) + + mant = sign * dnum / (10**pow10) + + if self.accuracy is None: # pragma: no cover + format_str = u("{mant: g}{prefix}") + else: + format_str = (u("{{mant: .{acc:d}f}}{{prefix}}") + .format(acc=self.accuracy)) + + formatted = format_str.format(mant=mant, prefix=prefix) + + return formatted # .strip() + + +def set_eng_float_format(accuracy=3, use_eng_prefix=False): + """ + Alter default behavior on how float is formatted in DataFrame. + Format float in engineering format. By accuracy, we mean the number of + decimal digits after the floating point. + + See also EngFormatter. + """ + + set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix)) + set_option("display.column_space", max(12, accuracy + 9)) + + +def _binify(cols, line_width): + adjoin_width = 1 + bins = [] + curr_width = 0 + i_last_column = len(cols) - 1 + for i, w in enumerate(cols): + w_adjoined = w + adjoin_width + curr_width += w_adjoined + if i_last_column == i: + wrap = curr_width + 1 > line_width and i > 0 + else: + wrap = curr_width + 2 > line_width and i > 0 + if wrap: + bins.append(i) + curr_width = w_adjoined + + bins.append(len(cols)) + return bins + + +def get_level_lengths(levels, sentinel=''): + """For each index in each level the function returns lengths of indexes. + + Parameters + ---------- + levels : list of lists + List of values on for level. + sentinel : string, optional + Value which states that no new index starts on there. + + Returns + ---------- + Returns list of maps. For each level returns map of indexes (key is index + in row and value is length of index). + """ + if len(levels) == 0: + return [] + + control = [True] * len(levels[0]) + + result = [] + for level in levels: + last_index = 0 + + lengths = {} + for i, key in enumerate(level): + if control[i] and key == sentinel: + pass + else: + control[i] = False + lengths[last_index] = i - last_index + last_index = i + + lengths[last_index] = len(level) - last_index + + result.append(lengths) + + return result + + +def buffer_put_lines(buf, lines): + """ + Appends lines to a buffer. + + Parameters + ---------- + buf + The buffer to write to + lines + The lines to append. + """ + if any(isinstance(x, compat.text_type) for x in lines): + lines = [compat.text_type(x) for x in lines] + buf.write('\n'.join(lines)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/html.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/html.py new file mode 100644 index 0000000000000000000000000000000000000000..f41749e0a7745da8f1cf45ec4b10c8b11b6c8882 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/html.py @@ -0,0 +1,531 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data in HTML. +""" + +from __future__ import print_function + +from textwrap import dedent + +from pandas.compat import OrderedDict, lzip, map, range, u, unichr, zip + +from pandas.core.dtypes.generic import ABCMultiIndex + +from pandas import compat +import pandas.core.common as com +from pandas.core.config import get_option + +from pandas.io.common import _is_url +from pandas.io.formats.format import TableFormatter, get_level_lengths +from pandas.io.formats.printing import pprint_thing + + +class HTMLFormatter(TableFormatter): + """ + Internal class for formatting output data in html. + This class is intended for shared functionality between + DataFrame.to_html() and DataFrame._repr_html_(). + Any logic in common with other output formatting methods + should ideally be inherited from classes in format.py + and this class responsible for only producing html markup. + """ + + indent_delta = 2 + + def __init__(self, formatter, classes=None, border=None): + self.fmt = formatter + self.classes = classes + + self.frame = self.fmt.frame + self.columns = self.fmt.tr_frame.columns + self.elements = [] + self.bold_rows = self.fmt.kwds.get('bold_rows', False) + self.escape = self.fmt.kwds.get('escape', True) + self.show_dimensions = self.fmt.show_dimensions + if border is None: + border = get_option('display.html.border') + self.border = border + self.table_id = self.fmt.table_id + self.render_links = self.fmt.render_links + + @property + def show_row_idx_names(self): + return self.fmt.show_row_idx_names + + @property + def show_col_idx_names(self): + return self.fmt.show_col_idx_names + + @property + def row_levels(self): + if self.fmt.index: + # showing (row) index + return self.frame.index.nlevels + elif self.show_col_idx_names: + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # If the row index is not displayed a column of + # blank cells need to be included before the DataFrame values. + return 1 + # not showing (row) index + return 0 + + @property + def is_truncated(self): + return self.fmt.is_truncated + + @property + def ncols(self): + return len(self.fmt.tr_frame.columns) + + def write(self, s, indent=0): + rs = pprint_thing(s) + self.elements.append(' ' * indent + rs) + + def write_th(self, s, indent=0, tags=None): + if self.fmt.col_space is not None and self.fmt.col_space > 0: + tags = (tags or "") + tags += ('style="min-width: {colspace};"' + .format(colspace=self.fmt.col_space)) + + return self._write_cell(s, kind='th', indent=indent, tags=tags) + + def write_td(self, s, indent=0, tags=None): + return self._write_cell(s, kind='td', indent=indent, tags=tags) + + def _write_cell(self, s, kind='td', indent=0, tags=None): + if tags is not None: + start_tag = '<{kind} {tags}>'.format(kind=kind, tags=tags) + else: + start_tag = '<{kind}>'.format(kind=kind) + + if self.escape: + # escape & first to prevent double escaping of & + esc = OrderedDict([('&', r'&'), ('<', r'<'), + ('>', r'>')]) + else: + esc = {} + + rs = pprint_thing(s, escape_chars=esc).strip() + + if self.render_links and _is_url(rs): + rs_unescaped = pprint_thing(s, escape_chars={}).strip() + start_tag += ''.format( + url=rs_unescaped) + end_a = '' + else: + end_a = '' + + self.write(u'{start}{rs}{end_a}'.format( + start=start_tag, rs=rs, end_a=end_a, kind=kind), indent) + + def write_tr(self, line, indent=0, indent_delta=0, header=False, + align=None, tags=None, nindex_levels=0): + if tags is None: + tags = {} + + if align is None: + self.write('', indent) + else: + self.write('' + .format(align=align), indent) + indent += indent_delta + + for i, s in enumerate(line): + val_tag = tags.get(i, None) + if header or (self.bold_rows and i < nindex_levels): + self.write_th(s, indent, tags=val_tag) + else: + self.write_td(s, indent, tags=val_tag) + + indent -= indent_delta + self.write('', indent) + + def render(self): + self._write_table() + + if self.should_show_dimensions: + by = chr(215) if compat.PY3 else unichr(215) # × + self.write(u('

{rows} rows {by} {cols} columns

') + .format(rows=len(self.frame), + by=by, + cols=len(self.frame.columns))) + + return self.elements + + def _write_table(self, indent=0): + _classes = ['dataframe'] # Default class. + use_mathjax = get_option("display.html.use_mathjax") + if not use_mathjax: + _classes.append('tex2jax_ignore') + if self.classes is not None: + if isinstance(self.classes, str): + self.classes = self.classes.split() + if not isinstance(self.classes, (list, tuple)): + raise AssertionError('classes must be list or tuple, not {typ}' + .format(typ=type(self.classes))) + _classes.extend(self.classes) + + if self.table_id is None: + id_section = "" + else: + id_section = ' id="{table_id}"'.format(table_id=self.table_id) + + self.write('
' + .format(border=self.border, cls=' '.join(_classes), + id_section=id_section), indent) + + if self.fmt.header or self.show_row_idx_names: + self._write_header(indent + self.indent_delta) + + self._write_body(indent + self.indent_delta) + + self.write('
', indent) + + def _write_col_header(self, indent): + truncate_h = self.fmt.truncate_h + if isinstance(self.columns, ABCMultiIndex): + template = 'colspan="{span:d}" halign="left"' + + if self.fmt.sparsify: + # GH3547 + sentinel = com.sentinel_factory() + else: + sentinel = False + levels = self.columns.format(sparsify=sentinel, adjoin=False, + names=False) + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + for lnum, (records, values) in enumerate(zip(level_lengths, + levels)): + if truncate_h: + # modify the header lines + ins_col = self.fmt.tr_col_num + if self.fmt.sparsify: + recs_new = {} + # Increment tags after ... col. + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + elif tag + span > ins_col: + recs_new[tag] = span + 1 + if lnum == inner_lvl: + values = (values[:ins_col] + (u('...'),) + + values[ins_col:]) + else: + # sparse col headers do not receive a ... + values = (values[:ins_col] + + (values[ins_col - 1], ) + + values[ins_col:]) + else: + recs_new[tag] = span + # if ins_col lies between tags, all col headers + # get ... + if tag + span == ins_col: + recs_new[ins_col] = 1 + values = (values[:ins_col] + (u('...'),) + + values[ins_col:]) + records = recs_new + inner_lvl = len(level_lengths) - 1 + if lnum == inner_lvl: + records[ins_col] = 1 + else: + recs_new = {} + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + else: + recs_new[tag] = span + recs_new[ins_col] = 1 + records = recs_new + values = (values[:ins_col] + [u('...')] + + values[ins_col:]) + + # see gh-22579 + # Column Offset Bug with to_html(index=False) with + # MultiIndex Columns and Index. + # Initially fill row with blank cells before column names. + # TODO: Refactor to remove code duplication with code + # block below for standard columns index. + row = [''] * (self.row_levels - 1) + if self.fmt.index or self.show_col_idx_names: + # see gh-22747 + # If to_html(index_names=False) do not show columns + # index names. + # TODO: Refactor to use _get_column_name_list from + # DataFrameFormatter class and create a + # _get_formatted_column_labels function for code + # parity with DataFrameFormatter class. + if self.fmt.show_index_names: + name = self.columns.names[lnum] + row.append(pprint_thing(name or '')) + else: + row.append('') + + tags = {} + j = len(row) + for i, v in enumerate(values): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + continue + j += 1 + row.append(v) + self.write_tr(row, indent, self.indent_delta, tags=tags, + header=True) + else: + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # Initially fill row with blank cells before column names. + # TODO: Refactor to remove code duplication with code block + # above for columns MultiIndex. + row = [''] * (self.row_levels - 1) + if self.fmt.index or self.show_col_idx_names: + # see gh-22747 + # If to_html(index_names=False) do not show columns + # index names. + # TODO: Refactor to use _get_column_name_list from + # DataFrameFormatter class. + if self.fmt.show_index_names: + row.append(self.columns.name or '') + else: + row.append('') + row.extend(self.columns) + align = self.fmt.justify + + if truncate_h: + ins_col = self.row_levels + self.fmt.tr_col_num + row.insert(ins_col, '...') + + self.write_tr(row, indent, self.indent_delta, header=True, + align=align) + + def _write_row_header(self, indent): + truncate_h = self.fmt.truncate_h + row = ([x if x is not None else '' for x in self.frame.index.names] + + [''] * (self.ncols + (1 if truncate_h else 0))) + self.write_tr(row, indent, self.indent_delta, header=True) + + def _write_header(self, indent): + self.write('', indent) + + if self.fmt.header: + self._write_col_header(indent + self.indent_delta) + + if self.show_row_idx_names: + self._write_row_header(indent + self.indent_delta) + + self.write('', indent) + + def _write_body(self, indent): + self.write('', indent) + fmt_values = {i: self.fmt._format_col(i) for i in range(self.ncols)} + + # write values + if self.fmt.index and isinstance(self.frame.index, ABCMultiIndex): + self._write_hierarchical_rows( + fmt_values, indent + self.indent_delta) + else: + self._write_regular_rows( + fmt_values, indent + self.indent_delta) + + self.write('', indent) + + def _write_regular_rows(self, fmt_values, indent): + truncate_h = self.fmt.truncate_h + truncate_v = self.fmt.truncate_v + + nrows = len(self.fmt.tr_frame) + + if self.fmt.index: + fmt = self.fmt._get_formatter('__index__') + if fmt is not None: + index_values = self.fmt.tr_frame.index.map(fmt) + else: + index_values = self.fmt.tr_frame.index.format() + + row = [] + for i in range(nrows): + + if truncate_v and i == (self.fmt.tr_row_num): + str_sep_row = ['...'] * len(row) + self.write_tr(str_sep_row, indent, self.indent_delta, + tags=None, nindex_levels=self.row_levels) + + row = [] + if self.fmt.index: + row.append(index_values[i]) + # see gh-22579 + # Column misalignment also occurs for + # a standard index when the columns index is named. + # Add blank cell before data cells. + elif self.show_col_idx_names: + row.append('') + row.extend(fmt_values[j][i] for j in range(self.ncols)) + + if truncate_h: + dot_col_ix = self.fmt.tr_col_num + self.row_levels + row.insert(dot_col_ix, '...') + self.write_tr(row, indent, self.indent_delta, tags=None, + nindex_levels=self.row_levels) + + def _write_hierarchical_rows(self, fmt_values, indent): + template = 'rowspan="{span}" valign="top"' + + truncate_h = self.fmt.truncate_h + truncate_v = self.fmt.truncate_v + frame = self.fmt.tr_frame + nrows = len(frame) + + idx_values = frame.index.format(sparsify=False, adjoin=False, + names=False) + idx_values = lzip(*idx_values) + + if self.fmt.sparsify: + # GH3547 + sentinel = com.sentinel_factory() + levels = frame.index.format(sparsify=sentinel, adjoin=False, + names=False) + + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + if truncate_v: + # Insert ... row and adjust idx_values and + # level_lengths to take this into account. + ins_row = self.fmt.tr_row_num + inserted = False + for lnum, records in enumerate(level_lengths): + rec_new = {} + for tag, span in list(records.items()): + if tag >= ins_row: + rec_new[tag + 1] = span + elif tag + span > ins_row: + rec_new[tag] = span + 1 + + # GH 14882 - Make sure insertion done once + if not inserted: + dot_row = list(idx_values[ins_row - 1]) + dot_row[-1] = u('...') + idx_values.insert(ins_row, tuple(dot_row)) + inserted = True + else: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = u('...') + idx_values[ins_row] = tuple(dot_row) + else: + rec_new[tag] = span + # If ins_row lies between tags, all cols idx cols + # receive ... + if tag + span == ins_row: + rec_new[ins_row] = 1 + if lnum == 0: + idx_values.insert(ins_row, tuple( + [u('...')] * len(level_lengths))) + + # GH 14882 - Place ... in correct level + elif inserted: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = u('...') + idx_values[ins_row] = tuple(dot_row) + level_lengths[lnum] = rec_new + + level_lengths[inner_lvl][ins_row] = 1 + for ix_col in range(len(fmt_values)): + fmt_values[ix_col].insert(ins_row, '...') + nrows += 1 + + for i in range(nrows): + row = [] + tags = {} + + sparse_offset = 0 + j = 0 + for records, v in zip(level_lengths, idx_values[i]): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + sparse_offset += 1 + continue + + j += 1 + row.append(v) + + row.extend(fmt_values[j][i] for j in range(self.ncols)) + if truncate_h: + row.insert(self.row_levels - sparse_offset + + self.fmt.tr_col_num, '...') + self.write_tr(row, indent, self.indent_delta, tags=tags, + nindex_levels=len(levels) - sparse_offset) + else: + row = [] + for i in range(len(frame)): + if truncate_v and i == (self.fmt.tr_row_num): + str_sep_row = ['...'] * len(row) + self.write_tr(str_sep_row, indent, self.indent_delta, + tags=None, nindex_levels=self.row_levels) + + idx_values = list(zip(*frame.index.format( + sparsify=False, adjoin=False, names=False))) + row = [] + row.extend(idx_values[i]) + row.extend(fmt_values[j][i] for j in range(self.ncols)) + if truncate_h: + row.insert(self.row_levels + self.fmt.tr_col_num, '...') + self.write_tr(row, indent, self.indent_delta, tags=None, + nindex_levels=frame.index.nlevels) + + +class NotebookFormatter(HTMLFormatter): + """ + Internal class for formatting output data in html for display in Jupyter + Notebooks. This class is intended for functionality specific to + DataFrame._repr_html_() and DataFrame.to_html(notebook=True) + """ + + def write_style(self): + # We use the "scoped" attribute here so that the desired + # style properties for the data frame are not then applied + # throughout the entire notebook. + template_first = """\ + """ + template_select = """\ + .dataframe %s { + %s: %s; + }""" + element_props = [('tbody tr th:only-of-type', + 'vertical-align', + 'middle'), + ('tbody tr th', + 'vertical-align', + 'top')] + if isinstance(self.columns, ABCMultiIndex): + element_props.append(('thead tr th', + 'text-align', + 'left')) + if self.show_row_idx_names: + element_props.append(('thead tr:last-of-type th', + 'text-align', + 'right')) + else: + element_props.append(('thead th', + 'text-align', + 'right')) + template_mid = '\n\n'.join(map(lambda t: template_select % t, + element_props)) + template = dedent('\n'.join((template_first, + template_mid, + template_last))) + self.write(template) + + def render(self): + self.write('
') + self.write_style() + super(NotebookFormatter, self).render() + self.write('
') + return self.elements diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/latex.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/latex.py new file mode 100644 index 0000000000000000000000000000000000000000..90be3364932a2b84d44984e5b7a34b92fedf167d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/latex.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data in Latex. +""" +from __future__ import print_function + +import numpy as np + +from pandas.compat import map, range, u, zip + +from pandas.core.dtypes.generic import ABCMultiIndex + +from pandas import compat + +from pandas.io.formats.format import TableFormatter + + +class LatexFormatter(TableFormatter): + """ Used to render a DataFrame to a LaTeX tabular/longtable environment + output. + + Parameters + ---------- + formatter : `DataFrameFormatter` + column_format : str, default None + The columns format as specified in `LaTeX table format + `__ e.g 'rcl' for 3 columns + longtable : boolean, default False + Use a longtable environment instead of tabular. + + See Also + -------- + HTMLFormatter + """ + + def __init__(self, formatter, column_format=None, longtable=False, + multicolumn=False, multicolumn_format=None, multirow=False): + self.fmt = formatter + self.frame = self.fmt.frame + self.bold_rows = self.fmt.kwds.get('bold_rows', False) + self.column_format = column_format + self.longtable = longtable + self.multicolumn = multicolumn + self.multicolumn_format = multicolumn_format + self.multirow = multirow + + def write_result(self, buf): + """ + Render a DataFrame to a LaTeX tabular/longtable environment output. + """ + + # string representation of the columns + if len(self.frame.columns) == 0 or len(self.frame.index) == 0: + info_line = (u('Empty {name}\nColumns: {col}\nIndex: {idx}') + .format(name=type(self.frame).__name__, + col=self.frame.columns, + idx=self.frame.index)) + strcols = [[info_line]] + else: + strcols = self.fmt._to_str_columns() + + def get_col_type(dtype): + if issubclass(dtype.type, np.number): + return 'r' + else: + return 'l' + + # reestablish the MultiIndex that has been joined by _to_str_column + if self.fmt.index and isinstance(self.frame.index, ABCMultiIndex): + out = self.frame.index.format( + adjoin=False, sparsify=self.fmt.sparsify, + names=self.fmt.has_index_names, na_rep=self.fmt.na_rep + ) + + # index.format will sparsify repeated entries with empty strings + # so pad these with some empty space + def pad_empties(x): + for pad in reversed(x): + if pad: + break + return [x[0]] + [i if i else ' ' * len(pad) for i in x[1:]] + out = (pad_empties(i) for i in out) + + # Add empty spaces for each column level + clevels = self.frame.columns.nlevels + out = [[' ' * len(i[-1])] * clevels + i for i in out] + + # Add the column names to the last index column + cnames = self.frame.columns.names + if any(cnames): + new_names = [i if i else '{}' for i in cnames] + out[self.frame.index.nlevels - 1][:clevels] = new_names + + # Get rid of old multiindex column and add new ones + strcols = out + strcols[1:] + + column_format = self.column_format + if column_format is None: + dtypes = self.frame.dtypes._values + column_format = ''.join(map(get_col_type, dtypes)) + if self.fmt.index: + index_format = 'l' * self.frame.index.nlevels + column_format = index_format + column_format + elif not isinstance(column_format, + compat.string_types): # pragma: no cover + raise AssertionError('column_format must be str or unicode, ' + 'not {typ}'.format(typ=type(column_format))) + + if not self.longtable: + buf.write('\\begin{{tabular}}{{{fmt}}}\n' + .format(fmt=column_format)) + buf.write('\\toprule\n') + else: + buf.write('\\begin{{longtable}}{{{fmt}}}\n' + .format(fmt=column_format)) + buf.write('\\toprule\n') + + ilevels = self.frame.index.nlevels + clevels = self.frame.columns.nlevels + nlevels = clevels + if self.fmt.has_index_names and self.fmt.show_index_names: + nlevels += 1 + strrows = list(zip(*strcols)) + self.clinebuf = [] + + for i, row in enumerate(strrows): + if i == nlevels and self.fmt.header: + buf.write('\\midrule\n') # End of header + if self.longtable: + buf.write('\\endhead\n') + buf.write('\\midrule\n') + buf.write('\\multicolumn{{{n}}}{{r}}{{{{Continued on next ' + 'page}}}} \\\\\n'.format(n=len(row))) + buf.write('\\midrule\n') + buf.write('\\endfoot\n\n') + buf.write('\\bottomrule\n') + buf.write('\\endlastfoot\n') + if self.fmt.kwds.get('escape', True): + # escape backslashes first + crow = [(x.replace('\\', '\\textbackslash ') + .replace('_', '\\_') + .replace('%', '\\%').replace('$', '\\$') + .replace('#', '\\#').replace('{', '\\{') + .replace('}', '\\}').replace('~', '\\textasciitilde ') + .replace('^', '\\textasciicircum ') + .replace('&', '\\&') + if (x and x != '{}') else '{}') for x in row] + else: + crow = [x if x else '{}' for x in row] + if self.bold_rows and self.fmt.index: + # bold row labels + crow = ['\\textbf{{{x}}}'.format(x=x) + if j < ilevels and x.strip() not in ['', '{}'] else x + for j, x in enumerate(crow)] + if i < clevels and self.fmt.header and self.multicolumn: + # sum up columns to multicolumns + crow = self._format_multicolumn(crow, ilevels) + if (i >= nlevels and self.fmt.index and self.multirow and + ilevels > 1): + # sum up rows to multirows + crow = self._format_multirow(crow, ilevels, i, strrows) + buf.write(' & '.join(crow)) + buf.write(' \\\\\n') + if self.multirow and i < len(strrows) - 1: + self._print_cline(buf, i, len(strcols)) + + if not self.longtable: + buf.write('\\bottomrule\n') + buf.write('\\end{tabular}\n') + else: + buf.write('\\end{longtable}\n') + + def _format_multicolumn(self, row, ilevels): + r""" + Combine columns belonging to a group to a single multicolumn entry + according to self.multicolumn_format + + e.g.: + a & & & b & c & + will become + \multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c} + """ + row2 = list(row[:ilevels]) + ncol = 1 + coltext = '' + + def append_col(): + # write multicolumn if needed + if ncol > 1: + row2.append('\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}' + .format(ncol=ncol, fmt=self.multicolumn_format, + txt=coltext.strip())) + # don't modify where not needed + else: + row2.append(coltext) + for c in row[ilevels:]: + # if next col has text, write the previous + if c.strip(): + if coltext: + append_col() + coltext = c + ncol = 1 + # if not, add it to the previous multicolumn + else: + ncol += 1 + # write last column name + if coltext: + append_col() + return row2 + + def _format_multirow(self, row, ilevels, i, rows): + r""" + Check following rows, whether row should be a multirow + + e.g.: becomes: + a & 0 & \multirow{2}{*}{a} & 0 & + & 1 & & 1 & + b & 0 & \cline{1-2} + b & 0 & + """ + for j in range(ilevels): + if row[j].strip(): + nrow = 1 + for r in rows[i + 1:]: + if not r[j].strip(): + nrow += 1 + else: + break + if nrow > 1: + # overwrite non-multirow entry + row[j] = '\\multirow{{{nrow:d}}}{{*}}{{{row:s}}}'.format( + nrow=nrow, row=row[j].strip()) + # save when to end the current block with \cline + self.clinebuf.append([i + nrow - 1, j + 1]) + return row + + def _print_cline(self, buf, i, icol): + """ + Print clines after multirow-blocks are finished + """ + for cl in self.clinebuf: + if cl[0] == i: + buf.write('\\cline{{{cl:d}-{icol:d}}}\n' + .format(cl=cl[1], icol=icol)) + # remove entries that have been written to buffer + self.clinebuf = [x for x in self.clinebuf if x[0] != i] diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/printing.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/printing.py new file mode 100644 index 0000000000000000000000000000000000000000..6d45d1e5dfceefea0aeebad8f450bfadf45c67a2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/printing.py @@ -0,0 +1,435 @@ +""" +printing tools +""" + +import sys + +from pandas.compat import u + +from pandas.core.dtypes.inference import is_sequence + +from pandas import compat +from pandas.core.config import get_option + + +def adjoin(space, *lists, **kwargs): + """ + Glues together two sets of strings using the amount of space requested. + The idea is to prettify. + + ---------- + space : int + number of spaces for padding + lists : str + list of str which being joined + strlen : callable + function used to calculate the length of each str. Needed for unicode + handling. + justfunc : callable + function used to justify str. Needed for unicode handling. + """ + strlen = kwargs.pop('strlen', len) + justfunc = kwargs.pop('justfunc', justify) + + out_lines = [] + newLists = [] + lengths = [max(map(strlen, x)) + space for x in lists[:-1]] + # not the last one + lengths.append(max(map(len, lists[-1]))) + maxLen = max(map(len, lists)) + for i, lst in enumerate(lists): + nl = justfunc(lst, lengths[i], mode='left') + nl.extend([' ' * lengths[i]] * (maxLen - len(lst))) + newLists.append(nl) + toJoin = zip(*newLists) + for lines in toJoin: + out_lines.append(_join_unicode(lines)) + return _join_unicode(out_lines, sep='\n') + + +def justify(texts, max_len, mode='right'): + """ + Perform ljust, center, rjust against string or list-like + """ + if mode == 'left': + return [x.ljust(max_len) for x in texts] + elif mode == 'center': + return [x.center(max_len) for x in texts] + else: + return [x.rjust(max_len) for x in texts] + + +def _join_unicode(lines, sep=''): + try: + return sep.join(lines) + except UnicodeDecodeError: + sep = compat.text_type(sep) + return sep.join([x.decode('utf-8') if isinstance(x, str) else x + for x in lines]) + + +# Unicode consolidation +# --------------------- +# +# pprinting utility functions for generating Unicode text or +# bytes(3.x)/str(2.x) representations of objects. +# Try to use these as much as possible rather then rolling your own. +# +# When to use +# ----------- +# +# 1) If you're writing code internal to pandas (no I/O directly involved), +# use pprint_thing(). +# +# It will always return unicode text which can handled by other +# parts of the package without breakage. +# +# 2) if you need to write something out to file, use +# pprint_thing_encoded(encoding). +# +# If no encoding is specified, it defaults to utf-8. Since encoding pure +# ascii with utf-8 is a no-op you can safely use the default utf-8 if you're +# working with straight ascii. + + +def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds): + """ + internal. pprinter for iterables. you should probably use pprint_thing() + rather then calling this directly. + + bounds length of printed sequence, depending on options + """ + if isinstance(seq, set): + fmt = u("{{{body}}}") + else: + fmt = u("[{body}]") if hasattr(seq, '__setitem__') else u("({body})") + + if max_seq_items is False: + nitems = len(seq) + else: + nitems = max_seq_items or get_option("max_seq_items") or len(seq) + + s = iter(seq) + # handle sets, no slicing + r = [pprint_thing(next(s), + _nest_lvl + 1, max_seq_items=max_seq_items, **kwds) + for i in range(min(nitems, len(seq)))] + body = ", ".join(r) + + if nitems < len(seq): + body += ", ..." + elif isinstance(seq, tuple) and len(seq) == 1: + body += ',' + + return fmt.format(body=body) + + +def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds): + """ + internal. pprinter for iterables. you should probably use pprint_thing() + rather then calling this directly. + """ + fmt = u("{{{things}}}") + pairs = [] + + pfmt = u("{key}: {val}") + + if max_seq_items is False: + nitems = len(seq) + else: + nitems = max_seq_items or get_option("max_seq_items") or len(seq) + + for k, v in list(seq.items())[:nitems]: + pairs.append( + pfmt.format( + key=pprint_thing(k, _nest_lvl + 1, + max_seq_items=max_seq_items, **kwds), + val=pprint_thing(v, _nest_lvl + 1, + max_seq_items=max_seq_items, **kwds))) + + if nitems < len(seq): + return fmt.format(things=", ".join(pairs) + ", ...") + else: + return fmt.format(things=", ".join(pairs)) + + +def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False, + quote_strings=False, max_seq_items=None): + """ + This function is the sanctioned way of converting objects + to a unicode representation. + + properly handles nested sequences containing unicode strings + (unicode(object) does not) + + Parameters + ---------- + thing : anything to be formatted + _nest_lvl : internal use only. pprint_thing() is mutually-recursive + with pprint_sequence, this argument is used to keep track of the + current nesting level, and limit it. + escape_chars : list or dict, optional + Characters to escape. If a dict is passed the values are the + replacements + default_escapes : bool, default False + Whether the input escape characters replaces or adds to the defaults + max_seq_items : False, int, default None + Pass thru to other pretty printers to limit sequence printing + + Returns + ------- + result - unicode object on py2, str on py3. Always Unicode. + + """ + + def as_escaped_unicode(thing, escape_chars=escape_chars): + # Unicode is fine, else we try to decode using utf-8 and 'replace' + # if that's not it either, we have no way of knowing and the user + # should deal with it himself. + + try: + result = compat.text_type(thing) # we should try this first + except UnicodeDecodeError: + # either utf-8 or we replace errors + result = str(thing).decode('utf-8', "replace") + + translate = {'\t': r'\t', '\n': r'\n', '\r': r'\r', } + if isinstance(escape_chars, dict): + if default_escapes: + translate.update(escape_chars) + else: + translate = escape_chars + escape_chars = list(escape_chars.keys()) + else: + escape_chars = escape_chars or tuple() + for c in escape_chars: + result = result.replace(c, translate[c]) + + return compat.text_type(result) + + if (compat.PY3 and hasattr(thing, '__next__')) or hasattr(thing, 'next'): + return compat.text_type(thing) + elif (isinstance(thing, dict) and + _nest_lvl < get_option("display.pprint_nest_depth")): + result = _pprint_dict(thing, _nest_lvl, quote_strings=True, + max_seq_items=max_seq_items) + elif (is_sequence(thing) and + _nest_lvl < get_option("display.pprint_nest_depth")): + result = _pprint_seq(thing, _nest_lvl, escape_chars=escape_chars, + quote_strings=quote_strings, + max_seq_items=max_seq_items) + elif isinstance(thing, compat.string_types) and quote_strings: + if compat.PY3: + fmt = u("'{thing}'") + else: + fmt = u("u'{thing}'") + result = fmt.format(thing=as_escaped_unicode(thing)) + else: + result = as_escaped_unicode(thing) + + return compat.text_type(result) # always unicode + + +def pprint_thing_encoded(object, encoding='utf-8', errors='replace', **kwds): + value = pprint_thing(object) # get unicode representation of object + return value.encode(encoding, errors, **kwds) + + +def _enable_data_resource_formatter(enable): + if 'IPython' not in sys.modules: + # definitely not in IPython + return + from IPython import get_ipython + ip = get_ipython() + if ip is None: + # still not in IPython + return + + formatters = ip.display_formatter.formatters + mimetype = "application/vnd.dataresource+json" + + if enable: + if mimetype not in formatters: + # define tableschema formatter + from IPython.core.formatters import BaseFormatter + + class TableSchemaFormatter(BaseFormatter): + print_method = '_repr_data_resource_' + _return_type = (dict,) + # register it: + formatters[mimetype] = TableSchemaFormatter() + # enable it if it's been disabled: + formatters[mimetype].enabled = True + else: + # unregister tableschema mime-type + if mimetype in formatters: + formatters[mimetype].enabled = False + + +default_pprint = lambda x, max_seq_items=None: \ + pprint_thing(x, escape_chars=('\t', '\r', '\n'), quote_strings=True, + max_seq_items=max_seq_items) + + +def format_object_summary(obj, formatter, is_justify=True, name=None, + indent_for_name=True): + """ + Return the formatted obj as a unicode string + + Parameters + ---------- + obj : object + must be iterable and support __getitem__ + formatter : callable + string formatter for an element + is_justify : boolean + should justify the display + name : name, optional + defaults to the class name of the obj + indent_for_name : bool, default True + Whether subsequent lines should be be indented to + align with the name. + + Returns + ------- + summary string + + """ + from pandas.io.formats.console import get_console_size + from pandas.io.formats.format import _get_adjustment + + display_width, _ = get_console_size() + if display_width is None: + display_width = get_option('display.width') or 80 + if name is None: + name = obj.__class__.__name__ + + if indent_for_name: + name_len = len(name) + space1 = "\n%s" % (' ' * (name_len + 1)) + space2 = "\n%s" % (' ' * (name_len + 2)) + else: + space1 = "\n" + space2 = "\n " # space for the opening '[' + + n = len(obj) + sep = ',' + max_seq_items = get_option('display.max_seq_items') or n + + # are we a truncated display + is_truncated = n > max_seq_items + + # adj can optionally handle unicode eastern asian width + adj = _get_adjustment() + + def _extend_line(s, line, value, display_width, next_line_prefix): + + if (adj.len(line.rstrip()) + adj.len(value.rstrip()) >= + display_width): + s += line.rstrip() + line = next_line_prefix + line += value + return s, line + + def best_len(values): + if values: + return max(adj.len(x) for x in values) + else: + return 0 + + close = u', ' + + if n == 0: + summary = u'[]{}'.format(close) + elif n == 1: + first = formatter(obj[0]) + summary = u'[{}]{}'.format(first, close) + elif n == 2: + first = formatter(obj[0]) + last = formatter(obj[-1]) + summary = u'[{}, {}]{}'.format(first, last, close) + else: + + if n > max_seq_items: + n = min(max_seq_items // 2, 10) + head = [formatter(x) for x in obj[:n]] + tail = [formatter(x) for x in obj[-n:]] + else: + head = [] + tail = [formatter(x) for x in obj] + + # adjust all values to max length if needed + if is_justify: + + # however, if we are not truncated and we are only a single + # line, then don't justify + if (is_truncated or + not (len(', '.join(head)) < display_width and + len(', '.join(tail)) < display_width)): + max_len = max(best_len(head), best_len(tail)) + head = [x.rjust(max_len) for x in head] + tail = [x.rjust(max_len) for x in tail] + + summary = "" + line = space2 + + for i in range(len(head)): + word = head[i] + sep + ' ' + summary, line = _extend_line(summary, line, word, + display_width, space2) + + if is_truncated: + # remove trailing space of last line + summary += line.rstrip() + space2 + '...' + line = space2 + + for i in range(len(tail) - 1): + word = tail[i] + sep + ' ' + summary, line = _extend_line(summary, line, word, + display_width, space2) + + # last value: no sep added + 1 space of width used for trailing ',' + summary, line = _extend_line(summary, line, tail[-1], + display_width - 2, space2) + summary += line + + # right now close is either '' or ', ' + # Now we want to include the ']', but not the maybe space. + close = ']' + close.rstrip(' ') + summary += close + + if len(summary) > (display_width): + summary += space1 + else: # one row + summary += ' ' + + # remove initial space + summary = '[' + summary[len(space2):] + + return summary + + +def format_object_attrs(obj): + """ + Return a list of tuples of the (attr, formatted_value) + for common attrs, including dtype, name, length + + Parameters + ---------- + obj : object + must be iterable + + Returns + ------- + list + + """ + attrs = [] + if hasattr(obj, 'dtype'): + attrs.append(('dtype', "'{}'".format(obj.dtype))) + if getattr(obj, 'name', None) is not None: + attrs.append(('name', default_pprint(obj.name))) + max_seq_items = get_option('display.max_seq_items') or len(obj) + if len(obj) > max_seq_items: + attrs.append(('length', len(obj))) + return attrs diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/style.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/style.py new file mode 100644 index 0000000000000000000000000000000000000000..598453eb92d250576250d653852403480cfa6068 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/io/formats/style.py @@ -0,0 +1,1367 @@ +""" +Module for applying conditional formatting to +DataFrames and Series. +""" + +from collections import defaultdict +from contextlib import contextmanager +import copy +from functools import partial +from itertools import product +from uuid import uuid1 + +import numpy as np + +from pandas.compat import range +from pandas.util._decorators import Appender + +from pandas.core.dtypes.common import is_float, is_string_like +from pandas.core.dtypes.generic import ABCSeries + +import pandas as pd +from pandas.api.types import is_dict_like, is_list_like +import pandas.core.common as com +from pandas.core.config import get_option +from pandas.core.generic import _shared_docs +from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice + +try: + from jinja2 import ( + PackageLoader, Environment, ChoiceLoader, FileSystemLoader + ) +except ImportError: + raise ImportError("pandas.Styler requires jinja2. " + "Please install with `conda install Jinja2`\n" + "or `pip install Jinja2`") + + +try: + import matplotlib.pyplot as plt + from matplotlib import colors + has_mpl = True +except ImportError: + has_mpl = False + no_mpl_message = "{0} requires matplotlib." + + +@contextmanager +def _mpl(func): + if has_mpl: + yield plt, colors + else: + raise ImportError(no_mpl_message.format(func.__name__)) + + +class Styler(object): + """ + Helps style a DataFrame or Series according to the data with HTML and CSS. + + Parameters + ---------- + data : Series or DataFrame + precision : int + precision to round floats to, defaults to pd.options.display.precision + table_styles : list-like, default None + list of {selector: (attr, value)} dicts; see Notes + uuid : str, default None + a unique identifier to avoid CSS collisions; generated automatically + caption : str, default None + caption to attach to the table + cell_ids : bool, default True + If True, each cell will have an ``id`` attribute in their HTML tag. + The ``id`` takes the form ``T__row_col`` + where ```` is the unique identifier, ```` is the row + number and ```` is the column number. + + Attributes + ---------- + env : Jinja2 Environment + template : Jinja2 Template + loader : Jinja2 Loader + + See Also + -------- + pandas.DataFrame.style + + Notes + ----- + Most styling will be done by passing style functions into + ``Styler.apply`` or ``Styler.applymap``. Style functions should + return values with strings containing CSS ``'attr: value'`` that will + be applied to the indicated cells. + + If using in the Jupyter notebook, Styler has defined a ``_repr_html_`` + to automatically render itself. Otherwise call Styler.render to get + the generated HTML. + + CSS classes are attached to the generated HTML + + * Index and Column names include ``index_name`` and ``level`` + where `k` is its level in a MultiIndex + * Index label cells include + + * ``row_heading`` + * ``row`` where `n` is the numeric position of the row + * ``level`` where `k` is the level in a MultiIndex + + * Column label cells include + * ``col_heading`` + * ``col`` where `n` is the numeric position of the column + * ``evel`` where `k` is the level in a MultiIndex + + * Blank cells include ``blank`` + * Data cells include ``data`` + """ + loader = PackageLoader("pandas", "io/formats/templates") + env = Environment( + loader=loader, + trim_blocks=True, + ) + template = env.get_template("html.tpl") + + def __init__(self, data, precision=None, table_styles=None, uuid=None, + caption=None, table_attributes=None, cell_ids=True): + self.ctx = defaultdict(list) + self._todo = [] + + if not isinstance(data, (pd.Series, pd.DataFrame)): + raise TypeError("``data`` must be a Series or DataFrame") + if data.ndim == 1: + data = data.to_frame() + if not data.index.is_unique or not data.columns.is_unique: + raise ValueError("style is not supported for non-unique indices.") + + self.data = data + self.index = data.index + self.columns = data.columns + + self.uuid = uuid + self.table_styles = table_styles + self.caption = caption + if precision is None: + precision = get_option('display.precision') + self.precision = precision + self.table_attributes = table_attributes + self.hidden_index = False + self.hidden_columns = [] + self.cell_ids = cell_ids + + # display_funcs maps (row, col) -> formatting function + + def default_display_func(x): + if is_float(x): + return '{:>.{precision}g}'.format(x, precision=self.precision) + else: + return x + + self._display_funcs = defaultdict(lambda: default_display_func) + + def _repr_html_(self): + """ + Hooks into Jupyter notebook rich display system. + """ + return self.render() + + @Appender(_shared_docs['to_excel'] % dict( + axes='index, columns', klass='Styler', + axes_single_arg="{0 or 'index', 1 or 'columns'}", + optional_by=""" + by : str or list of str + Name or list of names which refer to the axis items.""", + versionadded_to_excel='\n .. versionadded:: 0.20')) + def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', + float_format=None, columns=None, header=True, index=True, + index_label=None, startrow=0, startcol=0, engine=None, + merge_cells=True, encoding=None, inf_rep='inf', verbose=True, + freeze_panes=None): + + from pandas.io.formats.excel import ExcelFormatter + formatter = ExcelFormatter(self, na_rep=na_rep, cols=columns, + header=header, + float_format=float_format, index=index, + index_label=index_label, + merge_cells=merge_cells, + inf_rep=inf_rep) + formatter.write(excel_writer, sheet_name=sheet_name, startrow=startrow, + startcol=startcol, freeze_panes=freeze_panes, + engine=engine) + + def _translate(self): + """ + Convert the DataFrame in `self.data` and the attrs from `_build_styles` + into a dictionary of {head, body, uuid, cellstyle}. + """ + table_styles = self.table_styles or [] + caption = self.caption + ctx = self.ctx + precision = self.precision + hidden_index = self.hidden_index + hidden_columns = self.hidden_columns + uuid = self.uuid or str(uuid1()).replace("-", "_") + ROW_HEADING_CLASS = "row_heading" + COL_HEADING_CLASS = "col_heading" + INDEX_NAME_CLASS = "index_name" + + DATA_CLASS = "data" + BLANK_CLASS = "blank" + BLANK_VALUE = "" + + def format_attr(pair): + return "{key}={value}".format(**pair) + + # for sparsifying a MultiIndex + idx_lengths = _get_level_lengths(self.index) + col_lengths = _get_level_lengths(self.columns, hidden_columns) + + cell_context = dict() + + n_rlvls = self.data.index.nlevels + n_clvls = self.data.columns.nlevels + rlabels = self.data.index.tolist() + clabels = self.data.columns.tolist() + + if n_rlvls == 1: + rlabels = [[x] for x in rlabels] + if n_clvls == 1: + clabels = [[x] for x in clabels] + clabels = list(zip(*clabels)) + + cellstyle = [] + head = [] + + for r in range(n_clvls): + # Blank for Index columns... + row_es = [{"type": "th", + "value": BLANK_VALUE, + "display_value": BLANK_VALUE, + "is_visible": not hidden_index, + "class": " ".join([BLANK_CLASS])}] * (n_rlvls - 1) + + # ... except maybe the last for columns.names + name = self.data.columns.names[r] + cs = [BLANK_CLASS if name is None else INDEX_NAME_CLASS, + "level{lvl}".format(lvl=r)] + name = BLANK_VALUE if name is None else name + row_es.append({"type": "th", + "value": name, + "display_value": name, + "class": " ".join(cs), + "is_visible": not hidden_index}) + + if clabels: + for c, value in enumerate(clabels[r]): + cs = [COL_HEADING_CLASS, "level{lvl}".format(lvl=r), + "col{col}".format(col=c)] + cs.extend(cell_context.get( + "col_headings", {}).get(r, {}).get(c, [])) + es = { + "type": "th", + "value": value, + "display_value": value, + "class": " ".join(cs), + "is_visible": _is_visible(c, r, col_lengths), + } + colspan = col_lengths.get((r, c), 0) + if colspan > 1: + es["attributes"] = [ + format_attr({"key": "colspan", "value": colspan}) + ] + row_es.append(es) + head.append(row_es) + + if (self.data.index.names and + com._any_not_none(*self.data.index.names) and + not hidden_index): + index_header_row = [] + + for c, name in enumerate(self.data.index.names): + cs = [INDEX_NAME_CLASS, + "level{lvl}".format(lvl=c)] + name = '' if name is None else name + index_header_row.append({"type": "th", "value": name, + "class": " ".join(cs)}) + + index_header_row.extend( + [{"type": "th", + "value": BLANK_VALUE, + "class": " ".join([BLANK_CLASS]) + }] * (len(clabels[0]) - len(hidden_columns))) + + head.append(index_header_row) + + body = [] + for r, idx in enumerate(self.data.index): + row_es = [] + for c, value in enumerate(rlabels[r]): + rid = [ROW_HEADING_CLASS, "level{lvl}".format(lvl=c), + "row{row}".format(row=r)] + es = { + "type": "th", + "is_visible": (_is_visible(r, c, idx_lengths) and + not hidden_index), + "value": value, + "display_value": value, + "id": "_".join(rid[1:]), + "class": " ".join(rid) + } + rowspan = idx_lengths.get((c, r), 0) + if rowspan > 1: + es["attributes"] = [ + format_attr({"key": "rowspan", "value": rowspan}) + ] + row_es.append(es) + + for c, col in enumerate(self.data.columns): + cs = [DATA_CLASS, "row{row}".format(row=r), + "col{col}".format(col=c)] + cs.extend(cell_context.get("data", {}).get(r, {}).get(c, [])) + formatter = self._display_funcs[(r, c)] + value = self.data.iloc[r, c] + row_dict = {"type": "td", + "value": value, + "class": " ".join(cs), + "display_value": formatter(value), + "is_visible": (c not in hidden_columns)} + # only add an id if the cell has a style + if (self.cell_ids or + not(len(ctx[r, c]) == 1 and ctx[r, c][0] == '')): + row_dict["id"] = "_".join(cs[1:]) + row_es.append(row_dict) + props = [] + for x in ctx[r, c]: + # have to handle empty styles like [''] + if x.count(":"): + props.append(x.split(":")) + else: + props.append(['', '']) + cellstyle.append({'props': props, + 'selector': "row{row}_col{col}" + .format(row=r, col=c)}) + body.append(row_es) + + table_attr = self.table_attributes + use_mathjax = get_option("display.html.use_mathjax") + if not use_mathjax: + table_attr = table_attr or '' + if 'class="' in table_attr: + table_attr = table_attr.replace('class="', + 'class="tex2jax_ignore ') + else: + table_attr += ' class="tex2jax_ignore"' + + return dict(head=head, cellstyle=cellstyle, body=body, uuid=uuid, + precision=precision, table_styles=table_styles, + caption=caption, table_attributes=table_attr) + + def format(self, formatter, subset=None): + """ + Format the text display value of cells. + + .. versionadded:: 0.18.0 + + Parameters + ---------- + formatter : str, callable, or dict + subset : IndexSlice + An argument to ``DataFrame.loc`` that restricts which elements + ``formatter`` is applied to. + + Returns + ------- + self : Styler + + Notes + ----- + + ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where + ``a`` is one of + + - str: this will be wrapped in: ``a.format(x)`` + - callable: called with the value of an individual cell + + The default display value for numeric values is the "general" (``g``) + format with ``pd.options.display.precision`` precision. + + Examples + -------- + + >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b']) + >>> df.style.format("{:.2%}") + >>> df['c'] = ['a', 'b', 'c', 'd'] + >>> df.style.format({'c': str.upper}) + """ + if subset is None: + row_locs = range(len(self.data)) + col_locs = range(len(self.data.columns)) + else: + subset = _non_reducing_slice(subset) + if len(subset) == 1: + subset = subset, self.data.columns + + sub_df = self.data.loc[subset] + row_locs = self.data.index.get_indexer_for(sub_df.index) + col_locs = self.data.columns.get_indexer_for(sub_df.columns) + + if is_dict_like(formatter): + for col, col_formatter in formatter.items(): + # formatter must be callable, so '{}' are converted to lambdas + col_formatter = _maybe_wrap_formatter(col_formatter) + col_num = self.data.columns.get_indexer_for([col])[0] + + for row_num in row_locs: + self._display_funcs[(row_num, col_num)] = col_formatter + else: + # single scalar to format all cells with + locs = product(*(row_locs, col_locs)) + for i, j in locs: + formatter = _maybe_wrap_formatter(formatter) + self._display_funcs[(i, j)] = formatter + return self + + def render(self, **kwargs): + """ + Render the built up styles to HTML. + + Parameters + ---------- + `**kwargs` : Any additional keyword arguments are passed through + to ``self.template.render``. This is useful when you need to provide + additional variables for a custom template. + + .. versionadded:: 0.20 + + Returns + ------- + rendered : str + the rendered HTML + + Notes + ----- + ``Styler`` objects have defined the ``_repr_html_`` method + which automatically calls ``self.render()`` when it's the + last item in a Notebook cell. When calling ``Styler.render()`` + directly, wrap the result in ``IPython.display.HTML`` to view + the rendered HTML in the notebook. + + Pandas uses the following keys in render. Arguments passed + in ``**kwargs`` take precedence, so think carefully if you want + to override them: + + * head + * cellstyle + * body + * uuid + * precision + * table_styles + * caption + * table_attributes + """ + self._compute() + # TODO: namespace all the pandas keys + d = self._translate() + # filter out empty styles, every cell will have a class + # but the list of props may just be [['', '']]. + # so we have the neested anys below + trimmed = [x for x in d['cellstyle'] + if any(any(y) for y in x['props'])] + d['cellstyle'] = trimmed + d.update(kwargs) + return self.template.render(**d) + + def _update_ctx(self, attrs): + """ + Update the state of the Styler. + + Collects a mapping of {index_label: [': ']}. + + attrs : Series or DataFrame + should contain strings of ': ;: ' + Whitespace shouldn't matter and the final trailing ';' shouldn't + matter. + """ + for row_label, v in attrs.iterrows(): + for col_label, col in v.iteritems(): + i = self.index.get_indexer([row_label])[0] + j = self.columns.get_indexer([col_label])[0] + for pair in col.rstrip(";").split(";"): + self.ctx[(i, j)].append(pair) + + def _copy(self, deepcopy=False): + styler = Styler(self.data, precision=self.precision, + caption=self.caption, uuid=self.uuid, + table_styles=self.table_styles) + if deepcopy: + styler.ctx = copy.deepcopy(self.ctx) + styler._todo = copy.deepcopy(self._todo) + else: + styler.ctx = self.ctx + styler._todo = self._todo + return styler + + def __copy__(self): + """ + Deep copy by default. + """ + return self._copy(deepcopy=False) + + def __deepcopy__(self, memo): + return self._copy(deepcopy=True) + + def clear(self): + """ + Reset the styler, removing any previously applied styles. + Returns None. + """ + self.ctx.clear() + self._todo = [] + + def _compute(self): + """ + Execute the style functions built up in `self._todo`. + + Relies on the conventions that all style functions go through + .apply or .applymap. The append styles to apply as tuples of + + (application method, *args, **kwargs) + """ + r = self + for func, args, kwargs in self._todo: + r = func(self)(*args, **kwargs) + return r + + def _apply(self, func, axis=0, subset=None, **kwargs): + subset = slice(None) if subset is None else subset + subset = _non_reducing_slice(subset) + data = self.data.loc[subset] + if axis is not None: + result = data.apply(func, axis=axis, + result_type='expand', **kwargs) + result.columns = data.columns + else: + result = func(data, **kwargs) + if not isinstance(result, pd.DataFrame): + raise TypeError( + "Function {func!r} must return a DataFrame when " + "passed to `Styler.apply` with axis=None" + .format(func=func)) + if not (result.index.equals(data.index) and + result.columns.equals(data.columns)): + msg = ('Result of {func!r} must have identical index and ' + 'columns as the input'.format(func=func)) + raise ValueError(msg) + + result_shape = result.shape + expected_shape = self.data.loc[subset].shape + if result_shape != expected_shape: + msg = ("Function {func!r} returned the wrong shape.\n" + "Result has shape: {res}\n" + "Expected shape: {expect}".format(func=func, + res=result.shape, + expect=expected_shape)) + raise ValueError(msg) + self._update_ctx(result) + return self + + def apply(self, func, axis=0, subset=None, **kwargs): + """ + Apply a function column-wise, row-wise, or table-wise, + updating the HTML representation with the result. + + Parameters + ---------- + func : function + ``func`` should take a Series or DataFrame (depending + on ``axis``), and return an object with the same shape. + Must return a DataFrame with identical index and + column labels when ``axis=None`` + axis : int, str or None + apply to each column (``axis=0`` or ``'index'``) + or to each row (``axis=1`` or ``'columns'``) or + to the entire DataFrame at once with ``axis=None`` + subset : IndexSlice + a valid indexer to limit ``data`` to *before* applying the + function. Consider using a pandas.IndexSlice + kwargs : dict + pass along to ``func`` + + Returns + ------- + self : Styler + + Notes + ----- + The output shape of ``func`` should match the input, i.e. if + ``x`` is the input row, column, or table (depending on ``axis``), + then ``func(x).shape == x.shape`` should be true. + + This is similar to ``DataFrame.apply``, except that ``axis=None`` + applies the function to the entire DataFrame at once, + rather than column-wise or row-wise. + + Examples + -------- + >>> def highlight_max(x): + ... return ['background-color: yellow' if v == x.max() else '' + for v in x] + ... + >>> df = pd.DataFrame(np.random.randn(5, 2)) + >>> df.style.apply(highlight_max) + """ + self._todo.append((lambda instance: getattr(instance, '_apply'), + (func, axis, subset), kwargs)) + return self + + def _applymap(self, func, subset=None, **kwargs): + func = partial(func, **kwargs) # applymap doesn't take kwargs? + if subset is None: + subset = pd.IndexSlice[:] + subset = _non_reducing_slice(subset) + result = self.data.loc[subset].applymap(func) + self._update_ctx(result) + return self + + def applymap(self, func, subset=None, **kwargs): + """ + Apply a function elementwise, updating the HTML + representation with the result. + + Parameters + ---------- + func : function + ``func`` should take a scalar and return a scalar + subset : IndexSlice + a valid indexer to limit ``data`` to *before* applying the + function. Consider using a pandas.IndexSlice + kwargs : dict + pass along to ``func`` + + Returns + ------- + self : Styler + + See Also + -------- + Styler.where + """ + self._todo.append((lambda instance: getattr(instance, '_applymap'), + (func, subset), kwargs)) + return self + + def where(self, cond, value, other=None, subset=None, **kwargs): + """ + Apply a function elementwise, updating the HTML + representation with a style which is selected in + accordance with the return value of a function. + + .. versionadded:: 0.21.0 + + Parameters + ---------- + cond : callable + ``cond`` should take a scalar and return a boolean + value : str + applied when ``cond`` returns true + other : str + applied when ``cond`` returns false + subset : IndexSlice + a valid indexer to limit ``data`` to *before* applying the + function. Consider using a pandas.IndexSlice + kwargs : dict + pass along to ``cond`` + + Returns + ------- + self : Styler + + See Also + -------- + Styler.applymap + """ + + if other is None: + other = '' + + return self.applymap(lambda val: value if cond(val) else other, + subset=subset, **kwargs) + + def set_precision(self, precision): + """ + Set the precision used to render. + + Parameters + ---------- + precision : int + + Returns + ------- + self : Styler + """ + self.precision = precision + return self + + def set_table_attributes(self, attributes): + """ + Set the table attributes. + + These are the items that show up in the opening ```` tag + in addition to to automatic (by default) id. + + Parameters + ---------- + attributes : string + + Returns + ------- + self : Styler + + Examples + -------- + >>> df = pd.DataFrame(np.random.randn(10, 4)) + >>> df.style.set_table_attributes('class="pure-table"') + # ...
... + """ + self.table_attributes = attributes + return self + + def export(self): + """ + Export the styles to applied to the current Styler. + + Can be applied to a second style with ``Styler.use``. + + Returns + ------- + styles : list + + See Also + -------- + Styler.use + """ + return self._todo + + def use(self, styles): + """ + Set the styles on the current Styler, possibly using styles + from ``Styler.export``. + + Parameters + ---------- + styles : list + list of style functions + + Returns + ------- + self : Styler + + See Also + -------- + Styler.export + """ + self._todo.extend(styles) + return self + + def set_uuid(self, uuid): + """ + Set the uuid for a Styler. + + Parameters + ---------- + uuid : str + + Returns + ------- + self : Styler + """ + self.uuid = uuid + return self + + def set_caption(self, caption): + """ + Set the caption on a Styler + + Parameters + ---------- + caption : str + + Returns + ------- + self : Styler + """ + self.caption = caption + return self + + def set_table_styles(self, table_styles): + """ + Set the table styles on a Styler. + + These are placed in a ``