akaaafk commited on
Commit
789d9e3
·
verified ·
1 Parent(s): df38ea2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Solution/Radar_Solution.ipynb +1056 -0
  2. benchmark/IOL/ioling_hf/evals/results/HuggingFaceTB__SmolLM3-3B__diverse5.scores.jsonl +5 -0
  3. benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen2.5-3B-Instruct__diverse5.scores.jsonl +5 -0
  4. benchmark/IOL/ioling_hf/evals/results/google__gemma-3-12b-it__diverse5.scores.jsonl +5 -0
  5. benchmark/IOL/ioling_hf/evals/results/google__gemma-3-12b-it__strict30.scores.jsonl +30 -0
  6. benchmark/IOL/ioling_hf/evals/results/meta-llama__Llama-3.2-3B-Instruct__diverse5.scores.jsonl +5 -0
  7. benchmark/IOL/ioling_hf/evals/results/meta-llama__Llama-3.2-3B-Instruct__strict30.scores.jsonl +30 -0
  8. benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct.scores.jsonl +3 -0
  9. benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct__diverse5.scores.jsonl +5 -0
  10. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/__init__.py +1 -0
  11. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_assertionnew.py +322 -0
  12. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_assertionold.py +556 -0
  13. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_py2traceback.py +79 -0
  14. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/assertion.py +90 -0
  15. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/code.py +796 -0
  16. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/source.py +410 -0
  17. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/__init__.py +1 -0
  18. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/capture.py +371 -0
  19. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/saferepr.py +71 -0
  20. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/terminalwriter.py +421 -0
  21. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/__init__.py +2 -0
  22. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/log.py +206 -0
  23. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/warning.py +79 -0
  24. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/__init__.py +5 -0
  25. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/cpp.py +905 -0
  26. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/ctokens.py +133 -0
  27. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/lex.py +1099 -0
  28. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/yacc.py +0 -0
  29. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/ygen.py +74 -0
  30. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/San_Juan +0 -0
  31. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/San_Luis +0 -0
  32. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/Tucuman +0 -0
  33. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia +0 -0
  34. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis +0 -0
  35. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Indiana/Knox +0 -0
  36. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Mountain +0 -0
  37. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Newfoundland +0 -0
  38. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Pacific +0 -0
  39. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Saskatchewan +0 -0
  40. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Yukon +0 -0
  41. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Chile/Continental +0 -0
  42. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Chile/EasterIsland +0 -0
  43. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT +0 -0
  44. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+0 +0 -0
  45. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+1 +0 -0
  46. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+10 +0 -0
  47. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+11 +0 -0
  48. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+12 +0 -0
  49. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT-7 +0 -0
  50. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT-8 +0 -0
benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Solution/Radar_Solution.ipynb ADDED
@@ -0,0 +1,1056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "ab23242e-3c5e-4ba6-9cb9-dfc4d8c22321",
6
+ "metadata": {},
7
+ "source": [
8
+ "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
9
+ "\n",
10
+ "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
11
+ "\n",
12
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Radar/Solution/Radar_Solution.ipynb)"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "id": "f2ea67c2-ec81-4ced-b8a4-a19b591376bb",
18
+ "metadata": {},
19
+ "source": [
20
+ "# Radar: Reference Solution"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "id": "97ae6685",
26
+ "metadata": {},
27
+ "source": [
28
+ "## Configs"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "id": "4243ca5d",
35
+ "metadata": {
36
+ "jupyter": {
37
+ "source_hidden": false
38
+ }
39
+ },
40
+ "outputs": [],
41
+ "source": [
42
+ "radar_configs = {\n",
43
+ " 'c': 3e8, \n",
44
+ " 'startFreq': 77e9, \n",
45
+ " 'Tr': 60e-6, # Sweeping frequency time\n",
46
+ " 'Idle_time': 100e-6, # free time\n",
47
+ " 'Fs': 10e6, # Sampling frequency\n",
48
+ " 'Slope': 29.982e12, # chirp slope\n",
49
+ " 'Bandwidth': 60e-6 * 29.982e12, # Transmission signal bandwidth\n",
50
+ " 'BandwidthValid': 0.767539200e9,# Effective bandwidth of the transmitted signal\n",
51
+ " 'range_size': 256, # range size\n",
52
+ " 'azimuth_size': 181, # azimuth size\n",
53
+ " 'elevation_size': 181, # elevation size\n",
54
+ " 'crop_num': 3, # crop some indices in range domain\n",
55
+ " 'n_chirps': 128, # number of chirps in one frame\n",
56
+ " 'min_azimuth': -90, # min radar azimuth\n",
57
+ " 'max_azimuth': 90, # max radar azimuth\n",
58
+ " 'min_elevation': -90, # min radar elevation\n",
59
+ " 'max_elevation': 90, # max radar elevation \n",
60
+ " 'min_range': 1.0, # min radar range\n",
61
+ " 'max_range': 25.0, # max radar range\n",
62
+ " 'range_res': 3e8/(2*0.767539200e9), \n",
63
+ " 'angle_res': 1\n",
64
+ "}\n",
65
+ "\n",
66
+ "dimssnet_configs = {\n",
67
+ " 'n_epoch': 10,\n",
68
+ " 'batch_size': 2,\n",
69
+ " 'learning_rate': 1e-5,\n",
70
+ " 'range_size': 50,\n",
71
+ " 'azimuth_size': 181,\n",
72
+ " 'elevation_size': 181,\n",
73
+ " 'doppler_size': 181, \n",
74
+ " 'min_azimuth': -90, # min radar azimuth\n",
75
+ " 'max_azimuth': 90, # max radar azimuth\n",
76
+ " 'min_elevation': -90, # min radar elevation\n",
77
+ " 'max_elevation': 90, # max radar elevation \n",
78
+ " 'min_range': 1.0, # min radar range\n",
79
+ " 'max_range': 25.0, # max radar range\n",
80
+ "}\n",
81
+ "\n",
82
+ "n_class = 5\n",
83
+ "class_table = {\n",
84
+ " -1: 'background', \n",
85
+ " 0: 'suicase', \n",
86
+ " 1: 'chair', \n",
87
+ " 2: 'person',\n",
88
+ " 3: 'wall'\n",
89
+ "}"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "markdown",
94
+ "id": "c39a54f5",
95
+ "metadata": {},
96
+ "source": [
97
+ "## Models"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "id": "10817ce8",
104
+ "metadata": {
105
+ "jupyter": {
106
+ "source_hidden": false
107
+ }
108
+ },
109
+ "outputs": [],
110
+ "source": [
111
+ "import torch\n",
112
+ "import torch.nn as nn\n",
113
+ "import torch.nn.functional as F\n",
114
+ "\n",
115
+ "class SRA_Encode(nn.Module):\n",
116
+ " def __init__(self):\n",
117
+ " super(SRA_Encode, self).__init__()\n",
118
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
119
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
120
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
121
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
122
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
123
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
124
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
125
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
126
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
127
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
128
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
129
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
130
+ "\n",
131
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
132
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
133
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
134
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
135
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
136
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
137
+ "\n",
138
+ " self.relu = nn.ReLU()\n",
139
+ " \n",
140
+ " def forward(self, x):\n",
141
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
142
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
143
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
144
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
145
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
146
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
147
+ " \n",
148
+ " return x\n",
149
+ "\n",
150
+ "class SRA_Decode(nn.Module):\n",
151
+ " def __init__(self):\n",
152
+ " super(SRA_Decode, self).__init__()\n",
153
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
154
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
155
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
156
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
157
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
158
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
159
+ " self.prelu = nn.PReLU()\n",
160
+ " self.sigmoid = nn.Sigmoid()\n",
161
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
162
+ " dimssnet_configs['azimuth_size']), mode='nearest')\n",
163
+ "\n",
164
+ " def forward(self, x):\n",
165
+ " x = self.prelu(self.convt1(x))\n",
166
+ " x = self.prelu(self.convt2(x))\n",
167
+ " x = self.prelu(self.convt3(x))\n",
168
+ "\n",
169
+ " return x\n",
170
+ "\n",
171
+ "class DRA_Encode(nn.Module):\n",
172
+ " def __init__(self):\n",
173
+ " super(DRA_Encode, self).__init__()\n",
174
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
175
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) # (1 50 181)->(64 50 181)\n",
176
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
177
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (64 50 181)->(64 25 91)\n",
178
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
179
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) # (64 25 91)->(128 25 91)\n",
180
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
181
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (128 25 91)->(128 13 46)\n",
182
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
183
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) # (128 13 46)->(256 13 46)\n",
184
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
185
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (256 13 46)->(256 7 23)\n",
186
+ "\n",
187
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
188
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
189
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
190
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
191
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
192
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
193
+ "\n",
194
+ " self.relu = nn.ReLU()\n",
195
+ " \n",
196
+ " def forward(self, x):\n",
197
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
198
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
199
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
200
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
201
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
202
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
203
+ "\n",
204
+ " return x\n",
205
+ "\n",
206
+ "class DRA_Decode(nn.Module):\n",
207
+ " def __init__(self):\n",
208
+ " super(DRA_Decode, self).__init__()\n",
209
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
210
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (256 7 23)->(128 13 45)\n",
211
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
212
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (128 13 45)->(64 25 89)\n",
213
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
214
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) # (64 25 89)->(32 49 177)\n",
215
+ " self.prelu = nn.PReLU()\n",
216
+ " self.sigmoid = nn.Sigmoid()\n",
217
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
218
+ " dimssnet_configs['elevation_size']), mode='nearest')\n",
219
+ "\n",
220
+ " def forward(self, x):\n",
221
+ " x = self.prelu(self.convt1(x))\n",
222
+ " x = self.prelu(self.convt2(x))\n",
223
+ " x = self.prelu(self.convt3(x))\n",
224
+ "\n",
225
+ " return x\n",
226
+ "\n",
227
+ "class SRE_Encode(nn.Module):\n",
228
+ " def __init__(self):\n",
229
+ " super(SRE_Encode, self).__init__()\n",
230
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
231
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
232
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
233
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
234
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
235
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
236
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
237
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
238
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
239
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
240
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
241
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
242
+ "\n",
243
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
244
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
245
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
246
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
247
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
248
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
249
+ "\n",
250
+ " self.relu = nn.ReLU()\n",
251
+ " \n",
252
+ " def forward(self, x):\n",
253
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
254
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
255
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
256
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
257
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
258
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
259
+ "\n",
260
+ " return x\n",
261
+ "\n",
262
+ "class SRE_Decode(nn.Module):\n",
263
+ " def __init__(self):\n",
264
+ " super(SRE_Decode, self).__init__()\n",
265
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
266
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
267
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
268
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
269
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
270
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
271
+ " self.prelu = nn.PReLU()\n",
272
+ " self.sigmoid = nn.Sigmoid()\n",
273
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
274
+ " dimssnet_configs['elevation_size']), mode='nearest')\n",
275
+ "\n",
276
+ " def forward(self, x):\n",
277
+ " x = self.prelu(self.convt1(x))\n",
278
+ " x = self.prelu(self.convt2(x))\n",
279
+ " x = self.prelu(self.convt3(x))\n",
280
+ "\n",
281
+ " return x\n",
282
+ " \n",
283
+ "class DRE_Encode(nn.Module):\n",
284
+ " def __init__(self):\n",
285
+ " super(DRE_Encode, self).__init__()\n",
286
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
287
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
288
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
289
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
290
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
291
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
292
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
293
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
294
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
295
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
296
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
297
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
298
+ "\n",
299
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
300
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
301
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
302
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
303
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
304
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
305
+ "\n",
306
+ " self.relu = nn.ReLU()\n",
307
+ " \n",
308
+ " def forward(self, x):\n",
309
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
310
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
311
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
312
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
313
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
314
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
315
+ "\n",
316
+ " return x\n",
317
+ "\n",
318
+ "class DRE_Decode(nn.Module):\n",
319
+ " def __init__(self):\n",
320
+ " super(DRE_Decode, self).__init__()\n",
321
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
322
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
323
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
324
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
325
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
326
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
327
+ " self.prelu = nn.PReLU()\n",
328
+ " self.sigmoid = nn.Sigmoid()\n",
329
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
330
+ " dimssnet_configs['elevation_size']), mode='nearest')\n",
331
+ "\n",
332
+ " def forward(self, x):\n",
333
+ " x = self.prelu(self.convt1(x))\n",
334
+ " x = self.prelu(self.convt2(x))\n",
335
+ " x = self.prelu(self.convt3(x))\n",
336
+ "\n",
337
+ " return x\n",
338
+ " \n",
339
+ "class SRD_Encode(nn.Module):\n",
340
+ " def __init__(self):\n",
341
+ " super(SRD_Encode, self).__init__()\n",
342
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
343
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
344
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
345
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
346
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
347
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
348
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
349
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
350
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
351
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
352
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
353
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
354
+ "\n",
355
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
356
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
357
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
358
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
359
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
360
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
361
+ "\n",
362
+ " self.relu = nn.ReLU()\n",
363
+ " \n",
364
+ " def forward(self, x):\n",
365
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
366
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
367
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
368
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
369
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
370
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
371
+ "\n",
372
+ " return x\n",
373
+ "\n",
374
+ "class SRD_Decode(nn.Module):\n",
375
+ " def __init__(self):\n",
376
+ " super(SRD_Decode, self).__init__()\n",
377
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
378
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
379
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
380
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
381
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
382
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
383
+ " self.prelu = nn.PReLU()\n",
384
+ " self.sigmoid = nn.Sigmoid()\n",
385
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
386
+ " dimssnet_configs['doppler_size']), mode='nearest')\n",
387
+ "\n",
388
+ " def forward(self, x):\n",
389
+ " x = self.prelu(self.convt1(x))\n",
390
+ " x = self.prelu(self.convt2(x))\n",
391
+ " x = self.prelu(self.convt3(x))\n",
392
+ "\n",
393
+ " return x\n",
394
+ " \n",
395
+ "class DRD_Encode(nn.Module):\n",
396
+ " def __init__(self):\n",
397
+ " super(DRD_Encode, self).__init__()\n",
398
+ " self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
399
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
400
+ " self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
401
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
402
+ " self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
403
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
404
+ " self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
405
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
406
+ " self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
407
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
408
+ " self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
409
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
410
+ "\n",
411
+ " self.bn1a = nn.BatchNorm2d(num_features=64)\n",
412
+ " self.bn1b = nn.BatchNorm2d(num_features=64)\n",
413
+ " self.bn2a = nn.BatchNorm2d(num_features=128)\n",
414
+ " self.bn2b = nn.BatchNorm2d(num_features=128)\n",
415
+ " self.bn3a = nn.BatchNorm2d(num_features=256)\n",
416
+ " self.bn3b = nn.BatchNorm2d(num_features=256)\n",
417
+ "\n",
418
+ " self.relu = nn.ReLU()\n",
419
+ " \n",
420
+ " def forward(self, x):\n",
421
+ " x = self.relu(self.bn1a(self.conv1a(x)))\n",
422
+ " x = self.relu(self.bn1b(self.conv1b(x)))\n",
423
+ " x = self.relu(self.bn2a(self.conv2a(x)))\n",
424
+ " x = self.relu(self.bn2b(self.conv2b(x)))\n",
425
+ " x = self.relu(self.bn3a(self.conv3a(x)))\n",
426
+ " x = self.relu(self.bn3b(self.conv3b(x)))\n",
427
+ "\n",
428
+ " return x\n",
429
+ "\n",
430
+ "class DRD_Decode(nn.Module):\n",
431
+ " def __init__(self):\n",
432
+ " super(DRD_Decode, self).__init__()\n",
433
+ " self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
434
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
435
+ " self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
436
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
437
+ " self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
438
+ " kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
439
+ " self.prelu = nn.PReLU()\n",
440
+ " self.sigmoid = nn.Sigmoid()\n",
441
+ " self.upsample = nn.Upsample(size=(dimssnet_configs['range_size'],\n",
442
+ " dimssnet_configs['doppler_size']), mode='nearest')\n",
443
+ "\n",
444
+ " def forward(self, x):\n",
445
+ " x = self.prelu(self.convt1(x))\n",
446
+ " x = self.prelu(self.convt2(x))\n",
447
+ " x = self.prelu(self.convt3(x))\n",
448
+ "\n",
449
+ " return x"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "code",
454
+ "execution_count": null,
455
+ "id": "483a5ba6",
456
+ "metadata": {
457
+ "jupyter": {
458
+ "source_hidden": false
459
+ }
460
+ },
461
+ "outputs": [],
462
+ "source": [
463
+ "class DIMSSNet(nn.Module):\n",
464
+ " def __init__(self):\n",
465
+ " super(DIMSSNet, self).__init__()\n",
466
+ " self.encode_sra = SRA_Encode()\n",
467
+ " self.decode_sra = SRA_Decode()\n",
468
+ " self.encode_dra = DRA_Encode()\n",
469
+ " self.decode_dra = DRA_Decode()\n",
470
+ " self.encode_sre = SRE_Encode()\n",
471
+ " self.decode_sre = SRE_Decode()\n",
472
+ " self.encode_dre = DRE_Encode()\n",
473
+ " self.decode_dre = DRE_Decode()\n",
474
+ " self.encode_srd = SRD_Encode()\n",
475
+ " self.decode_srd = SRD_Decode()\n",
476
+ " self.encode_drd = DRD_Encode()\n",
477
+ " self.decode_drd = DRD_Decode()\n",
478
+ " self.fuse_fea = Fuse_fea()\n",
479
+ " # self.fuse_fea = Fuse_fea_2D()\n",
480
+ " \n",
481
+ " def forward(self, x_sra, x_dra, x_sre, x_dre, x_srd, x_drd):\n",
482
+ " x_sra = self.encode_sra(x_sra)\n",
483
+ " feas_sra = self.decode_sra(x_sra) # (B, 32, 50, 181)\n",
484
+ " \n",
485
+ " x_dra = self.encode_dra(x_dra)\n",
486
+ " feas_dra = self.decode_dra(x_dra) # (B, 32, 50, 181)\n",
487
+ " \n",
488
+ " x_sre = self.encode_sre(x_sre)\n",
489
+ " feas_sre = self.decode_sre(x_sre) # (B, 32, 50, 181)\n",
490
+ " \n",
491
+ " x_dre = self.encode_dre(x_dre)\n",
492
+ " feas_dre = self.decode_dre(x_dre) # (B, 32, 50, 181)\n",
493
+ "\n",
494
+ " x_srd = self.encode_sre(x_srd)\n",
495
+ " feas_srd = self.decode_sre(x_srd) # (B, 32, 50, 181)\n",
496
+ " \n",
497
+ " x_drd = self.encode_dre(x_drd)\n",
498
+ " feas_drd = self.decode_dre(x_drd) # (B, 32, 50, 181) \n",
499
+ " \n",
500
+ " feas = self.fuse_fea(feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd) # (B, 32, 50, 181)\n",
501
+ "\n",
502
+ " return feas"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "code",
507
+ "execution_count": null,
508
+ "id": "ddb913e6",
509
+ "metadata": {
510
+ "jupyter": {
511
+ "source_hidden": false
512
+ }
513
+ },
514
+ "outputs": [],
515
+ "source": [
516
+ "range_size=radar_configs['range_size']\n",
517
+ "azimuth_size=radar_configs['azimuth_size']\n",
518
+ "elevation_size=radar_configs['elevation_size']\n",
519
+ "\n",
520
+ "class Fuse_fea(nn.Module):\n",
521
+ " def __init__(self):\n",
522
+ " super(Fuse_fea, self).__init__()\n",
523
+ " self.convt1 = nn.Conv2d(in_channels=192, out_channels=96,\n",
524
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
525
+ " self.convt2 = nn.Conv2d(in_channels=96, out_channels=48,\n",
526
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
527
+ " self.convt3 = nn.Conv2d(in_channels=48, out_channels=24,\n",
528
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
529
+ " self.convt4 = nn.Conv2d(in_channels=24, out_channels=n_class,\n",
530
+ " kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) \n",
531
+ " self.relu = nn.ReLU()\n",
532
+ " self.sigmoid = nn.Sigmoid()\n",
533
+ "\n",
534
+ " def forward(self, feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd):\n",
535
+ " feas_sre = torch.sum(feas_sre, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
536
+ " feas_sre = feas_sre.expand(-1, -1, -1, azimuth_size)\n",
537
+ " \n",
538
+ " feas_dre = torch.sum(feas_dre, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
539
+ " feas_dre = feas_dre.expand(-1, -1, -1, azimuth_size)\n",
540
+ "\n",
541
+ " feas_srd = torch.sum(feas_srd, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
542
+ " feas_srd = feas_srd.expand(-1, -1, -1, azimuth_size)\n",
543
+ "\n",
544
+ " feas_drd = torch.sum(feas_drd, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
545
+ " feas_drd = feas_drd.expand(-1, -1, -1, azimuth_size)\n",
546
+ "\n",
547
+ " # Resize using bilinear interpolation\n",
548
+ " feas_sra = F.interpolate(feas_sra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
549
+ " feas_dra = F.interpolate(feas_dra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
550
+ " feas_sre = F.interpolate(feas_sre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
551
+ " feas_dre = F.interpolate(feas_dre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
552
+ " feas_srd = F.interpolate(feas_srd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
553
+ " feas_drd = F.interpolate(feas_drd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
554
+ " \n",
555
+ " feas_ra = torch.cat((feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd), 1) # 6*(B, 32, 50, 181) -> (B, 192, 50, 181)\n",
556
+ "\n",
557
+ " x = self.relu(self.convt1(feas_ra)) # (B, 192, 50, 181) -> (B, 96, 50, 181)\n",
558
+ " x = self.relu(self.convt2(x)) # (B, 96, 50, 181) -> (B, 48, 50, 181)\n",
559
+ " x = self.relu(self.convt3(x)) # (B, 48, 50, 181) -> (B, 24, 50, 181) \n",
560
+ " x = self.sigmoid(self.convt4(x)) # (B, 24, 50, 181) -> (B, 5, 50, 181)\n",
561
+ " \n",
562
+ " return x\n",
563
+ " "
564
+ ]
565
+ },
566
+ {
567
+ "cell_type": "markdown",
568
+ "id": "b8d86ece",
569
+ "metadata": {},
570
+ "source": [
571
+ "## Utils"
572
+ ]
573
+ },
574
+ {
575
+ "cell_type": "code",
576
+ "execution_count": null,
577
+ "id": "49705a8f",
578
+ "metadata": {
579
+ "jupyter": {
580
+ "source_hidden": false
581
+ }
582
+ },
583
+ "outputs": [],
584
+ "source": [
585
+ "import scipy.io\n",
586
+ "import numpy as np\n",
587
+ "\n",
588
+ "# Define the target size\n",
589
+ "TARGET_HEIGHT = 50\n",
590
+ "TARGET_WIDTH = 181\n",
591
+ "\n",
592
+ "def load_raw_data(file_path):\n",
593
+ " data = scipy.io.loadmat(file_path)\n",
594
+ "\n",
595
+ " # Range-Azimuth Static\n",
596
+ " range_az_static = data['range_az_static']\n",
597
+ " range_az_static_prob = data['range_az_music_average_static_probability']\n",
598
+ " range_az_static_class2_prob = range_az_static_prob[:, :, 1] # 椅子的概率\n",
599
+ "\n",
600
+ " # Range-Elevation Static\n",
601
+ " range_ele_static = data['range_ele_static_all']\n",
602
+ "\n",
603
+ " # Range-Azimuth Dynamic\n",
604
+ " range_az_dynamic = data['range_az_dynamic']\n",
605
+ " range_az_dynamic_prob = data['range_az_music_average_dynamic_probability']\n",
606
+ " range_az_dynamic_class1_prob = range_az_dynamic_prob[:, :, 0] # 人的概率\n",
607
+ "\n",
608
+ " # Range-Elevation Dynamic\n",
609
+ " range_ele_dynamic = data['range_ele_dynamic_all'] \n",
610
+ "\n",
611
+ " return [range_az_static, range_az_dynamic, range_ele_static,\n",
612
+ " range_ele_dynamic, range_az_dynamic_class1_prob, range_az_static_class2_prob]\n",
613
+ "\n",
614
+ "def generate_parameter():\n",
615
+ " parameter = {\n",
616
+ " 'c': 3e8, # the speed of light\n",
617
+ " 'start_freq': 77e9, # starting frequency\n",
618
+ " 'tr': 60e-6, # Sweeping time, that is, the cycle\n",
619
+ " 'samples': 256, # sampling point\n",
620
+ " 'fs': 10e6, # Sampling rate\n",
621
+ " 'tframe_set': 80e-3, # Frame period\n",
622
+ " 'range_bin': 256, # range bin\n",
623
+ " 'chirps': 128, # chirp number\n",
624
+ " 'doppler_bin': 128, # doppler bin\n",
625
+ " 'slope': 29.982e12, # chirp slope\n",
626
+ " 'bandwidth': 29.982e12 * 60e-6, # Effective bandwidth of the transmitted signal\n",
627
+ " 'bandwidth_valid': 256 / 10e6 * 29.982e12, # Transmission signal bandwidth\n",
628
+ " 'center_freq': 77e9 + (29.982e12 * 60e-6) / 2, # center frequency\n",
629
+ " 'lambda': 3e8 / (77e9 + (29.982e12 * 60e-6) / 2), # wavelength\n",
630
+ " 'tx_antenna': [1, 1, 1], # The number of transmitting antennas\n",
631
+ " 'rx_antenna': [1, 1, 1, 1], # Number of receiving antennas\n",
632
+ " 'tx_num': 3, # The number of transmitting antennas\n",
633
+ " 'rx_num': 4, # The number of receiving antennas\n",
634
+ " 'virtual_antenna': 12, # Number of virtual antennas\n",
635
+ " 'dz': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2, # Pitch spacing of the receiving antenna\n",
636
+ " 'dx': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2, # Horizontal spacing of receiving antennas\n",
637
+ " 'num_cpi': 50, # 帧数\n",
638
+ " }\n",
639
+ " return parameter\n",
640
+ "\n"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "markdown",
645
+ "id": "c266f24b",
646
+ "metadata": {},
647
+ "source": [
648
+ "## Dataloaders"
649
+ ]
650
+ },
651
+ {
652
+ "cell_type": "code",
653
+ "execution_count": null,
654
+ "id": "892cfb3a",
655
+ "metadata": {},
656
+ "outputs": [],
657
+ "source": [
658
+ "import os\n",
659
+ "from torch.utils.data import Dataset, DataLoader\n",
660
+ "from sklearn.model_selection import train_test_split\n",
661
+ "\n",
662
+ "class CustomDataset(Dataset):\n",
663
+ " def __init__(self, file_paths, transform=None):\n",
664
+ " self.file_paths = file_paths\n",
665
+ " self.transform = transform\n",
666
+ " self.file_names = [os.path.basename(path) for path in file_paths]\n",
667
+ "\n",
668
+ " def __len__(self):\n",
669
+ " return len(self.file_paths)\n",
670
+ "\n",
671
+ " def __getitem__(self, idx):\n",
672
+ " data = torch.load(self.file_paths[idx], weights_only=True)\n",
673
+ " \n",
674
+ " images = data[:6] #first 6 channels are the heatmaps\n",
675
+ " labels = data[6] #last channel is the label\n",
676
+ " \n",
677
+ " images = images.float() \n",
678
+ " labels = labels.long() \n",
679
+ " labels = labels + 1 #labels are -1 to 3, add 1 to make them 0 to 4\n",
680
+ "\n",
681
+ " if self.transform:\n",
682
+ " images = self.transform(images)\n",
683
+ " labels = self.transform(labels)\n",
684
+ " \n",
685
+ " return images, labels, self.file_names[idx]\n",
686
+ "\n",
687
+ "class CustomDataset_test(Dataset):\n",
688
+ " def __init__(self, file_paths, transform=None):\n",
689
+ " self.file_paths = file_paths\n",
690
+ " self.transform = transform\n",
691
+ " self.file_names = [os.path.basename(path) for path in file_paths]\n",
692
+ "\n",
693
+ " def __len__(self):\n",
694
+ " return len(self.file_paths)\n",
695
+ "\n",
696
+ " def __getitem__(self, idx):\n",
697
+ " data = torch.load(self.file_paths[idx], weights_only=True)\n",
698
+ " \n",
699
+ " images = data[:6] #only load first 6 channels, labels are not in val_set and test_set\n",
700
+ " \n",
701
+ " images = images.float() \n",
702
+ "\n",
703
+ " if self.transform:\n",
704
+ " images = self.transform(images)\n",
705
+ " \n",
706
+ " return images, self.file_names[idx]\n",
707
+ "\n",
708
+ "# extend base_path to file_path\n",
709
+ "def generate_file_paths(base_path):\n",
710
+ " file_paths = []\n",
711
+ " for frame in os.listdir(base_path):\n",
712
+ " frame_path = os.path.join(base_path, frame)\n",
713
+ " if frame_path.endswith('.mat.pt'):\n",
714
+ " file_paths.append(frame_path)\n",
715
+ " return [path for path in file_paths if os.path.exists(path)]\n",
716
+ "\n",
717
+ "def load_data(base_path, batch_size=4, num_workers=2, test_size=0.2):\n",
718
+ " file_paths = generate_file_paths(base_path)\n",
719
+ " \n",
720
+ " train_paths, test_paths = train_test_split(file_paths, test_size=test_size, random_state=42)\n",
721
+ " \n",
722
+ " train_dataset = CustomDataset(file_paths=train_paths)\n",
723
+ " test_dataset = CustomDataset(file_paths=test_paths)\n",
724
+ " \n",
725
+ " train_loader = DataLoader(\n",
726
+ " train_dataset, \n",
727
+ " batch_size=batch_size, \n",
728
+ " shuffle=True, \n",
729
+ " num_workers=num_workers, \n",
730
+ " drop_last=True\n",
731
+ " )\n",
732
+ " \n",
733
+ " test_loader = DataLoader(\n",
734
+ " test_dataset, \n",
735
+ " batch_size=batch_size, \n",
736
+ " shuffle=False, \n",
737
+ " num_workers=num_workers, \n",
738
+ " drop_last=True\n",
739
+ " )\n",
740
+ " \n",
741
+ " return train_loader, test_loader\n"
742
+ ]
743
+ },
744
+ {
745
+ "cell_type": "markdown",
746
+ "id": "67cd6c15",
747
+ "metadata": {},
748
+ "source": [
749
+ "## Loss Function"
750
+ ]
751
+ },
752
+ {
753
+ "cell_type": "code",
754
+ "execution_count": null,
755
+ "id": "4c573803",
756
+ "metadata": {},
757
+ "outputs": [],
758
+ "source": [
759
+ "#Used to handle the problem of class imbalance\n",
760
+ "\n",
761
+ "def to_one_hot(tensor, nClasses):\n",
762
+ " n, h, w = tensor.size()\n",
763
+ " one_hot = torch.zeros(n, nClasses, h, w, device=tensor.device)\n",
764
+ " index_tensor = tensor.long().view(n, 1, h, w)\n",
765
+ " one_hot = one_hot.scatter_(1, index_tensor, 1)\n",
766
+ " return one_hot\n",
767
+ "\n",
768
+ "def _neg_loss(pred, gt):\n",
769
+ " pred = torch.clamp(pred, 1e-5, 1-1e-5)\n",
770
+ "\n",
771
+ " pos_inds = gt.eq(1).float()\n",
772
+ " neg_inds = gt.eq(0).float()\n",
773
+ "\n",
774
+ " balance_cof = 1.0\n",
775
+ " pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds * balance_cof\n",
776
+ " neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_inds\n",
777
+ " num_pos = pos_inds.float().sum()\n",
778
+ " pos_loss_sum = pos_loss.sum()\n",
779
+ " neg_loss_sum = neg_loss.sum()\n",
780
+ " if num_pos == 0:\n",
781
+ " loss = -neg_loss_sum\n",
782
+ " else:\n",
783
+ " loss = -(pos_loss_sum + neg_loss_sum) / num_pos\n",
784
+ " return loss\n",
785
+ "\n",
786
+ "class FocalLoss(nn.Module):\n",
787
+ " def __init__(self):\n",
788
+ " super(FocalLoss, self).__init__()\n",
789
+ " self.neg_loss = _neg_loss\n",
790
+ "\n",
791
+ " def forward(self, out, target):\n",
792
+ " return self.neg_loss(out, target)"
793
+ ]
794
+ },
795
+ {
796
+ "cell_type": "markdown",
797
+ "id": "dec2b582",
798
+ "metadata": {},
799
+ "source": [
800
+ "## Train"
801
+ ]
802
+ },
803
+ {
804
+ "cell_type": "code",
805
+ "execution_count": null,
806
+ "id": "7c2f0301",
807
+ "metadata": {},
808
+ "outputs": [],
809
+ "source": [
810
+ "import torch.optim as optim\n",
811
+ "import matplotlib.pyplot as plt\n",
812
+ "import time\n",
813
+ "\n",
814
+ "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
815
+ "\n",
816
+ "num_epochs = 20\n",
817
+ "\n",
818
+ "base_path = '/bohr/train-22pn/v2/training_set'\n",
819
+ "train_loader, test_loader = load_data(\n",
820
+ " base_path=base_path,\n",
821
+ " batch_size=4,\n",
822
+ " num_workers=2,\n",
823
+ " test_size=0.2\n",
824
+ ")\n",
825
+ "\n",
826
+ "dimssnet = DIMSSNet().to(device)\n",
827
+ "criterion = FocalLoss()\n",
828
+ "optimizer = optim.Adam(dimssnet.parameters(), lr=0.001)\n",
829
+ "start_time = time.time()\n",
830
+ "test_loss_record = []\n",
831
+ "train_loss_record = []\n",
832
+ "\n",
833
+ "for epoch in range(num_epochs):\n",
834
+ " dimssnet.train()\n",
835
+ " running_loss = 0.0\n",
836
+ " for images, labels, _ in train_loader:\n",
837
+ " images = images.to(device)\n",
838
+ " labels = labels.to(device)\n",
839
+ " \n",
840
+ " images = [image.unsqueeze(1) for image in images]\n",
841
+ " images = torch.stack(images, dim=0)\n",
842
+ " images = images.float()\n",
843
+ " \n",
844
+ " outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n",
845
+ " images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n",
846
+ "\n",
847
+ " outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n",
848
+ " labels = to_one_hot(labels, n_class)\n",
849
+ " \n",
850
+ " loss = criterion(outputs_resized, labels.long())\n",
851
+ " optimizer.zero_grad()\n",
852
+ " loss.backward()\n",
853
+ " optimizer.step()\n",
854
+ " \n",
855
+ " running_loss += loss.item()\n",
856
+ "\n",
857
+ " test_loss = 0.0\n",
858
+ " dimssnet.eval()\n",
859
+ " with torch.no_grad():\n",
860
+ " for images, labels, _ in test_loader:\n",
861
+ " images = images.to(device)\n",
862
+ " labels = labels.to(device)\n",
863
+ " \n",
864
+ " images = [image.unsqueeze(1) for image in images]\n",
865
+ " images = torch.stack(images, dim=0)\n",
866
+ " images = images.float()\n",
867
+ " \n",
868
+ " outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n",
869
+ " images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n",
870
+ " \n",
871
+ " outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n",
872
+ " labels = to_one_hot(labels, n_class)\n",
873
+ " \n",
874
+ " loss = criterion(outputs_resized, labels.long())\n",
875
+ " test_loss += loss.item()\n",
876
+ " \n",
877
+ " test_loss_record.append(test_loss/len(test_loader))\n",
878
+ " train_loss_record.append(running_loss/len(train_loader))\n",
879
+ " print(f\"Epoch {epoch+1}/{num_epochs}, Training Loss: {running_loss/len(train_loader):.4f}, Test Loss: {test_loss/len(test_loader):.4f}\")\n",
880
+ "\n",
881
+ "# Create a new state_dict and add the \"model\" prefix, in order to match the loading method in metrics\n",
882
+ "new_state_dict = {}\n",
883
+ "for k, v in dimssnet.state_dict().items():\n",
884
+ " new_key = f\"model.{k}\" \n",
885
+ " new_state_dict[new_key] = v\n",
886
+ "\n",
887
+ "print(\"dimssnet successfully saved!\") \n",
888
+ "print(\"Training finished.\")\n",
889
+ "end_time = time.time()\n",
890
+ "total_time = end_time - start_time\n",
891
+ "print(f\"Training completed in {total_time} seconds\")"
892
+ ]
893
+ },
894
+ {
895
+ "cell_type": "markdown",
896
+ "id": "f001aee8",
897
+ "metadata": {},
898
+ "source": [
899
+ "## Inference"
900
+ ]
901
+ },
902
+ {
903
+ "cell_type": "code",
904
+ "execution_count": null,
905
+ "id": "8b330819",
906
+ "metadata": {},
907
+ "outputs": [],
908
+ "source": [
909
+ "# Run inference on validation set and testing set\n",
910
+ "import pandas as pd\n",
911
+ "\n",
912
+ "def run_inference(model, data_loader):\n",
913
+ " model.eval()\n",
914
+ " predictions = []\n",
915
+ " filenames = []\n",
916
+ " \n",
917
+ " with torch.no_grad():\n",
918
+ " for images, file_names in data_loader:\n",
919
+ " images = images.cuda() if torch.cuda.is_available() else images\n",
920
+ " \n",
921
+ " x = [image.unsqueeze(1) for image in images]\n",
922
+ " x = torch.stack(x, dim=0)\n",
923
+ " x = x.float()\n",
924
+ " \n",
925
+ " # Forward propagation\n",
926
+ " outputs = model(x[:, 0, :, :], x[:, 1, :, :], x[:, 2, :, :],\n",
927
+ " x[:, 3, :, :], x[:, 4, :, :], x[:, 5, :, :])\n",
928
+ " \n",
929
+ " # Adjust the output size\n",
930
+ " outputs = F.interpolate(outputs, size=(50, 181), mode='bilinear', align_corners=False)\n",
931
+ "\n",
932
+ " preds = torch.argmax(outputs, dim=1)\n",
933
+ " \n",
934
+ " preds = preds - 1\n",
935
+ " \n",
936
+ " for i, pred in enumerate(preds):\n",
937
+ " predictions.append(pred.cpu().numpy().flatten())\n",
938
+ " filenames.append(file_names[i])\n",
939
+ " \n",
940
+ " return predictions, filenames\n",
941
+ "\n",
942
+ "# Load validation set\n",
943
+ "if os.environ.get('DATA_PATH'):\n",
944
+ " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
945
+ "else:\n",
946
+ " DATA_PATH = \"\" # Fallback for local testing\n",
947
+ "# Load validation set\n",
948
+ "val_paths = generate_file_paths(DATA_PATH + 'validation_set')\n",
949
+ "val_dataset = CustomDataset_test(file_paths=val_paths)\n",
950
+ "val_loader = DataLoader(\n",
951
+ " val_dataset,\n",
952
+ " batch_size=1,\n",
953
+ " shuffle=False,\n",
954
+ " num_workers=0\n",
955
+ ")\n",
956
+ "\n",
957
+ "# Load testing set\n",
958
+ "if os.environ.get('DATA_PATH'):\n",
959
+ " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
960
+ "else:\n",
961
+ " DATA_PATH = \"\" # Fallback for local testing\n",
962
+ "# Load testing set\n",
963
+ "test_paths = generate_file_paths(DATA_PATH + 'testing_set')\n",
964
+ "test_dataset = CustomDataset_test(file_paths=test_paths)\n",
965
+ "test_loader = DataLoader(\n",
966
+ " test_dataset,\n",
967
+ " batch_size=1,\n",
968
+ " shuffle=False,\n",
969
+ " num_workers=0\n",
970
+ ")\n",
971
+ "\n",
972
+ "# Run inference on validation set\n",
973
+ "print(\"Running inference on validation set...\")\n",
974
+ "val_predictions, val_filenames = run_inference(dimssnet, val_loader)\n",
975
+ "\n",
976
+ "# Save validation results to CSV\n",
977
+ "val_results = []\n",
978
+ "for filename, pred in zip(val_filenames, val_predictions):\n",
979
+ " # Create a row with filename and flattened predictions\n",
980
+ " row = {'filename': filename}\n",
981
+ " for i, p in enumerate(pred):\n",
982
+ " row[f'pixel_{i}'] = p\n",
983
+ " val_results.append(row)\n",
984
+ "\n",
985
+ "val_df = pd.DataFrame(val_results)\n",
986
+ "val_df.to_csv('submission_val.csv', index=False)\n",
987
+ "print(f\"Validation results saved to output_validation.csv with shape: {val_df.shape}\")\n",
988
+ "\n",
989
+ "# Run inference on testing set\n",
990
+ "print(\"Running inference on testing set...\")\n",
991
+ "test_predictions, test_filenames = run_inference(dimssnet, test_loader)\n",
992
+ "\n",
993
+ "# Save testing results to CSV\n",
994
+ "test_results = []\n",
995
+ "for filename, pred in zip(test_filenames, test_predictions):\n",
996
+ " # Create a row with filename and flattened predictions\n",
997
+ " row = {'filename': filename}\n",
998
+ " for i, p in enumerate(pred):\n",
999
+ " row[f'pixel_{i}'] = p\n",
1000
+ " test_results.append(row)\n",
1001
+ "\n",
1002
+ "test_df = pd.DataFrame(test_results)\n",
1003
+ "test_df.to_csv('submission_test.csv', index=False)\n",
1004
+ "print(f\"Testing results saved to output_testing.csv with shape: {test_df.shape}\")\n",
1005
+ "\n",
1006
+ "print(\"\\nInference completed! Results saved to:\")\n",
1007
+ "print(\"- submission_val_ref.csv (for validation set leaderboard)\")\n",
1008
+ "print(\"- submission_test_ref.csv (for testing set leaderboard)\")"
1009
+ ]
1010
+ },
1011
+ {
1012
+ "cell_type": "code",
1013
+ "execution_count": null,
1014
+ "id": "72fde72d",
1015
+ "metadata": {},
1016
+ "outputs": [],
1017
+ "source": [
1018
+ "import zipfile\n",
1019
+ "import os\n",
1020
+ "\n",
1021
+ "# Define the files to zip and the zip file name.\n",
1022
+ "files_to_zip = ['submission_val.csv', 'submission_test.csv']\n",
1023
+ "zip_filename = 'submission.zip'\n",
1024
+ "\n",
1025
+ "# Create a zip file\n",
1026
+ "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
1027
+ " for file in files_to_zip:\n",
1028
+ " # Add the file to the zip fil\n",
1029
+ " zipf.write(file, os.path.basename(file))\n",
1030
+ "\n",
1031
+ "print(f'{zip_filename} Created successfully!')"
1032
+ ]
1033
+ }
1034
+ ],
1035
+ "metadata": {
1036
+ "kernelspec": {
1037
+ "display_name": "Python 3 (ipykernel)",
1038
+ "language": "python",
1039
+ "name": "python3"
1040
+ },
1041
+ "language_info": {
1042
+ "codemirror_mode": {
1043
+ "name": "ipython",
1044
+ "version": 3
1045
+ },
1046
+ "file_extension": ".py",
1047
+ "mimetype": "text/x-python",
1048
+ "name": "python",
1049
+ "nbconvert_exporter": "python",
1050
+ "pygments_lexer": "ipython3",
1051
+ "version": "3.12.9"
1052
+ }
1053
+ },
1054
+ "nbformat": 4,
1055
+ "nbformat_minor": 5
1056
+ }
benchmark/IOL/ioling_hf/evals/results/HuggingFaceTB__SmolLM3-3B__diverse5.scores.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.437, "full_output_similarity": 75.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.286, "full_output_similarity": 75.758}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 56.818}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "HuggingFaceTB/SmolLM3-3B"}
2
+ {"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.5, "full_output_similarity": 48.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "HuggingFaceTB/SmolLM3-3B"}
3
+ {"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 21.739, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 21.053, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 21.739, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 23.256, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 20.513, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.727, "full_output_similarity": 80.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.561, "full_output_similarity": 70.0}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 21.739, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "HuggingFaceTB/SmolLM3-3B"}
4
+ {"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.197, "full_output_similarity": 48.718}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.0, "full_output_similarity": 66.667}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.25, "full_output_similarity": 70.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 89.286}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.579, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 27.586, "full_output_similarity": 73.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.769, "full_output_similarity": 77.778}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.032, "full_output_similarity": 67.742}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.571, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "HuggingFaceTB/SmolLM3-3B"}
5
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.738, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "HuggingFaceTB/SmolLM3-3B"}
benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen2.5-3B-Instruct__diverse5.scores.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 92.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 84.848}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 78.571}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen2.5-3B-Instruct"}
2
+ {"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 49.0, "full_output_similarity": 49.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen2.5-3B-Instruct"}
3
+ {"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.857, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 20.0, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 52.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.242, "full_output_similarity": 50.0}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen2.5-3B-Instruct"}
4
+ {"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.769, "full_output_similarity": 46.154}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 66.667}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.483, "full_output_similarity": 70.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.571, "full_output_similarity": 89.286}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.364, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.714, "full_output_similarity": 73.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 77.778}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.484, "full_output_similarity": 67.742}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.787, "full_output_similarity": 75.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen2.5-3B-Instruct"}
5
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.143, "full_output_similarity": 36.31}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen2.5-3B-Instruct"}
benchmark/IOL/ioling_hf/evals/results/google__gemma-3-12b-it__diverse5.scores.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.758, "full_output_similarity": 75.758}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.19, "full_output_similarity": 51.19}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
2
+ {"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.0, "full_output_similarity": 50.98}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
3
+ {"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.63, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.435, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.787, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.167, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.532, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.034, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.0, "full_output_similarity": 80.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.0, "full_output_similarity": 70.0}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.63, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
4
+ {"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.286, "full_output_similarity": 89.286}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.333, "full_output_similarity": 73.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.742, "full_output_similarity": 67.742}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
5
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 28.571}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
benchmark/IOL/ioling_hf/evals/results/google__gemma-3-12b-it__strict30.scores.jsonl ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.013, "full_output_similarity": 80.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.758, "full_output_similarity": 75.758}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.682, "full_output_similarity": 55.682}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.074, "full_output_similarity": 71.429}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
2
+ {"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.83, "full_output_similarity": 45.879}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
3
+ {"record_id": "iol-2007-individual-p5", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.379, "full_output_similarity": 65.517}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.333, "full_output_similarity": 45.714}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.826, "full_output_similarity": 56.522}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 45.161}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
4
+ {"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.703, "full_output_similarity": 47.953}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
5
+ {"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.646, "full_output_similarity": 46.552}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
6
+ {"record_id": "iol-2009-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.927, "full_output_similarity": 53.927}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
7
+ {"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 86.653, "full_output_similarity": 86.885}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
8
+ {"record_id": "iol-2010-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.037, "full_output_similarity": 35.579}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
9
+ {"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.667, "full_output_similarity": 79.137}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
10
+ {"record_id": "iol-2012-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 46.377}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
11
+ {"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.796, "full_output_similarity": 80.412}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
12
+ {"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 66.667}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.765, "full_output_similarity": 47.059}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 27.5, "full_output_similarity": 43.75}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.846, "full_output_similarity": 40.0}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.885, "full_output_similarity": 55.172}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
13
+ {"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
14
+ {"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.531, "full_output_similarity": 48.59}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
15
+ {"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 49.367, "full_output_similarity": 50.633}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.571, "full_output_similarity": 52.857}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.27, "full_output_similarity": 72.973}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.25, "full_output_similarity": 53.75}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
16
+ {"record_id": "iol-2016-individual-p1", "score": 0.0, "max_score": 15.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.216, "full_output_similarity": 74.468}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.667, "full_output_similarity": 84.444}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 17.143, "full_output_similarity": 75.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 17.647, "full_output_similarity": 73.171}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.216, "full_output_similarity": 77.778}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.438, "full_output_similarity": 73.171}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.216, "full_output_similarity": 77.083}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.901, "full_output_similarity": 79.487}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.667, "full_output_similarity": 83.333}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.667, "full_output_similarity": 72.5}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.667, "full_output_similarity": 73.81}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.901, "full_output_similarity": 77.273}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.901, "full_output_similarity": 69.048}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.216, "full_output_similarity": 75.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.216, "full_output_similarity": 76.596}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
17
+ {"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.659, "full_output_similarity": 60.87}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.125, "full_output_similarity": 56.25}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
18
+ {"record_id": "iol-2017-individual-p2-sub-a", "score": 0.0, "max_score": 16.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.21, "full_output_similarity": 62.295}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.528, "full_output_similarity": 66.038}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.667, "full_output_similarity": 83.333}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.688, "full_output_similarity": 65.079}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.829, "full_output_similarity": 95.122}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.19, "full_output_similarity": 52.381}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.787, "full_output_similarity": 52.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.842, "full_output_similarity": 73.684}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.714, "full_output_similarity": 68.571}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 77.778}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.0, "full_output_similarity": 92.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.667, "full_output_similarity": 72.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.268, "full_output_similarity": 80.488}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 23.256, "full_output_similarity": 51.163}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 27.273, "full_output_similarity": 52.273}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.0, "full_output_similarity": 76.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
19
+ {"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.161, "full_output_similarity": 71.398}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
20
+ {"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.944, "full_output_similarity": 40.278}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
21
+ {"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 20.93, "full_output_similarity": 72.093}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 69.697}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.532, "full_output_similarity": 68.571}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.5, "full_output_similarity": 70.0}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.923, "full_output_similarity": 65.385}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.0, "full_output_similarity": 71.429}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 72.727}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.471, "full_output_similarity": 76.471}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.087, "full_output_similarity": 69.697}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 21.429, "full_output_similarity": 63.415}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.087, "full_output_similarity": 70.968}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.087, "full_output_similarity": 66.667}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.641, "full_output_similarity": 59.259}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.857, "full_output_similarity": 75.61}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 27.907, "full_output_similarity": 62.963}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.532, "full_output_similarity": 68.75}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.926, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
22
+ {"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.485, "full_output_similarity": 77.582}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
23
+ {"record_id": "iol-2021-individual-p3-sub-a", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.216, "full_output_similarity": 100.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.435, "full_output_similarity": 100.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.769, "full_output_similarity": 100.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.71, "full_output_similarity": 100.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
24
+ {"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.684, "full_output_similarity": 86.486}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
25
+ {"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
26
+ {"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 87.5, "full_output_similarity": 87.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.613, "full_output_similarity": 51.613}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.714, "full_output_similarity": 45.714}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.583, "full_output_similarity": 64.583}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.789, "full_output_similarity": 65.789}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.102, "full_output_similarity": 55.102}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 91.176, "full_output_similarity": 91.176}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.353, "full_output_similarity": 82.353}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.081, "full_output_similarity": 81.081}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.333, "full_output_similarity": 83.333}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
27
+ {"record_id": "iol-2024-individual-p1", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.258, "full_output_similarity": 45.161}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.375, "full_output_similarity": 43.75}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.0, "full_output_similarity": 47.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.0, "full_output_similarity": 45.333}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 55.556}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.929, "full_output_similarity": 46.429}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.303, "full_output_similarity": 48.485}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.375, "full_output_similarity": 43.75}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.857, "full_output_similarity": 44.737}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 71.875}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.852, "full_output_similarity": 62.963}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.054, "full_output_similarity": 81.081}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 86.667}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.0, "full_output_similarity": 84.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.064, "full_output_similarity": 67.742}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 83.871}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 83.333}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
28
+ {"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.962, "full_output_similarity": 54.545}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 50.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 27.66, "full_output_similarity": 55.556}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.508, "full_output_similarity": 56.098}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.358, "full_output_similarity": 48.529}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.962, "full_output_similarity": 51.515}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.571, "full_output_similarity": 63.636}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.375, "full_output_similarity": 50.0}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.137, "full_output_similarity": 54.348}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 29.73, "full_output_similarity": 48.649}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.962, "full_output_similarity": 45.455}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.571, "full_output_similarity": 52.381}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.746, "full_output_similarity": 50.0}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.727, "full_output_similarity": 56.757}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.189, "full_output_similarity": 56.757}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.235, "full_output_similarity": 60.0}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.829, "full_output_similarity": 61.111}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 63.333}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.508, "full_output_similarity": 53.846}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
29
+ {"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.298, "full_output_similarity": 38.298}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
30
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 27.976}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "google/gemma-3-12b-it"}
benchmark/IOL/ioling_hf/evals/results/meta-llama__Llama-3.2-3B-Instruct__diverse5.scores.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 1.0, "max_score": 4.0, "score_fraction": 0.25, "verdict": "partial", "matched_units": ["assignment_1.1"], "missed_units": ["assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 95.0, "full_output_similarity": 95.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.576, "full_output_similarity": 60.606}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.0, "full_output_similarity": 56.818}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 72.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
2
+ {"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.832, "full_output_similarity": 59.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
3
+ {"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.857, "full_output_similarity": 40.741}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 39.13}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 20.0, "full_output_similarity": 40.741}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 45.833}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 41.667}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 44.828}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 48.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.242, "full_output_similarity": 46.667}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 40.741}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
4
+ {"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.872, "full_output_similarity": 44.872}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.0, "full_output_similarity": 65.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.143, "full_output_similarity": 57.143}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.333, "full_output_similarity": 53.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.065, "full_output_similarity": 58.065}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.889, "full_output_similarity": 63.889}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
5
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.842, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
benchmark/IOL/ioling_hf/evals/results/meta-llama__Llama-3.2-3B-Instruct__strict30.scores.jsonl ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.5, "full_output_similarity": 82.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.591, "full_output_similarity": 53.409}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.286, "full_output_similarity": 64.286}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
2
+ {"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.446, "full_output_similarity": 43.173}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
3
+ {"record_id": "iol-2007-individual-p5", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.379, "full_output_similarity": 55.172}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.286, "full_output_similarity": 48.571}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.13, "full_output_similarity": 56.522}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.71, "full_output_similarity": 41.935}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
4
+ {"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.029, "full_output_similarity": 45.029}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
5
+ {"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.284, "full_output_similarity": 46.207}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
6
+ {"record_id": "iol-2009-individual-p4-sub-a", "score": 1.0, "max_score": 1.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["a.1"], "missed_units": [], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 49.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
7
+ {"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.163, "full_output_similarity": 41.163}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
8
+ {"record_id": "iol-2010-team-p1", "score": 1.0, "max_score": 1.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["full.1"], "missed_units": [], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 34.182}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
9
+ {"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.079, "full_output_similarity": 51.079}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
10
+ {"record_id": "iol-2012-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 49.275, "full_output_similarity": 49.275}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
11
+ {"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.885, "full_output_similarity": 69.892}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
12
+ {"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 66.667}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.037, "full_output_similarity": 50.588}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.0, "full_output_similarity": 47.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.645, "full_output_similarity": 45.333}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.23, "full_output_similarity": 55.172}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
13
+ {"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
14
+ {"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.796, "full_output_similarity": 40.796}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
15
+ {"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 53.333}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 51.899}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 45.714}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 51.351}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 52.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
16
+ {"record_id": "iol-2016-individual-p1", "score": 15.0, "max_score": 15.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "missed_units": [], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 74.468}, {"unit_id": "full.2", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 77.778}, {"unit_id": "full.3", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 85.0}, {"unit_id": "full.4", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 78.049}, {"unit_id": "full.5", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 75.556}, {"unit_id": "full.6", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 75.61}, {"unit_id": "full.7", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 83.333}, {"unit_id": "full.8", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 79.487}, {"unit_id": "full.9", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 76.19}, {"unit_id": "full.10", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 90.0}, {"unit_id": "full.11", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 88.095}, {"unit_id": "full.12", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 79.545}, {"unit_id": "full.13", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 83.333}, {"unit_id": "full.14", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 85.417}, {"unit_id": "full.15", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 82.979}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
17
+ {"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 60.87}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 53.125}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
18
+ {"record_id": "iol-2017-individual-p2-sub-a", "score": 0.0, "max_score": 16.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 54.098}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 60.377}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 79.167}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 57.143}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 73.171}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 54.762}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 54.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 78.947}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 62.857}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 72.222}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 80.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 76.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 75.61}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 53.488}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 59.091}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 76.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
19
+ {"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.017, "full_output_similarity": 61.585}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
20
+ {"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 37.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
21
+ {"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 76.744}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 75.758}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 77.143}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 75.0}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 73.077}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 71.429}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 84.848}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 88.235}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 81.818}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 68.293}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 70.968}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 66.667}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 70.37}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 78.049}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 66.667}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 71.875}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 74.074}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
22
+ {"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.491, "full_output_similarity": 41.491}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
23
+ {"record_id": "iol-2021-individual-p3-sub-a", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.235, "full_output_similarity": 97.059}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.478, "full_output_similarity": 100.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.095, "full_output_similarity": 100.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.026, "full_output_similarity": 97.436}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
24
+ {"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 83.784}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
25
+ {"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 16.667, "full_output_similarity": 50.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
26
+ {"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.5, "full_output_similarity": 87.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 48.387}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.037, "full_output_similarity": 59.259}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 72.0}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 54.286}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 66.667}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.0, "full_output_similarity": 72.917}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.105, "full_output_similarity": 73.684}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.98, "full_output_similarity": 65.306}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.588, "full_output_similarity": 70.588}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.647, "full_output_similarity": 73.529}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.676, "full_output_similarity": 78.378}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 79.012}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
27
+ {"record_id": "iol-2024-individual-p1", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.667, "full_output_similarity": 46.237}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 47.917}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.5, "full_output_similarity": 47.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.22, "full_output_similarity": 44.0}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 66.667}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.714, "full_output_similarity": 44.643}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.364, "full_output_similarity": 45.455}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 47.917}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.714, "full_output_similarity": 42.105}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.574, "full_output_similarity": 68.75}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 59.259}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.649, "full_output_similarity": 78.378}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 86.667}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.0, "full_output_similarity": 64.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.29, "full_output_similarity": 67.742}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.29, "full_output_similarity": 61.29}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.684, "full_output_similarity": 71.795}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
28
+ {"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.394, "full_output_similarity": 39.394}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.176, "full_output_similarity": 41.176}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 44.444}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.463, "full_output_similarity": 41.463}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.118, "full_output_similarity": 44.118}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.424, "full_output_similarity": 42.424}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.818, "full_output_similarity": 41.818}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.875, "full_output_similarity": 46.875}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.652, "full_output_similarity": 45.652}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.541, "full_output_similarity": 40.541}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.424, "full_output_similarity": 42.424}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.857, "full_output_similarity": 42.857}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.243, "full_output_similarity": 43.243}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.243, "full_output_similarity": 43.243}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.636, "full_output_similarity": 43.636}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 40.741}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.333, "full_output_similarity": 48.333}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 46.154}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
29
+ {"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.979, "full_output_similarity": 32.979}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
30
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.842, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "meta-llama/Llama-3.2-3B-Instruct"}
benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct.scores.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4", "assignment_2.1", "assignment_3.1", "assignment_3.2", "assignment_3.3", "assignment_3.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.5, "full_output_similarity": 72.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.576, "full_output_similarity": 57.576}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.286, "full_output_similarity": 64.286}, {"unit_id": "assignment_2.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "assignment_3.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.767, "full_output_similarity": 69.767}, {"unit_id": "assignment_3.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.833, "full_output_similarity": 70.833}, {"unit_id": "assignment_3.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "assignment_3.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
2
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.5, "full_output_similarity": 77.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.429, "full_output_similarity": 71.429}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
3
+ {"record_id": "iol-2006-individual-p1-sub-assignment_2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_2.1"], "unit_results": [{"unit_id": "assignment_2.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.333, "full_output_similarity": 58.333}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct__diverse5.scores.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.5, "full_output_similarity": 77.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.273, "full_output_similarity": 52.273}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
2
+ {"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
3
+ {"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.913, "full_output_similarity": 73.913}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.833, "full_output_similarity": 45.833}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.828, "full_output_similarity": 44.828}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.0, "full_output_similarity": 52.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 46.667}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 44.444}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
4
+ {"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 46.154}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 46.667}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.857, "full_output_similarity": 42.857}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 46.667}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.935, "full_output_similarity": 41.935}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.111, "full_output_similarity": 36.111}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
5
+ {"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.738, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"}
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """ python inspection/code generation API """
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_assertionnew.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Find intermediate evalutation results in assert statements through builtin AST.
3
+ This should replace _assertionold.py eventually.
4
+ """
5
+
6
+ import sys
7
+ import ast
8
+
9
+ import py
10
+ from py._code.assertion import _format_explanation, BuiltinAssertionError
11
+
12
+
13
+ def _is_ast_expr(node):
14
+ return isinstance(node, ast.expr)
15
+ def _is_ast_stmt(node):
16
+ return isinstance(node, ast.stmt)
17
+
18
+
19
+ class Failure(Exception):
20
+ """Error found while interpreting AST."""
21
+
22
+ def __init__(self, explanation=""):
23
+ self.cause = sys.exc_info()
24
+ self.explanation = explanation
25
+
26
+
27
+ def interpret(source, frame, should_fail=False):
28
+ mod = ast.parse(source)
29
+ visitor = DebugInterpreter(frame)
30
+ try:
31
+ visitor.visit(mod)
32
+ except Failure:
33
+ failure = sys.exc_info()[1]
34
+ return getfailure(failure)
35
+ if should_fail:
36
+ return ("(assertion failed, but when it was re-run for "
37
+ "printing intermediate values, it did not fail. Suggestions: "
38
+ "compute assert expression before the assert or use --no-assert)")
39
+
40
+ def run(offending_line, frame=None):
41
+ if frame is None:
42
+ frame = py.code.Frame(sys._getframe(1))
43
+ return interpret(offending_line, frame)
44
+
45
+ def getfailure(failure):
46
+ explanation = _format_explanation(failure.explanation)
47
+ value = failure.cause[1]
48
+ if str(value):
49
+ lines = explanation.splitlines()
50
+ if not lines:
51
+ lines.append("")
52
+ lines[0] += " << %s" % (value,)
53
+ explanation = "\n".join(lines)
54
+ text = "%s: %s" % (failure.cause[0].__name__, explanation)
55
+ if text.startswith("AssertionError: assert "):
56
+ text = text[16:]
57
+ return text
58
+
59
+
60
+ operator_map = {
61
+ ast.BitOr : "|",
62
+ ast.BitXor : "^",
63
+ ast.BitAnd : "&",
64
+ ast.LShift : "<<",
65
+ ast.RShift : ">>",
66
+ ast.Add : "+",
67
+ ast.Sub : "-",
68
+ ast.Mult : "*",
69
+ ast.Div : "/",
70
+ ast.FloorDiv : "//",
71
+ ast.Mod : "%",
72
+ ast.Eq : "==",
73
+ ast.NotEq : "!=",
74
+ ast.Lt : "<",
75
+ ast.LtE : "<=",
76
+ ast.Gt : ">",
77
+ ast.GtE : ">=",
78
+ ast.Pow : "**",
79
+ ast.Is : "is",
80
+ ast.IsNot : "is not",
81
+ ast.In : "in",
82
+ ast.NotIn : "not in"
83
+ }
84
+
85
+ unary_map = {
86
+ ast.Not : "not %s",
87
+ ast.Invert : "~%s",
88
+ ast.USub : "-%s",
89
+ ast.UAdd : "+%s"
90
+ }
91
+
92
+
93
+ class DebugInterpreter(ast.NodeVisitor):
94
+ """Interpret AST nodes to gleam useful debugging information. """
95
+
96
+ def __init__(self, frame):
97
+ self.frame = frame
98
+
99
+ def generic_visit(self, node):
100
+ # Fallback when we don't have a special implementation.
101
+ if _is_ast_expr(node):
102
+ mod = ast.Expression(node)
103
+ co = self._compile(mod)
104
+ try:
105
+ result = self.frame.eval(co)
106
+ except Exception:
107
+ raise Failure()
108
+ explanation = self.frame.repr(result)
109
+ return explanation, result
110
+ elif _is_ast_stmt(node):
111
+ mod = ast.Module([node])
112
+ co = self._compile(mod, "exec")
113
+ try:
114
+ self.frame.exec_(co)
115
+ except Exception:
116
+ raise Failure()
117
+ return None, None
118
+ else:
119
+ raise AssertionError("can't handle %s" %(node,))
120
+
121
+ def _compile(self, source, mode="eval"):
122
+ return compile(source, "<assertion interpretation>", mode)
123
+
124
+ def visit_Expr(self, expr):
125
+ return self.visit(expr.value)
126
+
127
+ def visit_Module(self, mod):
128
+ for stmt in mod.body:
129
+ self.visit(stmt)
130
+
131
+ def visit_Name(self, name):
132
+ explanation, result = self.generic_visit(name)
133
+ # See if the name is local.
134
+ source = "%r in locals() is not globals()" % (name.id,)
135
+ co = self._compile(source)
136
+ try:
137
+ local = self.frame.eval(co)
138
+ except Exception:
139
+ # have to assume it isn't
140
+ local = False
141
+ if not local:
142
+ return name.id, result
143
+ return explanation, result
144
+
145
+ def visit_Compare(self, comp):
146
+ left = comp.left
147
+ left_explanation, left_result = self.visit(left)
148
+ for op, next_op in zip(comp.ops, comp.comparators):
149
+ next_explanation, next_result = self.visit(next_op)
150
+ op_symbol = operator_map[op.__class__]
151
+ explanation = "%s %s %s" % (left_explanation, op_symbol,
152
+ next_explanation)
153
+ source = "__exprinfo_left %s __exprinfo_right" % (op_symbol,)
154
+ co = self._compile(source)
155
+ try:
156
+ result = self.frame.eval(co, __exprinfo_left=left_result,
157
+ __exprinfo_right=next_result)
158
+ except Exception:
159
+ raise Failure(explanation)
160
+ try:
161
+ if not result:
162
+ break
163
+ except KeyboardInterrupt:
164
+ raise
165
+ except:
166
+ break
167
+ left_explanation, left_result = next_explanation, next_result
168
+
169
+ rcomp = py.code._reprcompare
170
+ if rcomp:
171
+ res = rcomp(op_symbol, left_result, next_result)
172
+ if res:
173
+ explanation = res
174
+ return explanation, result
175
+
176
+ def visit_BoolOp(self, boolop):
177
+ is_or = isinstance(boolop.op, ast.Or)
178
+ explanations = []
179
+ for operand in boolop.values:
180
+ explanation, result = self.visit(operand)
181
+ explanations.append(explanation)
182
+ if result == is_or:
183
+ break
184
+ name = is_or and " or " or " and "
185
+ explanation = "(" + name.join(explanations) + ")"
186
+ return explanation, result
187
+
188
+ def visit_UnaryOp(self, unary):
189
+ pattern = unary_map[unary.op.__class__]
190
+ operand_explanation, operand_result = self.visit(unary.operand)
191
+ explanation = pattern % (operand_explanation,)
192
+ co = self._compile(pattern % ("__exprinfo_expr",))
193
+ try:
194
+ result = self.frame.eval(co, __exprinfo_expr=operand_result)
195
+ except Exception:
196
+ raise Failure(explanation)
197
+ return explanation, result
198
+
199
+ def visit_BinOp(self, binop):
200
+ left_explanation, left_result = self.visit(binop.left)
201
+ right_explanation, right_result = self.visit(binop.right)
202
+ symbol = operator_map[binop.op.__class__]
203
+ explanation = "(%s %s %s)" % (left_explanation, symbol,
204
+ right_explanation)
205
+ source = "__exprinfo_left %s __exprinfo_right" % (symbol,)
206
+ co = self._compile(source)
207
+ try:
208
+ result = self.frame.eval(co, __exprinfo_left=left_result,
209
+ __exprinfo_right=right_result)
210
+ except Exception:
211
+ raise Failure(explanation)
212
+ return explanation, result
213
+
214
+ def visit_Call(self, call):
215
+ func_explanation, func = self.visit(call.func)
216
+ arg_explanations = []
217
+ ns = {"__exprinfo_func" : func}
218
+ arguments = []
219
+ for arg in call.args:
220
+ arg_explanation, arg_result = self.visit(arg)
221
+ arg_name = "__exprinfo_%s" % (len(ns),)
222
+ ns[arg_name] = arg_result
223
+ arguments.append(arg_name)
224
+ arg_explanations.append(arg_explanation)
225
+ for keyword in call.keywords:
226
+ arg_explanation, arg_result = self.visit(keyword.value)
227
+ arg_name = "__exprinfo_%s" % (len(ns),)
228
+ ns[arg_name] = arg_result
229
+ keyword_source = "%s=%%s" % (keyword.arg)
230
+ arguments.append(keyword_source % (arg_name,))
231
+ arg_explanations.append(keyword_source % (arg_explanation,))
232
+ if call.starargs:
233
+ arg_explanation, arg_result = self.visit(call.starargs)
234
+ arg_name = "__exprinfo_star"
235
+ ns[arg_name] = arg_result
236
+ arguments.append("*%s" % (arg_name,))
237
+ arg_explanations.append("*%s" % (arg_explanation,))
238
+ if call.kwargs:
239
+ arg_explanation, arg_result = self.visit(call.kwargs)
240
+ arg_name = "__exprinfo_kwds"
241
+ ns[arg_name] = arg_result
242
+ arguments.append("**%s" % (arg_name,))
243
+ arg_explanations.append("**%s" % (arg_explanation,))
244
+ args_explained = ", ".join(arg_explanations)
245
+ explanation = "%s(%s)" % (func_explanation, args_explained)
246
+ args = ", ".join(arguments)
247
+ source = "__exprinfo_func(%s)" % (args,)
248
+ co = self._compile(source)
249
+ try:
250
+ result = self.frame.eval(co, **ns)
251
+ except Exception:
252
+ raise Failure(explanation)
253
+ pattern = "%s\n{%s = %s\n}"
254
+ rep = self.frame.repr(result)
255
+ explanation = pattern % (rep, rep, explanation)
256
+ return explanation, result
257
+
258
+ def _is_builtin_name(self, name):
259
+ pattern = "%r not in globals() and %r not in locals()"
260
+ source = pattern % (name.id, name.id)
261
+ co = self._compile(source)
262
+ try:
263
+ return self.frame.eval(co)
264
+ except Exception:
265
+ return False
266
+
267
+ def visit_Attribute(self, attr):
268
+ if not isinstance(attr.ctx, ast.Load):
269
+ return self.generic_visit(attr)
270
+ source_explanation, source_result = self.visit(attr.value)
271
+ explanation = "%s.%s" % (source_explanation, attr.attr)
272
+ source = "__exprinfo_expr.%s" % (attr.attr,)
273
+ co = self._compile(source)
274
+ try:
275
+ result = self.frame.eval(co, __exprinfo_expr=source_result)
276
+ except Exception:
277
+ raise Failure(explanation)
278
+ explanation = "%s\n{%s = %s.%s\n}" % (self.frame.repr(result),
279
+ self.frame.repr(result),
280
+ source_explanation, attr.attr)
281
+ # Check if the attr is from an instance.
282
+ source = "%r in getattr(__exprinfo_expr, '__dict__', {})"
283
+ source = source % (attr.attr,)
284
+ co = self._compile(source)
285
+ try:
286
+ from_instance = self.frame.eval(co, __exprinfo_expr=source_result)
287
+ except Exception:
288
+ from_instance = True
289
+ if from_instance:
290
+ rep = self.frame.repr(result)
291
+ pattern = "%s\n{%s = %s\n}"
292
+ explanation = pattern % (rep, rep, explanation)
293
+ return explanation, result
294
+
295
+ def visit_Assert(self, assrt):
296
+ test_explanation, test_result = self.visit(assrt.test)
297
+ if test_explanation.startswith("False\n{False =") and \
298
+ test_explanation.endswith("\n"):
299
+ test_explanation = test_explanation[15:-2]
300
+ explanation = "assert %s" % (test_explanation,)
301
+ if not test_result:
302
+ try:
303
+ raise BuiltinAssertionError
304
+ except Exception:
305
+ raise Failure(explanation)
306
+ return explanation, test_result
307
+
308
+ def visit_Assign(self, assign):
309
+ value_explanation, value_result = self.visit(assign.value)
310
+ explanation = "... = %s" % (value_explanation,)
311
+ name = ast.Name("__exprinfo_expr", ast.Load(),
312
+ lineno=assign.value.lineno,
313
+ col_offset=assign.value.col_offset)
314
+ new_assign = ast.Assign(assign.targets, name, lineno=assign.lineno,
315
+ col_offset=assign.col_offset)
316
+ mod = ast.Module([new_assign])
317
+ co = self._compile(mod, "exec")
318
+ try:
319
+ self.frame.exec_(co, __exprinfo_expr=value_result)
320
+ except Exception:
321
+ raise Failure(explanation)
322
+ return explanation, value_result
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_assertionold.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import py
2
+ import sys, inspect
3
+ from compiler import parse, ast, pycodegen
4
+ from py._code.assertion import BuiltinAssertionError, _format_explanation
5
+ import types
6
+
7
+ passthroughex = py.builtin._sysex
8
+
9
+ class Failure:
10
+ def __init__(self, node):
11
+ self.exc, self.value, self.tb = sys.exc_info()
12
+ self.node = node
13
+
14
+ class View(object):
15
+ """View base class.
16
+
17
+ If C is a subclass of View, then C(x) creates a proxy object around
18
+ the object x. The actual class of the proxy is not C in general,
19
+ but a *subclass* of C determined by the rules below. To avoid confusion
20
+ we call view class the class of the proxy (a subclass of C, so of View)
21
+ and object class the class of x.
22
+
23
+ Attributes and methods not found in the proxy are automatically read on x.
24
+ Other operations like setting attributes are performed on the proxy, as
25
+ determined by its view class. The object x is available from the proxy
26
+ as its __obj__ attribute.
27
+
28
+ The view class selection is determined by the __view__ tuples and the
29
+ optional __viewkey__ method. By default, the selected view class is the
30
+ most specific subclass of C whose __view__ mentions the class of x.
31
+ If no such subclass is found, the search proceeds with the parent
32
+ object classes. For example, C(True) will first look for a subclass
33
+ of C with __view__ = (..., bool, ...) and only if it doesn't find any
34
+ look for one with __view__ = (..., int, ...), and then ..., object,...
35
+ If everything fails the class C itself is considered to be the default.
36
+
37
+ Alternatively, the view class selection can be driven by another aspect
38
+ of the object x, instead of the class of x, by overriding __viewkey__.
39
+ See last example at the end of this module.
40
+ """
41
+
42
+ _viewcache = {}
43
+ __view__ = ()
44
+
45
+ def __new__(rootclass, obj, *args, **kwds):
46
+ self = object.__new__(rootclass)
47
+ self.__obj__ = obj
48
+ self.__rootclass__ = rootclass
49
+ key = self.__viewkey__()
50
+ try:
51
+ self.__class__ = self._viewcache[key]
52
+ except KeyError:
53
+ self.__class__ = self._selectsubclass(key)
54
+ return self
55
+
56
+ def __getattr__(self, attr):
57
+ # attributes not found in the normal hierarchy rooted on View
58
+ # are looked up in the object's real class
59
+ return getattr(self.__obj__, attr)
60
+
61
+ def __viewkey__(self):
62
+ return self.__obj__.__class__
63
+
64
+ def __matchkey__(self, key, subclasses):
65
+ if inspect.isclass(key):
66
+ keys = inspect.getmro(key)
67
+ else:
68
+ keys = [key]
69
+ for key in keys:
70
+ result = [C for C in subclasses if key in C.__view__]
71
+ if result:
72
+ return result
73
+ return []
74
+
75
+ def _selectsubclass(self, key):
76
+ subclasses = list(enumsubclasses(self.__rootclass__))
77
+ for C in subclasses:
78
+ if not isinstance(C.__view__, tuple):
79
+ C.__view__ = (C.__view__,)
80
+ choices = self.__matchkey__(key, subclasses)
81
+ if not choices:
82
+ return self.__rootclass__
83
+ elif len(choices) == 1:
84
+ return choices[0]
85
+ else:
86
+ # combine the multiple choices
87
+ return type('?', tuple(choices), {})
88
+
89
+ def __repr__(self):
90
+ return '%s(%r)' % (self.__rootclass__.__name__, self.__obj__)
91
+
92
+
93
+ def enumsubclasses(cls):
94
+ for subcls in cls.__subclasses__():
95
+ for subsubclass in enumsubclasses(subcls):
96
+ yield subsubclass
97
+ yield cls
98
+
99
+
100
+ class Interpretable(View):
101
+ """A parse tree node with a few extra methods."""
102
+ explanation = None
103
+
104
+ def is_builtin(self, frame):
105
+ return False
106
+
107
+ def eval(self, frame):
108
+ # fall-back for unknown expression nodes
109
+ try:
110
+ expr = ast.Expression(self.__obj__)
111
+ expr.filename = '<eval>'
112
+ self.__obj__.filename = '<eval>'
113
+ co = pycodegen.ExpressionCodeGenerator(expr).getCode()
114
+ result = frame.eval(co)
115
+ except passthroughex:
116
+ raise
117
+ except:
118
+ raise Failure(self)
119
+ self.result = result
120
+ self.explanation = self.explanation or frame.repr(self.result)
121
+
122
+ def run(self, frame):
123
+ # fall-back for unknown statement nodes
124
+ try:
125
+ expr = ast.Module(None, ast.Stmt([self.__obj__]))
126
+ expr.filename = '<run>'
127
+ co = pycodegen.ModuleCodeGenerator(expr).getCode()
128
+ frame.exec_(co)
129
+ except passthroughex:
130
+ raise
131
+ except:
132
+ raise Failure(self)
133
+
134
+ def nice_explanation(self):
135
+ return _format_explanation(self.explanation)
136
+
137
+
138
+ class Name(Interpretable):
139
+ __view__ = ast.Name
140
+
141
+ def is_local(self, frame):
142
+ source = '%r in locals() is not globals()' % self.name
143
+ try:
144
+ return frame.is_true(frame.eval(source))
145
+ except passthroughex:
146
+ raise
147
+ except:
148
+ return False
149
+
150
+ def is_global(self, frame):
151
+ source = '%r in globals()' % self.name
152
+ try:
153
+ return frame.is_true(frame.eval(source))
154
+ except passthroughex:
155
+ raise
156
+ except:
157
+ return False
158
+
159
+ def is_builtin(self, frame):
160
+ source = '%r not in locals() and %r not in globals()' % (
161
+ self.name, self.name)
162
+ try:
163
+ return frame.is_true(frame.eval(source))
164
+ except passthroughex:
165
+ raise
166
+ except:
167
+ return False
168
+
169
+ def eval(self, frame):
170
+ super(Name, self).eval(frame)
171
+ if not self.is_local(frame):
172
+ self.explanation = self.name
173
+
174
+ class Compare(Interpretable):
175
+ __view__ = ast.Compare
176
+
177
+ def eval(self, frame):
178
+ expr = Interpretable(self.expr)
179
+ expr.eval(frame)
180
+ for operation, expr2 in self.ops:
181
+ if hasattr(self, 'result'):
182
+ # shortcutting in chained expressions
183
+ if not frame.is_true(self.result):
184
+ break
185
+ expr2 = Interpretable(expr2)
186
+ expr2.eval(frame)
187
+ self.explanation = "%s %s %s" % (
188
+ expr.explanation, operation, expr2.explanation)
189
+ source = "__exprinfo_left %s __exprinfo_right" % operation
190
+ try:
191
+ self.result = frame.eval(source,
192
+ __exprinfo_left=expr.result,
193
+ __exprinfo_right=expr2.result)
194
+ except passthroughex:
195
+ raise
196
+ except:
197
+ raise Failure(self)
198
+ expr = expr2
199
+
200
+ class And(Interpretable):
201
+ __view__ = ast.And
202
+
203
+ def eval(self, frame):
204
+ explanations = []
205
+ for expr in self.nodes:
206
+ expr = Interpretable(expr)
207
+ expr.eval(frame)
208
+ explanations.append(expr.explanation)
209
+ self.result = expr.result
210
+ if not frame.is_true(expr.result):
211
+ break
212
+ self.explanation = '(' + ' and '.join(explanations) + ')'
213
+
214
+ class Or(Interpretable):
215
+ __view__ = ast.Or
216
+
217
+ def eval(self, frame):
218
+ explanations = []
219
+ for expr in self.nodes:
220
+ expr = Interpretable(expr)
221
+ expr.eval(frame)
222
+ explanations.append(expr.explanation)
223
+ self.result = expr.result
224
+ if frame.is_true(expr.result):
225
+ break
226
+ self.explanation = '(' + ' or '.join(explanations) + ')'
227
+
228
+
229
+ # == Unary operations ==
230
+ keepalive = []
231
+ for astclass, astpattern in {
232
+ ast.Not : 'not __exprinfo_expr',
233
+ ast.Invert : '(~__exprinfo_expr)',
234
+ }.items():
235
+
236
+ class UnaryArith(Interpretable):
237
+ __view__ = astclass
238
+
239
+ def eval(self, frame, astpattern=astpattern):
240
+ expr = Interpretable(self.expr)
241
+ expr.eval(frame)
242
+ self.explanation = astpattern.replace('__exprinfo_expr',
243
+ expr.explanation)
244
+ try:
245
+ self.result = frame.eval(astpattern,
246
+ __exprinfo_expr=expr.result)
247
+ except passthroughex:
248
+ raise
249
+ except:
250
+ raise Failure(self)
251
+
252
+ keepalive.append(UnaryArith)
253
+
254
+ # == Binary operations ==
255
+ for astclass, astpattern in {
256
+ ast.Add : '(__exprinfo_left + __exprinfo_right)',
257
+ ast.Sub : '(__exprinfo_left - __exprinfo_right)',
258
+ ast.Mul : '(__exprinfo_left * __exprinfo_right)',
259
+ ast.Div : '(__exprinfo_left / __exprinfo_right)',
260
+ ast.Mod : '(__exprinfo_left % __exprinfo_right)',
261
+ ast.Power : '(__exprinfo_left ** __exprinfo_right)',
262
+ }.items():
263
+
264
+ class BinaryArith(Interpretable):
265
+ __view__ = astclass
266
+
267
+ def eval(self, frame, astpattern=astpattern):
268
+ left = Interpretable(self.left)
269
+ left.eval(frame)
270
+ right = Interpretable(self.right)
271
+ right.eval(frame)
272
+ self.explanation = (astpattern
273
+ .replace('__exprinfo_left', left .explanation)
274
+ .replace('__exprinfo_right', right.explanation))
275
+ try:
276
+ self.result = frame.eval(astpattern,
277
+ __exprinfo_left=left.result,
278
+ __exprinfo_right=right.result)
279
+ except passthroughex:
280
+ raise
281
+ except:
282
+ raise Failure(self)
283
+
284
+ keepalive.append(BinaryArith)
285
+
286
+
287
+ class CallFunc(Interpretable):
288
+ __view__ = ast.CallFunc
289
+
290
+ def is_bool(self, frame):
291
+ source = 'isinstance(__exprinfo_value, bool)'
292
+ try:
293
+ return frame.is_true(frame.eval(source,
294
+ __exprinfo_value=self.result))
295
+ except passthroughex:
296
+ raise
297
+ except:
298
+ return False
299
+
300
+ def eval(self, frame):
301
+ node = Interpretable(self.node)
302
+ node.eval(frame)
303
+ explanations = []
304
+ vars = {'__exprinfo_fn': node.result}
305
+ source = '__exprinfo_fn('
306
+ for a in self.args:
307
+ if isinstance(a, ast.Keyword):
308
+ keyword = a.name
309
+ a = a.expr
310
+ else:
311
+ keyword = None
312
+ a = Interpretable(a)
313
+ a.eval(frame)
314
+ argname = '__exprinfo_%d' % len(vars)
315
+ vars[argname] = a.result
316
+ if keyword is None:
317
+ source += argname + ','
318
+ explanations.append(a.explanation)
319
+ else:
320
+ source += '%s=%s,' % (keyword, argname)
321
+ explanations.append('%s=%s' % (keyword, a.explanation))
322
+ if self.star_args:
323
+ star_args = Interpretable(self.star_args)
324
+ star_args.eval(frame)
325
+ argname = '__exprinfo_star'
326
+ vars[argname] = star_args.result
327
+ source += '*' + argname + ','
328
+ explanations.append('*' + star_args.explanation)
329
+ if self.dstar_args:
330
+ dstar_args = Interpretable(self.dstar_args)
331
+ dstar_args.eval(frame)
332
+ argname = '__exprinfo_kwds'
333
+ vars[argname] = dstar_args.result
334
+ source += '**' + argname + ','
335
+ explanations.append('**' + dstar_args.explanation)
336
+ self.explanation = "%s(%s)" % (
337
+ node.explanation, ', '.join(explanations))
338
+ if source.endswith(','):
339
+ source = source[:-1]
340
+ source += ')'
341
+ try:
342
+ self.result = frame.eval(source, **vars)
343
+ except passthroughex:
344
+ raise
345
+ except:
346
+ raise Failure(self)
347
+ if not node.is_builtin(frame) or not self.is_bool(frame):
348
+ r = frame.repr(self.result)
349
+ self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)
350
+
351
+ class Getattr(Interpretable):
352
+ __view__ = ast.Getattr
353
+
354
+ def eval(self, frame):
355
+ expr = Interpretable(self.expr)
356
+ expr.eval(frame)
357
+ source = '__exprinfo_expr.%s' % self.attrname
358
+ try:
359
+ self.result = frame.eval(source, __exprinfo_expr=expr.result)
360
+ except passthroughex:
361
+ raise
362
+ except:
363
+ raise Failure(self)
364
+ self.explanation = '%s.%s' % (expr.explanation, self.attrname)
365
+ # if the attribute comes from the instance, its value is interesting
366
+ source = ('hasattr(__exprinfo_expr, "__dict__") and '
367
+ '%r in __exprinfo_expr.__dict__' % self.attrname)
368
+ try:
369
+ from_instance = frame.is_true(
370
+ frame.eval(source, __exprinfo_expr=expr.result))
371
+ except passthroughex:
372
+ raise
373
+ except:
374
+ from_instance = True
375
+ if from_instance:
376
+ r = frame.repr(self.result)
377
+ self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)
378
+
379
+ # == Re-interpretation of full statements ==
380
+
381
+ class Assert(Interpretable):
382
+ __view__ = ast.Assert
383
+
384
+ def run(self, frame):
385
+ test = Interpretable(self.test)
386
+ test.eval(frame)
387
+ # simplify 'assert False where False = ...'
388
+ if (test.explanation.startswith('False\n{False = ') and
389
+ test.explanation.endswith('\n}')):
390
+ test.explanation = test.explanation[15:-2]
391
+ # print the result as 'assert <explanation>'
392
+ self.result = test.result
393
+ self.explanation = 'assert ' + test.explanation
394
+ if not frame.is_true(test.result):
395
+ try:
396
+ raise BuiltinAssertionError
397
+ except passthroughex:
398
+ raise
399
+ except:
400
+ raise Failure(self)
401
+
402
+ class Assign(Interpretable):
403
+ __view__ = ast.Assign
404
+
405
+ def run(self, frame):
406
+ expr = Interpretable(self.expr)
407
+ expr.eval(frame)
408
+ self.result = expr.result
409
+ self.explanation = '... = ' + expr.explanation
410
+ # fall-back-run the rest of the assignment
411
+ ass = ast.Assign(self.nodes, ast.Name('__exprinfo_expr'))
412
+ mod = ast.Module(None, ast.Stmt([ass]))
413
+ mod.filename = '<run>'
414
+ co = pycodegen.ModuleCodeGenerator(mod).getCode()
415
+ try:
416
+ frame.exec_(co, __exprinfo_expr=expr.result)
417
+ except passthroughex:
418
+ raise
419
+ except:
420
+ raise Failure(self)
421
+
422
+ class Discard(Interpretable):
423
+ __view__ = ast.Discard
424
+
425
+ def run(self, frame):
426
+ expr = Interpretable(self.expr)
427
+ expr.eval(frame)
428
+ self.result = expr.result
429
+ self.explanation = expr.explanation
430
+
431
+ class Stmt(Interpretable):
432
+ __view__ = ast.Stmt
433
+
434
+ def run(self, frame):
435
+ for stmt in self.nodes:
436
+ stmt = Interpretable(stmt)
437
+ stmt.run(frame)
438
+
439
+
440
+ def report_failure(e):
441
+ explanation = e.node.nice_explanation()
442
+ if explanation:
443
+ explanation = ", in: " + explanation
444
+ else:
445
+ explanation = ""
446
+ sys.stdout.write("%s: %s%s\n" % (e.exc.__name__, e.value, explanation))
447
+
448
+ def check(s, frame=None):
449
+ if frame is None:
450
+ frame = sys._getframe(1)
451
+ frame = py.code.Frame(frame)
452
+ expr = parse(s, 'eval')
453
+ assert isinstance(expr, ast.Expression)
454
+ node = Interpretable(expr.node)
455
+ try:
456
+ node.eval(frame)
457
+ except passthroughex:
458
+ raise
459
+ except Failure:
460
+ e = sys.exc_info()[1]
461
+ report_failure(e)
462
+ else:
463
+ if not frame.is_true(node.result):
464
+ sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())
465
+
466
+
467
+ ###########################################################
468
+ # API / Entry points
469
+ # #########################################################
470
+
471
+ def interpret(source, frame, should_fail=False):
472
+ module = Interpretable(parse(source, 'exec').node)
473
+ #print "got module", module
474
+ if isinstance(frame, types.FrameType):
475
+ frame = py.code.Frame(frame)
476
+ try:
477
+ module.run(frame)
478
+ except Failure:
479
+ e = sys.exc_info()[1]
480
+ return getfailure(e)
481
+ except passthroughex:
482
+ raise
483
+ except:
484
+ import traceback
485
+ traceback.print_exc()
486
+ if should_fail:
487
+ return ("(assertion failed, but when it was re-run for "
488
+ "printing intermediate values, it did not fail. Suggestions: "
489
+ "compute assert expression before the assert or use --nomagic)")
490
+ else:
491
+ return None
492
+
493
+ def getmsg(excinfo):
494
+ if isinstance(excinfo, tuple):
495
+ excinfo = py.code.ExceptionInfo(excinfo)
496
+ #frame, line = gettbline(tb)
497
+ #frame = py.code.Frame(frame)
498
+ #return interpret(line, frame)
499
+
500
+ tb = excinfo.traceback[-1]
501
+ source = str(tb.statement).strip()
502
+ x = interpret(source, tb.frame, should_fail=True)
503
+ if not isinstance(x, str):
504
+ raise TypeError("interpret returned non-string %r" % (x,))
505
+ return x
506
+
507
+ def getfailure(e):
508
+ explanation = e.node.nice_explanation()
509
+ if str(e.value):
510
+ lines = explanation.split('\n')
511
+ lines[0] += " << %s" % (e.value,)
512
+ explanation = '\n'.join(lines)
513
+ text = "%s: %s" % (e.exc.__name__, explanation)
514
+ if text.startswith('AssertionError: assert '):
515
+ text = text[16:]
516
+ return text
517
+
518
+ def run(s, frame=None):
519
+ if frame is None:
520
+ frame = sys._getframe(1)
521
+ frame = py.code.Frame(frame)
522
+ module = Interpretable(parse(s, 'exec').node)
523
+ try:
524
+ module.run(frame)
525
+ except Failure:
526
+ e = sys.exc_info()[1]
527
+ report_failure(e)
528
+
529
+
530
+ if __name__ == '__main__':
531
+ # example:
532
+ def f():
533
+ return 5
534
+ def g():
535
+ return 3
536
+ def h(x):
537
+ return 'never'
538
+ check("f() * g() == 5")
539
+ check("not f()")
540
+ check("not (f() and g() or 0)")
541
+ check("f() == g()")
542
+ i = 4
543
+ check("i == f()")
544
+ check("len(f()) == 0")
545
+ check("isinstance(2+3+4, float)")
546
+
547
+ run("x = i")
548
+ check("x == 5")
549
+
550
+ run("assert not f(), 'oops'")
551
+ run("a, b, c = 1, 2")
552
+ run("a, b, c = f()")
553
+
554
+ check("max([f(),g()]) == 4")
555
+ check("'hello'[g()] == 'h'")
556
+ run("'guk%d' % h(f())")
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/_py2traceback.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copied from python-2.7.3's traceback.py
2
+ # CHANGES:
3
+ # - some_str is replaced, trying to create unicode strings
4
+ #
5
+ import types
6
+
7
+ def format_exception_only(etype, value):
8
+ """Format the exception part of a traceback.
9
+
10
+ The arguments are the exception type and value such as given by
11
+ sys.last_type and sys.last_value. The return value is a list of
12
+ strings, each ending in a newline.
13
+
14
+ Normally, the list contains a single string; however, for
15
+ SyntaxError exceptions, it contains several lines that (when
16
+ printed) display detailed information about where the syntax
17
+ error occurred.
18
+
19
+ The message indicating which exception occurred is always the last
20
+ string in the list.
21
+
22
+ """
23
+
24
+ # An instance should not have a meaningful value parameter, but
25
+ # sometimes does, particularly for string exceptions, such as
26
+ # >>> raise string1, string2 # deprecated
27
+ #
28
+ # Clear these out first because issubtype(string1, SyntaxError)
29
+ # would throw another exception and mask the original problem.
30
+ if (isinstance(etype, BaseException) or
31
+ isinstance(etype, types.InstanceType) or
32
+ etype is None or type(etype) is str):
33
+ return [_format_final_exc_line(etype, value)]
34
+
35
+ stype = etype.__name__
36
+
37
+ if not issubclass(etype, SyntaxError):
38
+ return [_format_final_exc_line(stype, value)]
39
+
40
+ # It was a syntax error; show exactly where the problem was found.
41
+ lines = []
42
+ try:
43
+ msg, (filename, lineno, offset, badline) = value.args
44
+ except Exception:
45
+ pass
46
+ else:
47
+ filename = filename or "<string>"
48
+ lines.append(' File "%s", line %d\n' % (filename, lineno))
49
+ if badline is not None:
50
+ lines.append(' %s\n' % badline.strip())
51
+ if offset is not None:
52
+ caretspace = badline.rstrip('\n')[:offset].lstrip()
53
+ # non-space whitespace (likes tabs) must be kept for alignment
54
+ caretspace = ((c.isspace() and c or ' ') for c in caretspace)
55
+ # only three spaces to account for offset1 == pos 0
56
+ lines.append(' %s^\n' % ''.join(caretspace))
57
+ value = msg
58
+
59
+ lines.append(_format_final_exc_line(stype, value))
60
+ return lines
61
+
62
+ def _format_final_exc_line(etype, value):
63
+ """Return a list of a single line -- normal case for format_exception_only"""
64
+ valuestr = _some_str(value)
65
+ if value is None or not valuestr:
66
+ line = "%s\n" % etype
67
+ else:
68
+ line = "%s: %s\n" % (etype, valuestr)
69
+ return line
70
+
71
+ def _some_str(value):
72
+ try:
73
+ return unicode(value)
74
+ except Exception:
75
+ try:
76
+ return str(value)
77
+ except Exception:
78
+ pass
79
+ return '<unprintable %s object>' % type(value).__name__
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/assertion.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import py
3
+
4
+ BuiltinAssertionError = py.builtin.builtins.AssertionError
5
+
6
+ _reprcompare = None # if set, will be called by assert reinterp for comparison ops
7
+
8
+ def _format_explanation(explanation):
9
+ """This formats an explanation
10
+
11
+ Normally all embedded newlines are escaped, however there are
12
+ three exceptions: \n{, \n} and \n~. The first two are intended
13
+ cover nested explanations, see function and attribute explanations
14
+ for examples (.visit_Call(), visit_Attribute()). The last one is
15
+ for when one explanation needs to span multiple lines, e.g. when
16
+ displaying diffs.
17
+ """
18
+ raw_lines = (explanation or '').split('\n')
19
+ # escape newlines not followed by {, } and ~
20
+ lines = [raw_lines[0]]
21
+ for l in raw_lines[1:]:
22
+ if l.startswith('{') or l.startswith('}') or l.startswith('~'):
23
+ lines.append(l)
24
+ else:
25
+ lines[-1] += '\\n' + l
26
+
27
+ result = lines[:1]
28
+ stack = [0]
29
+ stackcnt = [0]
30
+ for line in lines[1:]:
31
+ if line.startswith('{'):
32
+ if stackcnt[-1]:
33
+ s = 'and '
34
+ else:
35
+ s = 'where '
36
+ stack.append(len(result))
37
+ stackcnt[-1] += 1
38
+ stackcnt.append(0)
39
+ result.append(' +' + ' '*(len(stack)-1) + s + line[1:])
40
+ elif line.startswith('}'):
41
+ assert line.startswith('}')
42
+ stack.pop()
43
+ stackcnt.pop()
44
+ result[stack[-1]] += line[1:]
45
+ else:
46
+ assert line.startswith('~')
47
+ result.append(' '*len(stack) + line[1:])
48
+ assert len(stack) == 1
49
+ return '\n'.join(result)
50
+
51
+
52
+ class AssertionError(BuiltinAssertionError):
53
+ def __init__(self, *args):
54
+ BuiltinAssertionError.__init__(self, *args)
55
+ if args:
56
+ try:
57
+ self.msg = str(args[0])
58
+ except py.builtin._sysex:
59
+ raise
60
+ except:
61
+ self.msg = "<[broken __repr__] %s at %0xd>" %(
62
+ args[0].__class__, id(args[0]))
63
+ else:
64
+ f = py.code.Frame(sys._getframe(1))
65
+ try:
66
+ source = f.code.fullsource
67
+ if source is not None:
68
+ try:
69
+ source = source.getstatement(f.lineno, assertion=True)
70
+ except IndexError:
71
+ source = None
72
+ else:
73
+ source = str(source.deindent()).strip()
74
+ except py.error.ENOENT:
75
+ source = None
76
+ # this can also occur during reinterpretation, when the
77
+ # co_filename is set to "<run>".
78
+ if source:
79
+ self.msg = reinterpret(source, f, should_fail=True)
80
+ else:
81
+ self.msg = "<could not determine information>"
82
+ if not self.args:
83
+ self.args = (self.msg,)
84
+
85
+ if sys.version_info > (3, 0):
86
+ AssertionError.__module__ = "builtins"
87
+ reinterpret_old = "old reinterpretation not available for py3"
88
+ else:
89
+ from py._code._assertionold import interpret as reinterpret_old
90
+ from py._code._assertionnew import interpret as reinterpret
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/code.py ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import py
2
+ import sys
3
+ from inspect import CO_VARARGS, CO_VARKEYWORDS, isclass
4
+
5
+ builtin_repr = repr
6
+
7
+ reprlib = py.builtin._tryimport('repr', 'reprlib')
8
+
9
+ if sys.version_info[0] >= 3:
10
+ from traceback import format_exception_only
11
+ else:
12
+ from py._code._py2traceback import format_exception_only
13
+
14
+ import traceback
15
+
16
+
17
+ class Code(object):
18
+ """ wrapper around Python code objects """
19
+ def __init__(self, rawcode):
20
+ if not hasattr(rawcode, "co_filename"):
21
+ rawcode = py.code.getrawcode(rawcode)
22
+ try:
23
+ self.filename = rawcode.co_filename
24
+ self.firstlineno = rawcode.co_firstlineno - 1
25
+ self.name = rawcode.co_name
26
+ except AttributeError:
27
+ raise TypeError("not a code object: %r" % (rawcode,))
28
+ self.raw = rawcode
29
+
30
+ def __eq__(self, other):
31
+ return self.raw == other.raw
32
+
33
+ def __ne__(self, other):
34
+ return not self == other
35
+
36
+ @property
37
+ def path(self):
38
+ """ return a path object pointing to source code (note that it
39
+ might not point to an actually existing file). """
40
+ p = py.path.local(self.raw.co_filename)
41
+ # maybe don't try this checking
42
+ if not p.check():
43
+ # XXX maybe try harder like the weird logic
44
+ # in the standard lib [linecache.updatecache] does?
45
+ p = self.raw.co_filename
46
+ return p
47
+
48
+ @property
49
+ def fullsource(self):
50
+ """ return a py.code.Source object for the full source file of the code
51
+ """
52
+ from py._code import source
53
+ full, _ = source.findsource(self.raw)
54
+ return full
55
+
56
+ def source(self):
57
+ """ return a py.code.Source object for the code object's source only
58
+ """
59
+ # return source only for that part of code
60
+ return py.code.Source(self.raw)
61
+
62
+ def getargs(self, var=False):
63
+ """ return a tuple with the argument names for the code object
64
+
65
+ if 'var' is set True also return the names of the variable and
66
+ keyword arguments when present
67
+ """
68
+ # handfull shortcut for getting args
69
+ raw = self.raw
70
+ argcount = raw.co_argcount
71
+ if var:
72
+ argcount += raw.co_flags & CO_VARARGS
73
+ argcount += raw.co_flags & CO_VARKEYWORDS
74
+ return raw.co_varnames[:argcount]
75
+
76
+ class Frame(object):
77
+ """Wrapper around a Python frame holding f_locals and f_globals
78
+ in which expressions can be evaluated."""
79
+
80
+ def __init__(self, frame):
81
+ self.lineno = frame.f_lineno - 1
82
+ self.f_globals = frame.f_globals
83
+ self.f_locals = frame.f_locals
84
+ self.raw = frame
85
+ self.code = py.code.Code(frame.f_code)
86
+
87
+ @property
88
+ def statement(self):
89
+ """ statement this frame is at """
90
+ if self.code.fullsource is None:
91
+ return py.code.Source("")
92
+ return self.code.fullsource.getstatement(self.lineno)
93
+
94
+ def eval(self, code, **vars):
95
+ """ evaluate 'code' in the frame
96
+
97
+ 'vars' are optional additional local variables
98
+
99
+ returns the result of the evaluation
100
+ """
101
+ f_locals = self.f_locals.copy()
102
+ f_locals.update(vars)
103
+ return eval(code, self.f_globals, f_locals)
104
+
105
+ def exec_(self, code, **vars):
106
+ """ exec 'code' in the frame
107
+
108
+ 'vars' are optiona; additional local variables
109
+ """
110
+ f_locals = self.f_locals.copy()
111
+ f_locals.update(vars)
112
+ py.builtin.exec_(code, self.f_globals, f_locals)
113
+
114
+ def repr(self, object):
115
+ """ return a 'safe' (non-recursive, one-line) string repr for 'object'
116
+ """
117
+ return py.io.saferepr(object)
118
+
119
+ def is_true(self, object):
120
+ return object
121
+
122
+ def getargs(self, var=False):
123
+ """ return a list of tuples (name, value) for all arguments
124
+
125
+ if 'var' is set True also include the variable and keyword
126
+ arguments when present
127
+ """
128
+ retval = []
129
+ for arg in self.code.getargs(var):
130
+ try:
131
+ retval.append((arg, self.f_locals[arg]))
132
+ except KeyError:
133
+ pass # this can occur when using Psyco
134
+ return retval
135
+
136
+
137
+ class TracebackEntry(object):
138
+ """ a single entry in a traceback """
139
+
140
+ _repr_style = None
141
+ exprinfo = None
142
+
143
+ def __init__(self, rawentry):
144
+ self._rawentry = rawentry
145
+ self.lineno = rawentry.tb_lineno - 1
146
+
147
+ def set_repr_style(self, mode):
148
+ assert mode in ("short", "long")
149
+ self._repr_style = mode
150
+
151
+ @property
152
+ def frame(self):
153
+ return py.code.Frame(self._rawentry.tb_frame)
154
+
155
+ @property
156
+ def relline(self):
157
+ return self.lineno - self.frame.code.firstlineno
158
+
159
+ def __repr__(self):
160
+ return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno+1)
161
+
162
+ @property
163
+ def statement(self):
164
+ """ py.code.Source object for the current statement """
165
+ source = self.frame.code.fullsource
166
+ return source.getstatement(self.lineno)
167
+
168
+ @property
169
+ def path(self):
170
+ """ path to the source code """
171
+ return self.frame.code.path
172
+
173
+ def getlocals(self):
174
+ return self.frame.f_locals
175
+ locals = property(getlocals, None, None, "locals of underlaying frame")
176
+
177
+ def reinterpret(self):
178
+ """Reinterpret the failing statement and returns a detailed information
179
+ about what operations are performed."""
180
+ if self.exprinfo is None:
181
+ source = str(self.statement).strip()
182
+ x = py.code._reinterpret(source, self.frame, should_fail=True)
183
+ if not isinstance(x, str):
184
+ raise TypeError("interpret returned non-string %r" % (x,))
185
+ self.exprinfo = x
186
+ return self.exprinfo
187
+
188
+ def getfirstlinesource(self):
189
+ # on Jython this firstlineno can be -1 apparently
190
+ return max(self.frame.code.firstlineno, 0)
191
+
192
+ def getsource(self, astcache=None):
193
+ """ return failing source code. """
194
+ # we use the passed in astcache to not reparse asttrees
195
+ # within exception info printing
196
+ from py._code.source import getstatementrange_ast
197
+ source = self.frame.code.fullsource
198
+ if source is None:
199
+ return None
200
+ key = astnode = None
201
+ if astcache is not None:
202
+ key = self.frame.code.path
203
+ if key is not None:
204
+ astnode = astcache.get(key, None)
205
+ start = self.getfirstlinesource()
206
+ try:
207
+ astnode, _, end = getstatementrange_ast(self.lineno, source,
208
+ astnode=astnode)
209
+ except SyntaxError:
210
+ end = self.lineno + 1
211
+ else:
212
+ if key is not None:
213
+ astcache[key] = astnode
214
+ return source[start:end]
215
+
216
+ source = property(getsource)
217
+
218
+ def ishidden(self):
219
+ """ return True if the current frame has a var __tracebackhide__
220
+ resolving to True
221
+
222
+ mostly for internal use
223
+ """
224
+ try:
225
+ return self.frame.f_locals['__tracebackhide__']
226
+ except KeyError:
227
+ try:
228
+ return self.frame.f_globals['__tracebackhide__']
229
+ except KeyError:
230
+ return False
231
+
232
+ def __str__(self):
233
+ try:
234
+ fn = str(self.path)
235
+ except py.error.Error:
236
+ fn = '???'
237
+ name = self.frame.code.name
238
+ try:
239
+ line = str(self.statement).lstrip()
240
+ except KeyboardInterrupt:
241
+ raise
242
+ except:
243
+ line = "???"
244
+ return " File %r:%d in %s\n %s\n" % (fn, self.lineno+1, name, line)
245
+
246
+ def name(self):
247
+ return self.frame.code.raw.co_name
248
+ name = property(name, None, None, "co_name of underlaying code")
249
+
250
+
251
+ class Traceback(list):
252
+ """ Traceback objects encapsulate and offer higher level
253
+ access to Traceback entries.
254
+ """
255
+ Entry = TracebackEntry
256
+
257
+ def __init__(self, tb):
258
+ """ initialize from given python traceback object. """
259
+ if hasattr(tb, 'tb_next'):
260
+ def f(cur):
261
+ while cur is not None:
262
+ yield self.Entry(cur)
263
+ cur = cur.tb_next
264
+ list.__init__(self, f(tb))
265
+ else:
266
+ list.__init__(self, tb)
267
+
268
+ def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
269
+ """ return a Traceback instance wrapping part of this Traceback
270
+
271
+ by provding any combination of path, lineno and firstlineno, the
272
+ first frame to start the to-be-returned traceback is determined
273
+
274
+ this allows cutting the first part of a Traceback instance e.g.
275
+ for formatting reasons (removing some uninteresting bits that deal
276
+ with handling of the exception/traceback)
277
+ """
278
+ for x in self:
279
+ code = x.frame.code
280
+ codepath = code.path
281
+ if ((path is None or codepath == path) and
282
+ (excludepath is None or not hasattr(codepath, 'relto') or
283
+ not codepath.relto(excludepath)) and
284
+ (lineno is None or x.lineno == lineno) and
285
+ (firstlineno is None or x.frame.code.firstlineno == firstlineno)):
286
+ return Traceback(x._rawentry)
287
+ return self
288
+
289
+ def __getitem__(self, key):
290
+ val = super(Traceback, self).__getitem__(key)
291
+ if isinstance(key, type(slice(0))):
292
+ val = self.__class__(val)
293
+ return val
294
+
295
+ def filter(self, fn=lambda x: not x.ishidden()):
296
+ """ return a Traceback instance with certain items removed
297
+
298
+ fn is a function that gets a single argument, a TracebackItem
299
+ instance, and should return True when the item should be added
300
+ to the Traceback, False when not
301
+
302
+ by default this removes all the TracebackItems which are hidden
303
+ (see ishidden() above)
304
+ """
305
+ return Traceback(filter(fn, self))
306
+
307
+ def getcrashentry(self):
308
+ """ return last non-hidden traceback entry that lead
309
+ to the exception of a traceback.
310
+ """
311
+ for i in range(-1, -len(self)-1, -1):
312
+ entry = self[i]
313
+ if not entry.ishidden():
314
+ return entry
315
+ return self[-1]
316
+
317
+ def recursionindex(self):
318
+ """ return the index of the frame/TracebackItem where recursion
319
+ originates if appropriate, None if no recursion occurred
320
+ """
321
+ cache = {}
322
+ for i, entry in enumerate(self):
323
+ # id for the code.raw is needed to work around
324
+ # the strange metaprogramming in the decorator lib from pypi
325
+ # which generates code objects that have hash/value equality
326
+ #XXX needs a test
327
+ key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
328
+ #print "checking for recursion at", key
329
+ l = cache.setdefault(key, [])
330
+ if l:
331
+ f = entry.frame
332
+ loc = f.f_locals
333
+ for otherloc in l:
334
+ if f.is_true(f.eval(co_equal,
335
+ __recursioncache_locals_1=loc,
336
+ __recursioncache_locals_2=otherloc)):
337
+ return i
338
+ l.append(entry.frame.f_locals)
339
+ return None
340
+
341
+ co_equal = compile('__recursioncache_locals_1 == __recursioncache_locals_2',
342
+ '?', 'eval')
343
+
344
+ class ExceptionInfo(object):
345
+ """ wraps sys.exc_info() objects and offers
346
+ help for navigating the traceback.
347
+ """
348
+ _striptext = ''
349
+ def __init__(self, tup=None, exprinfo=None):
350
+ if tup is None:
351
+ tup = sys.exc_info()
352
+ if exprinfo is None and isinstance(tup[1], AssertionError):
353
+ exprinfo = getattr(tup[1], 'msg', None)
354
+ if exprinfo is None:
355
+ exprinfo = str(tup[1])
356
+ if exprinfo and exprinfo.startswith('assert '):
357
+ self._striptext = 'AssertionError: '
358
+ self._excinfo = tup
359
+ #: the exception class
360
+ self.type = tup[0]
361
+ #: the exception instance
362
+ self.value = tup[1]
363
+ #: the exception raw traceback
364
+ self.tb = tup[2]
365
+ #: the exception type name
366
+ self.typename = self.type.__name__
367
+ #: the exception traceback (py.code.Traceback instance)
368
+ self.traceback = py.code.Traceback(self.tb)
369
+
370
+ def __repr__(self):
371
+ return "<ExceptionInfo %s tblen=%d>" % (
372
+ self.typename, len(self.traceback))
373
+
374
+ def exconly(self, tryshort=False):
375
+ """ return the exception as a string
376
+
377
+ when 'tryshort' resolves to True, and the exception is a
378
+ py.code._AssertionError, only the actual exception part of
379
+ the exception representation is returned (so 'AssertionError: ' is
380
+ removed from the beginning)
381
+ """
382
+ lines = format_exception_only(self.type, self.value)
383
+ text = ''.join(lines)
384
+ text = text.rstrip()
385
+ if tryshort:
386
+ if text.startswith(self._striptext):
387
+ text = text[len(self._striptext):]
388
+ return text
389
+
390
+ def errisinstance(self, exc):
391
+ """ return True if the exception is an instance of exc """
392
+ return isinstance(self.value, exc)
393
+
394
+ def _getreprcrash(self):
395
+ exconly = self.exconly(tryshort=True)
396
+ entry = self.traceback.getcrashentry()
397
+ path, lineno = entry.frame.code.raw.co_filename, entry.lineno
398
+ return ReprFileLocation(path, lineno+1, exconly)
399
+
400
+ def getrepr(self, showlocals=False, style="long",
401
+ abspath=False, tbfilter=True, funcargs=False):
402
+ """ return str()able representation of this exception info.
403
+ showlocals: show locals per traceback entry
404
+ style: long|short|no|native traceback style
405
+ tbfilter: hide entries (where __tracebackhide__ is true)
406
+
407
+ in case of style==native, tbfilter and showlocals is ignored.
408
+ """
409
+ if style == 'native':
410
+ return ReprExceptionInfo(ReprTracebackNative(
411
+ traceback.format_exception(
412
+ self.type,
413
+ self.value,
414
+ self.traceback[0]._rawentry,
415
+ )), self._getreprcrash())
416
+
417
+ fmt = FormattedExcinfo(
418
+ showlocals=showlocals, style=style,
419
+ abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
420
+ return fmt.repr_excinfo(self)
421
+
422
+ def __str__(self):
423
+ entry = self.traceback[-1]
424
+ loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
425
+ return str(loc)
426
+
427
+ def __unicode__(self):
428
+ entry = self.traceback[-1]
429
+ loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
430
+ return loc.__unicode__()
431
+
432
+
433
+ class FormattedExcinfo(object):
434
+ """ presenting information about failing Functions and Generators. """
435
+ # for traceback entries
436
+ flow_marker = ">"
437
+ fail_marker = "E"
438
+
439
+ def __init__(self, showlocals=False, style="long",
440
+ abspath=True, tbfilter=True, funcargs=False):
441
+ self.showlocals = showlocals
442
+ self.style = style
443
+ self.tbfilter = tbfilter
444
+ self.funcargs = funcargs
445
+ self.abspath = abspath
446
+ self.astcache = {}
447
+
448
+ def _getindent(self, source):
449
+ # figure out indent for given source
450
+ try:
451
+ s = str(source.getstatement(len(source)-1))
452
+ except KeyboardInterrupt:
453
+ raise
454
+ except:
455
+ try:
456
+ s = str(source[-1])
457
+ except KeyboardInterrupt:
458
+ raise
459
+ except:
460
+ return 0
461
+ return 4 + (len(s) - len(s.lstrip()))
462
+
463
+ def _getentrysource(self, entry):
464
+ source = entry.getsource(self.astcache)
465
+ if source is not None:
466
+ source = source.deindent()
467
+ return source
468
+
469
+ def _saferepr(self, obj):
470
+ return py.io.saferepr(obj)
471
+
472
+ def repr_args(self, entry):
473
+ if self.funcargs:
474
+ args = []
475
+ for argname, argvalue in entry.frame.getargs(var=True):
476
+ args.append((argname, self._saferepr(argvalue)))
477
+ return ReprFuncArgs(args)
478
+
479
+ def get_source(self, source, line_index=-1, excinfo=None, short=False):
480
+ """ return formatted and marked up source lines. """
481
+ lines = []
482
+ if source is None or line_index >= len(source.lines):
483
+ source = py.code.Source("???")
484
+ line_index = 0
485
+ if line_index < 0:
486
+ line_index += len(source)
487
+ space_prefix = " "
488
+ if short:
489
+ lines.append(space_prefix + source.lines[line_index].strip())
490
+ else:
491
+ for line in source.lines[:line_index]:
492
+ lines.append(space_prefix + line)
493
+ lines.append(self.flow_marker + " " + source.lines[line_index])
494
+ for line in source.lines[line_index+1:]:
495
+ lines.append(space_prefix + line)
496
+ if excinfo is not None:
497
+ indent = 4 if short else self._getindent(source)
498
+ lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
499
+ return lines
500
+
501
+ def get_exconly(self, excinfo, indent=4, markall=False):
502
+ lines = []
503
+ indent = " " * indent
504
+ # get the real exception information out
505
+ exlines = excinfo.exconly(tryshort=True).split('\n')
506
+ failindent = self.fail_marker + indent[1:]
507
+ for line in exlines:
508
+ lines.append(failindent + line)
509
+ if not markall:
510
+ failindent = indent
511
+ return lines
512
+
513
+ def repr_locals(self, locals):
514
+ if self.showlocals:
515
+ lines = []
516
+ keys = [loc for loc in locals if loc[0] != "@"]
517
+ keys.sort()
518
+ for name in keys:
519
+ value = locals[name]
520
+ if name == '__builtins__':
521
+ lines.append("__builtins__ = <builtins>")
522
+ else:
523
+ # This formatting could all be handled by the
524
+ # _repr() function, which is only reprlib.Repr in
525
+ # disguise, so is very configurable.
526
+ str_repr = self._saferepr(value)
527
+ #if len(str_repr) < 70 or not isinstance(value,
528
+ # (list, tuple, dict)):
529
+ lines.append("%-10s = %s" %(name, str_repr))
530
+ #else:
531
+ # self._line("%-10s =\\" % (name,))
532
+ # # XXX
533
+ # pprint.pprint(value, stream=self.excinfowriter)
534
+ return ReprLocals(lines)
535
+
536
+ def repr_traceback_entry(self, entry, excinfo=None):
537
+ source = self._getentrysource(entry)
538
+ if source is None:
539
+ source = py.code.Source("???")
540
+ line_index = 0
541
+ else:
542
+ # entry.getfirstlinesource() can be -1, should be 0 on jython
543
+ line_index = entry.lineno - max(entry.getfirstlinesource(), 0)
544
+
545
+ lines = []
546
+ style = entry._repr_style
547
+ if style is None:
548
+ style = self.style
549
+ if style in ("short", "long"):
550
+ short = style == "short"
551
+ reprargs = self.repr_args(entry) if not short else None
552
+ s = self.get_source(source, line_index, excinfo, short=short)
553
+ lines.extend(s)
554
+ if short:
555
+ message = "in %s" %(entry.name)
556
+ else:
557
+ message = excinfo and excinfo.typename or ""
558
+ path = self._makepath(entry.path)
559
+ filelocrepr = ReprFileLocation(path, entry.lineno+1, message)
560
+ localsrepr = None
561
+ if not short:
562
+ localsrepr = self.repr_locals(entry.locals)
563
+ return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
564
+ if excinfo:
565
+ lines.extend(self.get_exconly(excinfo, indent=4))
566
+ return ReprEntry(lines, None, None, None, style)
567
+
568
+ def _makepath(self, path):
569
+ if not self.abspath:
570
+ try:
571
+ np = py.path.local().bestrelpath(path)
572
+ except OSError:
573
+ return path
574
+ if len(np) < len(str(path)):
575
+ path = np
576
+ return path
577
+
578
+ def repr_traceback(self, excinfo):
579
+ traceback = excinfo.traceback
580
+ if self.tbfilter:
581
+ traceback = traceback.filter()
582
+ recursionindex = None
583
+ if excinfo.errisinstance(RuntimeError):
584
+ if "maximum recursion depth exceeded" in str(excinfo.value):
585
+ recursionindex = traceback.recursionindex()
586
+ last = traceback[-1]
587
+ entries = []
588
+ extraline = None
589
+ for index, entry in enumerate(traceback):
590
+ einfo = (last == entry) and excinfo or None
591
+ reprentry = self.repr_traceback_entry(entry, einfo)
592
+ entries.append(reprentry)
593
+ if index == recursionindex:
594
+ extraline = "!!! Recursion detected (same locals & position)"
595
+ break
596
+ return ReprTraceback(entries, extraline, style=self.style)
597
+
598
+ def repr_excinfo(self, excinfo):
599
+ reprtraceback = self.repr_traceback(excinfo)
600
+ reprcrash = excinfo._getreprcrash()
601
+ return ReprExceptionInfo(reprtraceback, reprcrash)
602
+
603
+ class TerminalRepr:
604
+ def __str__(self):
605
+ s = self.__unicode__()
606
+ if sys.version_info[0] < 3:
607
+ s = s.encode('utf-8')
608
+ return s
609
+
610
+ def __unicode__(self):
611
+ # FYI this is called from pytest-xdist's serialization of exception
612
+ # information.
613
+ io = py.io.TextIO()
614
+ tw = py.io.TerminalWriter(file=io)
615
+ self.toterminal(tw)
616
+ return io.getvalue().strip()
617
+
618
+ def __repr__(self):
619
+ return "<%s instance at %0x>" %(self.__class__, id(self))
620
+
621
+
622
+ class ReprExceptionInfo(TerminalRepr):
623
+ def __init__(self, reprtraceback, reprcrash):
624
+ self.reprtraceback = reprtraceback
625
+ self.reprcrash = reprcrash
626
+ self.sections = []
627
+
628
+ def addsection(self, name, content, sep="-"):
629
+ self.sections.append((name, content, sep))
630
+
631
+ def toterminal(self, tw):
632
+ self.reprtraceback.toterminal(tw)
633
+ for name, content, sep in self.sections:
634
+ tw.sep(sep, name)
635
+ tw.line(content)
636
+
637
+ class ReprTraceback(TerminalRepr):
638
+ entrysep = "_ "
639
+
640
+ def __init__(self, reprentries, extraline, style):
641
+ self.reprentries = reprentries
642
+ self.extraline = extraline
643
+ self.style = style
644
+
645
+ def toterminal(self, tw):
646
+ # the entries might have different styles
647
+ last_style = None
648
+ for i, entry in enumerate(self.reprentries):
649
+ if entry.style == "long":
650
+ tw.line("")
651
+ entry.toterminal(tw)
652
+ if i < len(self.reprentries) - 1:
653
+ next_entry = self.reprentries[i+1]
654
+ if entry.style == "long" or \
655
+ entry.style == "short" and next_entry.style == "long":
656
+ tw.sep(self.entrysep)
657
+
658
+ if self.extraline:
659
+ tw.line(self.extraline)
660
+
661
+ class ReprTracebackNative(ReprTraceback):
662
+ def __init__(self, tblines):
663
+ self.style = "native"
664
+ self.reprentries = [ReprEntryNative(tblines)]
665
+ self.extraline = None
666
+
667
+ class ReprEntryNative(TerminalRepr):
668
+ style = "native"
669
+
670
+ def __init__(self, tblines):
671
+ self.lines = tblines
672
+
673
+ def toterminal(self, tw):
674
+ tw.write("".join(self.lines))
675
+
676
+ class ReprEntry(TerminalRepr):
677
+ localssep = "_ "
678
+
679
+ def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):
680
+ self.lines = lines
681
+ self.reprfuncargs = reprfuncargs
682
+ self.reprlocals = reprlocals
683
+ self.reprfileloc = filelocrepr
684
+ self.style = style
685
+
686
+ def toterminal(self, tw):
687
+ if self.style == "short":
688
+ self.reprfileloc.toterminal(tw)
689
+ for line in self.lines:
690
+ red = line.startswith("E ")
691
+ tw.line(line, bold=True, red=red)
692
+ #tw.line("")
693
+ return
694
+ if self.reprfuncargs:
695
+ self.reprfuncargs.toterminal(tw)
696
+ for line in self.lines:
697
+ red = line.startswith("E ")
698
+ tw.line(line, bold=True, red=red)
699
+ if self.reprlocals:
700
+ #tw.sep(self.localssep, "Locals")
701
+ tw.line("")
702
+ self.reprlocals.toterminal(tw)
703
+ if self.reprfileloc:
704
+ if self.lines:
705
+ tw.line("")
706
+ self.reprfileloc.toterminal(tw)
707
+
708
+ def __str__(self):
709
+ return "%s\n%s\n%s" % ("\n".join(self.lines),
710
+ self.reprlocals,
711
+ self.reprfileloc)
712
+
713
+ class ReprFileLocation(TerminalRepr):
714
+ def __init__(self, path, lineno, message):
715
+ self.path = str(path)
716
+ self.lineno = lineno
717
+ self.message = message
718
+
719
+ def toterminal(self, tw):
720
+ # filename and lineno output for each entry,
721
+ # using an output format that most editors unterstand
722
+ msg = self.message
723
+ i = msg.find("\n")
724
+ if i != -1:
725
+ msg = msg[:i]
726
+ tw.line("%s:%s: %s" %(self.path, self.lineno, msg))
727
+
728
+ class ReprLocals(TerminalRepr):
729
+ def __init__(self, lines):
730
+ self.lines = lines
731
+
732
+ def toterminal(self, tw):
733
+ for line in self.lines:
734
+ tw.line(line)
735
+
736
+ class ReprFuncArgs(TerminalRepr):
737
+ def __init__(self, args):
738
+ self.args = args
739
+
740
+ def toterminal(self, tw):
741
+ if self.args:
742
+ linesofar = ""
743
+ for name, value in self.args:
744
+ ns = "%s = %s" %(name, value)
745
+ if len(ns) + len(linesofar) + 2 > tw.fullwidth:
746
+ if linesofar:
747
+ tw.line(linesofar)
748
+ linesofar = ns
749
+ else:
750
+ if linesofar:
751
+ linesofar += ", " + ns
752
+ else:
753
+ linesofar = ns
754
+ if linesofar:
755
+ tw.line(linesofar)
756
+ tw.line("")
757
+
758
+
759
+
760
+ oldbuiltins = {}
761
+
762
+ def patch_builtins(assertion=True, compile=True):
763
+ """ put compile and AssertionError builtins to Python's builtins. """
764
+ if assertion:
765
+ from py._code import assertion
766
+ l = oldbuiltins.setdefault('AssertionError', [])
767
+ l.append(py.builtin.builtins.AssertionError)
768
+ py.builtin.builtins.AssertionError = assertion.AssertionError
769
+ if compile:
770
+ l = oldbuiltins.setdefault('compile', [])
771
+ l.append(py.builtin.builtins.compile)
772
+ py.builtin.builtins.compile = py.code.compile
773
+
774
+ def unpatch_builtins(assertion=True, compile=True):
775
+ """ remove compile and AssertionError builtins from Python builtins. """
776
+ if assertion:
777
+ py.builtin.builtins.AssertionError = oldbuiltins['AssertionError'].pop()
778
+ if compile:
779
+ py.builtin.builtins.compile = oldbuiltins['compile'].pop()
780
+
781
+ def getrawcode(obj, trycall=True):
782
+ """ return code object for given function. """
783
+ try:
784
+ return obj.__code__
785
+ except AttributeError:
786
+ obj = getattr(obj, 'im_func', obj)
787
+ obj = getattr(obj, 'func_code', obj)
788
+ obj = getattr(obj, 'f_code', obj)
789
+ obj = getattr(obj, '__code__', obj)
790
+ if trycall and not hasattr(obj, 'co_firstlineno'):
791
+ if hasattr(obj, '__call__') and not isclass(obj):
792
+ x = getrawcode(obj.__call__, trycall=False)
793
+ if hasattr(x, 'co_firstlineno'):
794
+ return x
795
+ return obj
796
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_code/source.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import generators
2
+
3
+ from bisect import bisect_right
4
+ import sys
5
+ import inspect, tokenize
6
+ import py
7
+ from types import ModuleType
8
+ cpy_compile = compile
9
+
10
+ try:
11
+ import _ast
12
+ from _ast import PyCF_ONLY_AST as _AST_FLAG
13
+ except ImportError:
14
+ _AST_FLAG = 0
15
+ _ast = None
16
+
17
+
18
+ class Source(object):
19
+ """ a immutable object holding a source code fragment,
20
+ possibly deindenting it.
21
+ """
22
+ _compilecounter = 0
23
+ def __init__(self, *parts, **kwargs):
24
+ self.lines = lines = []
25
+ de = kwargs.get('deindent', True)
26
+ rstrip = kwargs.get('rstrip', True)
27
+ for part in parts:
28
+ if not part:
29
+ partlines = []
30
+ if isinstance(part, Source):
31
+ partlines = part.lines
32
+ elif isinstance(part, (tuple, list)):
33
+ partlines = [x.rstrip("\n") for x in part]
34
+ elif isinstance(part, py.builtin._basestring):
35
+ partlines = part.split('\n')
36
+ if rstrip:
37
+ while partlines:
38
+ if partlines[-1].strip():
39
+ break
40
+ partlines.pop()
41
+ else:
42
+ partlines = getsource(part, deindent=de).lines
43
+ if de:
44
+ partlines = deindent(partlines)
45
+ lines.extend(partlines)
46
+
47
+ def __eq__(self, other):
48
+ try:
49
+ return self.lines == other.lines
50
+ except AttributeError:
51
+ if isinstance(other, str):
52
+ return str(self) == other
53
+ return False
54
+
55
+ def __getitem__(self, key):
56
+ if isinstance(key, int):
57
+ return self.lines[key]
58
+ else:
59
+ if key.step not in (None, 1):
60
+ raise IndexError("cannot slice a Source with a step")
61
+ return self.__getslice__(key.start, key.stop)
62
+
63
+ def __len__(self):
64
+ return len(self.lines)
65
+
66
+ def __getslice__(self, start, end):
67
+ newsource = Source()
68
+ newsource.lines = self.lines[start:end]
69
+ return newsource
70
+
71
+ def strip(self):
72
+ """ return new source object with trailing
73
+ and leading blank lines removed.
74
+ """
75
+ start, end = 0, len(self)
76
+ while start < end and not self.lines[start].strip():
77
+ start += 1
78
+ while end > start and not self.lines[end-1].strip():
79
+ end -= 1
80
+ source = Source()
81
+ source.lines[:] = self.lines[start:end]
82
+ return source
83
+
84
+ def putaround(self, before='', after='', indent=' ' * 4):
85
+ """ return a copy of the source object with
86
+ 'before' and 'after' wrapped around it.
87
+ """
88
+ before = Source(before)
89
+ after = Source(after)
90
+ newsource = Source()
91
+ lines = [ (indent + line) for line in self.lines]
92
+ newsource.lines = before.lines + lines + after.lines
93
+ return newsource
94
+
95
+ def indent(self, indent=' ' * 4):
96
+ """ return a copy of the source object with
97
+ all lines indented by the given indent-string.
98
+ """
99
+ newsource = Source()
100
+ newsource.lines = [(indent+line) for line in self.lines]
101
+ return newsource
102
+
103
+ def getstatement(self, lineno, assertion=False):
104
+ """ return Source statement which contains the
105
+ given linenumber (counted from 0).
106
+ """
107
+ start, end = self.getstatementrange(lineno, assertion)
108
+ return self[start:end]
109
+
110
+ def getstatementrange(self, lineno, assertion=False):
111
+ """ return (start, end) tuple which spans the minimal
112
+ statement region which containing the given lineno.
113
+ """
114
+ if not (0 <= lineno < len(self)):
115
+ raise IndexError("lineno out of range")
116
+ ast, start, end = getstatementrange_ast(lineno, self)
117
+ return start, end
118
+
119
+ def deindent(self, offset=None):
120
+ """ return a new source object deindented by offset.
121
+ If offset is None then guess an indentation offset from
122
+ the first non-blank line. Subsequent lines which have a
123
+ lower indentation offset will be copied verbatim as
124
+ they are assumed to be part of multilines.
125
+ """
126
+ # XXX maybe use the tokenizer to properly handle multiline
127
+ # strings etc.pp?
128
+ newsource = Source()
129
+ newsource.lines[:] = deindent(self.lines, offset)
130
+ return newsource
131
+
132
+ def isparseable(self, deindent=True):
133
+ """ return True if source is parseable, heuristically
134
+ deindenting it by default.
135
+ """
136
+ try:
137
+ import parser
138
+ except ImportError:
139
+ syntax_checker = lambda x: compile(x, 'asd', 'exec')
140
+ else:
141
+ syntax_checker = parser.suite
142
+
143
+ if deindent:
144
+ source = str(self.deindent())
145
+ else:
146
+ source = str(self)
147
+ try:
148
+ #compile(source+'\n', "x", "exec")
149
+ syntax_checker(source+'\n')
150
+ except KeyboardInterrupt:
151
+ raise
152
+ except Exception:
153
+ return False
154
+ else:
155
+ return True
156
+
157
+ def __str__(self):
158
+ return "\n".join(self.lines)
159
+
160
+ def compile(self, filename=None, mode='exec',
161
+ flag=generators.compiler_flag,
162
+ dont_inherit=0, _genframe=None):
163
+ """ return compiled code object. if filename is None
164
+ invent an artificial filename which displays
165
+ the source/line position of the caller frame.
166
+ """
167
+ if not filename or py.path.local(filename).check(file=0):
168
+ if _genframe is None:
169
+ _genframe = sys._getframe(1) # the caller
170
+ fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno
171
+ base = "<%d-codegen " % self._compilecounter
172
+ self.__class__._compilecounter += 1
173
+ if not filename:
174
+ filename = base + '%s:%d>' % (fn, lineno)
175
+ else:
176
+ filename = base + '%r %s:%d>' % (filename, fn, lineno)
177
+ source = "\n".join(self.lines) + '\n'
178
+ try:
179
+ co = cpy_compile(source, filename, mode, flag)
180
+ except SyntaxError:
181
+ ex = sys.exc_info()[1]
182
+ # re-represent syntax errors from parsing python strings
183
+ msglines = self.lines[:ex.lineno]
184
+ if ex.offset:
185
+ msglines.append(" "*ex.offset + '^')
186
+ msglines.append("(code was compiled probably from here: %s)" % filename)
187
+ newex = SyntaxError('\n'.join(msglines))
188
+ newex.offset = ex.offset
189
+ newex.lineno = ex.lineno
190
+ newex.text = ex.text
191
+ raise newex
192
+ else:
193
+ if flag & _AST_FLAG:
194
+ return co
195
+ lines = [(x + "\n") for x in self.lines]
196
+ import linecache
197
+ linecache.cache[filename] = (1, None, lines, filename)
198
+ return co
199
+
200
+ #
201
+ # public API shortcut functions
202
+ #
203
+
204
+ def compile_(source, filename=None, mode='exec', flags=
205
+ generators.compiler_flag, dont_inherit=0):
206
+ """ compile the given source to a raw code object,
207
+ and maintain an internal cache which allows later
208
+ retrieval of the source code for the code object
209
+ and any recursively created code objects.
210
+ """
211
+ if _ast is not None and isinstance(source, _ast.AST):
212
+ # XXX should Source support having AST?
213
+ return cpy_compile(source, filename, mode, flags, dont_inherit)
214
+ _genframe = sys._getframe(1) # the caller
215
+ s = Source(source)
216
+ co = s.compile(filename, mode, flags, _genframe=_genframe)
217
+ return co
218
+
219
+
220
+ def getfslineno(obj):
221
+ """ Return source location (path, lineno) for the given object.
222
+ If the source cannot be determined return ("", -1)
223
+ """
224
+ try:
225
+ code = py.code.Code(obj)
226
+ except TypeError:
227
+ try:
228
+ fn = (inspect.getsourcefile(obj) or
229
+ inspect.getfile(obj))
230
+ except TypeError:
231
+ return "", -1
232
+
233
+ fspath = fn and py.path.local(fn) or None
234
+ lineno = -1
235
+ if fspath:
236
+ try:
237
+ _, lineno = findsource(obj)
238
+ except IOError:
239
+ pass
240
+ else:
241
+ fspath = code.path
242
+ lineno = code.firstlineno
243
+ assert isinstance(lineno, int)
244
+ return fspath, lineno
245
+
246
+ #
247
+ # helper functions
248
+ #
249
+
250
+ def findsource(obj):
251
+ try:
252
+ sourcelines, lineno = inspect.findsource(obj)
253
+ except py.builtin._sysex:
254
+ raise
255
+ except:
256
+ return None, -1
257
+ source = Source()
258
+ source.lines = [line.rstrip() for line in sourcelines]
259
+ return source, lineno
260
+
261
+ def getsource(obj, **kwargs):
262
+ obj = py.code.getrawcode(obj)
263
+ try:
264
+ strsrc = inspect.getsource(obj)
265
+ except IndentationError:
266
+ strsrc = "\"Buggy python version consider upgrading, cannot get source\""
267
+ assert isinstance(strsrc, str)
268
+ return Source(strsrc, **kwargs)
269
+
270
+ def deindent(lines, offset=None):
271
+ if offset is None:
272
+ for line in lines:
273
+ line = line.expandtabs()
274
+ s = line.lstrip()
275
+ if s:
276
+ offset = len(line)-len(s)
277
+ break
278
+ else:
279
+ offset = 0
280
+ if offset == 0:
281
+ return list(lines)
282
+ newlines = []
283
+ def readline_generator(lines):
284
+ for line in lines:
285
+ yield line + '\n'
286
+ while True:
287
+ yield ''
288
+
289
+ it = readline_generator(lines)
290
+
291
+ try:
292
+ for _, _, (sline, _), (eline, _), _ in tokenize.generate_tokens(lambda: next(it)):
293
+ if sline > len(lines):
294
+ break # End of input reached
295
+ if sline > len(newlines):
296
+ line = lines[sline - 1].expandtabs()
297
+ if line.lstrip() and line[:offset].isspace():
298
+ line = line[offset:] # Deindent
299
+ newlines.append(line)
300
+
301
+ for i in range(sline, eline):
302
+ # Don't deindent continuing lines of
303
+ # multiline tokens (i.e. multiline strings)
304
+ newlines.append(lines[i])
305
+ except (IndentationError, tokenize.TokenError):
306
+ pass
307
+ # Add any lines we didn't see. E.g. if an exception was raised.
308
+ newlines.extend(lines[len(newlines):])
309
+ return newlines
310
+
311
+
312
+ def get_statement_startend2(lineno, node):
313
+ import ast
314
+ # flatten all statements and except handlers into one lineno-list
315
+ # AST's line numbers start indexing at 1
316
+ l = []
317
+ for x in ast.walk(node):
318
+ if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
319
+ l.append(x.lineno - 1)
320
+ for name in "finalbody", "orelse":
321
+ val = getattr(x, name, None)
322
+ if val:
323
+ # treat the finally/orelse part as its own statement
324
+ l.append(val[0].lineno - 1 - 1)
325
+ l.sort()
326
+ insert_index = bisect_right(l, lineno)
327
+ start = l[insert_index - 1]
328
+ if insert_index >= len(l):
329
+ end = None
330
+ else:
331
+ end = l[insert_index]
332
+ return start, end
333
+
334
+
335
+ def getstatementrange_ast(lineno, source, assertion=False, astnode=None):
336
+ if astnode is None:
337
+ content = str(source)
338
+ try:
339
+ astnode = compile(content, "source", "exec", 1024) # 1024 for AST
340
+ except ValueError:
341
+ start, end = getstatementrange_old(lineno, source, assertion)
342
+ return None, start, end
343
+ start, end = get_statement_startend2(lineno, astnode)
344
+ # we need to correct the end:
345
+ # - ast-parsing strips comments
346
+ # - there might be empty lines
347
+ # - we might have lesser indented code blocks at the end
348
+ if end is None:
349
+ end = len(source.lines)
350
+
351
+ if end > start + 1:
352
+ # make sure we don't span differently indented code blocks
353
+ # by using the BlockFinder helper used which inspect.getsource() uses itself
354
+ block_finder = inspect.BlockFinder()
355
+ # if we start with an indented line, put blockfinder to "started" mode
356
+ block_finder.started = source.lines[start][0].isspace()
357
+ it = ((x + "\n") for x in source.lines[start:end])
358
+ try:
359
+ for tok in tokenize.generate_tokens(lambda: next(it)):
360
+ block_finder.tokeneater(*tok)
361
+ except (inspect.EndOfBlock, IndentationError):
362
+ end = block_finder.last + start
363
+ except Exception:
364
+ pass
365
+
366
+ # the end might still point to a comment or empty line, correct it
367
+ while end:
368
+ line = source.lines[end - 1].lstrip()
369
+ if line.startswith("#") or not line:
370
+ end -= 1
371
+ else:
372
+ break
373
+ return astnode, start, end
374
+
375
+
376
+ def getstatementrange_old(lineno, source, assertion=False):
377
+ """ return (start, end) tuple which spans the minimal
378
+ statement region which containing the given lineno.
379
+ raise an IndexError if no such statementrange can be found.
380
+ """
381
+ # XXX this logic is only used on python2.4 and below
382
+ # 1. find the start of the statement
383
+ from codeop import compile_command
384
+ for start in range(lineno, -1, -1):
385
+ if assertion:
386
+ line = source.lines[start]
387
+ # the following lines are not fully tested, change with care
388
+ if 'super' in line and 'self' in line and '__init__' in line:
389
+ raise IndexError("likely a subclass")
390
+ if "assert" not in line and "raise" not in line:
391
+ continue
392
+ trylines = source.lines[start:lineno+1]
393
+ # quick hack to prepare parsing an indented line with
394
+ # compile_command() (which errors on "return" outside defs)
395
+ trylines.insert(0, 'def xxx():')
396
+ trysource = '\n '.join(trylines)
397
+ # ^ space here
398
+ try:
399
+ compile_command(trysource)
400
+ except (SyntaxError, OverflowError, ValueError):
401
+ continue
402
+
403
+ # 2. find the end of the statement
404
+ for end in range(lineno+1, len(source)+1):
405
+ trysource = source[start:end]
406
+ if trysource.isparseable():
407
+ return start, end
408
+ raise SyntaxError("no valid source range around line %d " % (lineno,))
409
+
410
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """ input/output helping """
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/capture.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import py
4
+ import tempfile
5
+
6
+ try:
7
+ from io import StringIO
8
+ except ImportError:
9
+ from StringIO import StringIO
10
+
11
+ if sys.version_info < (3,0):
12
+ class TextIO(StringIO):
13
+ def write(self, data):
14
+ if not isinstance(data, unicode):
15
+ data = unicode(data, getattr(self, '_encoding', 'UTF-8'), 'replace')
16
+ StringIO.write(self, data)
17
+ else:
18
+ TextIO = StringIO
19
+
20
+ try:
21
+ from io import BytesIO
22
+ except ImportError:
23
+ class BytesIO(StringIO):
24
+ def write(self, data):
25
+ if isinstance(data, unicode):
26
+ raise TypeError("not a byte value: %r" %(data,))
27
+ StringIO.write(self, data)
28
+
29
+ patchsysdict = {0: 'stdin', 1: 'stdout', 2: 'stderr'}
30
+
31
+ class FDCapture:
32
+ """ Capture IO to/from a given os-level filedescriptor. """
33
+
34
+ def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False):
35
+ """ save targetfd descriptor, and open a new
36
+ temporary file there. If no tmpfile is
37
+ specified a tempfile.Tempfile() will be opened
38
+ in text mode.
39
+ """
40
+ self.targetfd = targetfd
41
+ if tmpfile is None and targetfd != 0:
42
+ f = tempfile.TemporaryFile('wb+')
43
+ tmpfile = dupfile(f, encoding="UTF-8")
44
+ f.close()
45
+ self.tmpfile = tmpfile
46
+ self._savefd = os.dup(self.targetfd)
47
+ if patchsys:
48
+ self._oldsys = getattr(sys, patchsysdict[targetfd])
49
+ if now:
50
+ self.start()
51
+
52
+ def start(self):
53
+ try:
54
+ os.fstat(self._savefd)
55
+ except OSError:
56
+ raise ValueError("saved filedescriptor not valid, "
57
+ "did you call start() twice?")
58
+ if self.targetfd == 0 and not self.tmpfile:
59
+ fd = os.open(devnullpath, os.O_RDONLY)
60
+ os.dup2(fd, 0)
61
+ os.close(fd)
62
+ if hasattr(self, '_oldsys'):
63
+ setattr(sys, patchsysdict[self.targetfd], DontReadFromInput())
64
+ else:
65
+ os.dup2(self.tmpfile.fileno(), self.targetfd)
66
+ if hasattr(self, '_oldsys'):
67
+ setattr(sys, patchsysdict[self.targetfd], self.tmpfile)
68
+
69
+ def done(self):
70
+ """ unpatch and clean up, returns the self.tmpfile (file object)
71
+ """
72
+ os.dup2(self._savefd, self.targetfd)
73
+ os.close(self._savefd)
74
+ if self.targetfd != 0:
75
+ self.tmpfile.seek(0)
76
+ if hasattr(self, '_oldsys'):
77
+ setattr(sys, patchsysdict[self.targetfd], self._oldsys)
78
+ return self.tmpfile
79
+
80
+ def writeorg(self, data):
81
+ """ write a string to the original file descriptor
82
+ """
83
+ tempfp = tempfile.TemporaryFile()
84
+ try:
85
+ os.dup2(self._savefd, tempfp.fileno())
86
+ tempfp.write(data)
87
+ finally:
88
+ tempfp.close()
89
+
90
+
91
+ def dupfile(f, mode=None, buffering=0, raising=False, encoding=None):
92
+ """ return a new open file object that's a duplicate of f
93
+
94
+ mode is duplicated if not given, 'buffering' controls
95
+ buffer size (defaulting to no buffering) and 'raising'
96
+ defines whether an exception is raised when an incompatible
97
+ file object is passed in (if raising is False, the file
98
+ object itself will be returned)
99
+ """
100
+ try:
101
+ fd = f.fileno()
102
+ mode = mode or f.mode
103
+ except AttributeError:
104
+ if raising:
105
+ raise
106
+ return f
107
+ newfd = os.dup(fd)
108
+ if sys.version_info >= (3,0):
109
+ if encoding is not None:
110
+ mode = mode.replace("b", "")
111
+ buffering = True
112
+ return os.fdopen(newfd, mode, buffering, encoding, closefd=True)
113
+ else:
114
+ f = os.fdopen(newfd, mode, buffering)
115
+ if encoding is not None:
116
+ return EncodedFile(f, encoding)
117
+ return f
118
+
119
+ class EncodedFile(object):
120
+ def __init__(self, _stream, encoding):
121
+ self._stream = _stream
122
+ self.encoding = encoding
123
+
124
+ def write(self, obj):
125
+ if isinstance(obj, unicode):
126
+ obj = obj.encode(self.encoding)
127
+ elif isinstance(obj, str):
128
+ pass
129
+ else:
130
+ obj = str(obj)
131
+ self._stream.write(obj)
132
+
133
+ def writelines(self, linelist):
134
+ data = ''.join(linelist)
135
+ self.write(data)
136
+
137
+ def __getattr__(self, name):
138
+ return getattr(self._stream, name)
139
+
140
+ class Capture(object):
141
+ def call(cls, func, *args, **kwargs):
142
+ """ return a (res, out, err) tuple where
143
+ out and err represent the output/error output
144
+ during function execution.
145
+ call the given function with args/kwargs
146
+ and capture output/error during its execution.
147
+ """
148
+ so = cls()
149
+ try:
150
+ res = func(*args, **kwargs)
151
+ finally:
152
+ out, err = so.reset()
153
+ return res, out, err
154
+ call = classmethod(call)
155
+
156
+ def reset(self):
157
+ """ reset sys.stdout/stderr and return captured output as strings. """
158
+ if hasattr(self, '_reset'):
159
+ raise ValueError("was already reset")
160
+ self._reset = True
161
+ outfile, errfile = self.done(save=False)
162
+ out, err = "", ""
163
+ if outfile and not outfile.closed:
164
+ out = outfile.read()
165
+ outfile.close()
166
+ if errfile and errfile != outfile and not errfile.closed:
167
+ err = errfile.read()
168
+ errfile.close()
169
+ return out, err
170
+
171
+ def suspend(self):
172
+ """ return current snapshot captures, memorize tempfiles. """
173
+ outerr = self.readouterr()
174
+ outfile, errfile = self.done()
175
+ return outerr
176
+
177
+
178
+ class StdCaptureFD(Capture):
179
+ """ This class allows to capture writes to FD1 and FD2
180
+ and may connect a NULL file to FD0 (and prevent
181
+ reads from sys.stdin). If any of the 0,1,2 file descriptors
182
+ is invalid it will not be captured.
183
+ """
184
+ def __init__(self, out=True, err=True, mixed=False,
185
+ in_=True, patchsys=True, now=True):
186
+ self._options = {
187
+ "out": out,
188
+ "err": err,
189
+ "mixed": mixed,
190
+ "in_": in_,
191
+ "patchsys": patchsys,
192
+ "now": now,
193
+ }
194
+ self._save()
195
+ if now:
196
+ self.startall()
197
+
198
+ def _save(self):
199
+ in_ = self._options['in_']
200
+ out = self._options['out']
201
+ err = self._options['err']
202
+ mixed = self._options['mixed']
203
+ patchsys = self._options['patchsys']
204
+ if in_:
205
+ try:
206
+ self.in_ = FDCapture(0, tmpfile=None, now=False,
207
+ patchsys=patchsys)
208
+ except OSError:
209
+ pass
210
+ if out:
211
+ tmpfile = None
212
+ if hasattr(out, 'write'):
213
+ tmpfile = out
214
+ try:
215
+ self.out = FDCapture(1, tmpfile=tmpfile,
216
+ now=False, patchsys=patchsys)
217
+ self._options['out'] = self.out.tmpfile
218
+ except OSError:
219
+ pass
220
+ if err:
221
+ if out and mixed:
222
+ tmpfile = self.out.tmpfile
223
+ elif hasattr(err, 'write'):
224
+ tmpfile = err
225
+ else:
226
+ tmpfile = None
227
+ try:
228
+ self.err = FDCapture(2, tmpfile=tmpfile,
229
+ now=False, patchsys=patchsys)
230
+ self._options['err'] = self.err.tmpfile
231
+ except OSError:
232
+ pass
233
+
234
+ def startall(self):
235
+ if hasattr(self, 'in_'):
236
+ self.in_.start()
237
+ if hasattr(self, 'out'):
238
+ self.out.start()
239
+ if hasattr(self, 'err'):
240
+ self.err.start()
241
+
242
+ def resume(self):
243
+ """ resume capturing with original temp files. """
244
+ self.startall()
245
+
246
+ def done(self, save=True):
247
+ """ return (outfile, errfile) and stop capturing. """
248
+ outfile = errfile = None
249
+ if hasattr(self, 'out') and not self.out.tmpfile.closed:
250
+ outfile = self.out.done()
251
+ if hasattr(self, 'err') and not self.err.tmpfile.closed:
252
+ errfile = self.err.done()
253
+ if hasattr(self, 'in_'):
254
+ tmpfile = self.in_.done()
255
+ if save:
256
+ self._save()
257
+ return outfile, errfile
258
+
259
+ def readouterr(self):
260
+ """ return snapshot value of stdout/stderr capturings. """
261
+ if hasattr(self, "out"):
262
+ out = self._readsnapshot(self.out.tmpfile)
263
+ else:
264
+ out = ""
265
+ if hasattr(self, "err"):
266
+ err = self._readsnapshot(self.err.tmpfile)
267
+ else:
268
+ err = ""
269
+ return [out, err]
270
+
271
+ def _readsnapshot(self, f):
272
+ f.seek(0)
273
+ res = f.read()
274
+ enc = getattr(f, "encoding", None)
275
+ if enc:
276
+ res = py.builtin._totext(res, enc, "replace")
277
+ f.truncate(0)
278
+ f.seek(0)
279
+ return res
280
+
281
+
282
+ class StdCapture(Capture):
283
+ """ This class allows to capture writes to sys.stdout|stderr "in-memory"
284
+ and will raise errors on tries to read from sys.stdin. It only
285
+ modifies sys.stdout|stderr|stdin attributes and does not
286
+ touch underlying File Descriptors (use StdCaptureFD for that).
287
+ """
288
+ def __init__(self, out=True, err=True, in_=True, mixed=False, now=True):
289
+ self._oldout = sys.stdout
290
+ self._olderr = sys.stderr
291
+ self._oldin = sys.stdin
292
+ if out and not hasattr(out, 'file'):
293
+ out = TextIO()
294
+ self.out = out
295
+ if err:
296
+ if mixed:
297
+ err = out
298
+ elif not hasattr(err, 'write'):
299
+ err = TextIO()
300
+ self.err = err
301
+ self.in_ = in_
302
+ if now:
303
+ self.startall()
304
+
305
+ def startall(self):
306
+ if self.out:
307
+ sys.stdout = self.out
308
+ if self.err:
309
+ sys.stderr = self.err
310
+ if self.in_:
311
+ sys.stdin = self.in_ = DontReadFromInput()
312
+
313
+ def done(self, save=True):
314
+ """ return (outfile, errfile) and stop capturing. """
315
+ outfile = errfile = None
316
+ if self.out and not self.out.closed:
317
+ sys.stdout = self._oldout
318
+ outfile = self.out
319
+ outfile.seek(0)
320
+ if self.err and not self.err.closed:
321
+ sys.stderr = self._olderr
322
+ errfile = self.err
323
+ errfile.seek(0)
324
+ if self.in_:
325
+ sys.stdin = self._oldin
326
+ return outfile, errfile
327
+
328
+ def resume(self):
329
+ """ resume capturing with original temp files. """
330
+ self.startall()
331
+
332
+ def readouterr(self):
333
+ """ return snapshot value of stdout/stderr capturings. """
334
+ out = err = ""
335
+ if self.out:
336
+ out = self.out.getvalue()
337
+ self.out.truncate(0)
338
+ self.out.seek(0)
339
+ if self.err:
340
+ err = self.err.getvalue()
341
+ self.err.truncate(0)
342
+ self.err.seek(0)
343
+ return out, err
344
+
345
+ class DontReadFromInput:
346
+ """Temporary stub class. Ideally when stdin is accessed, the
347
+ capturing should be turned off, with possibly all data captured
348
+ so far sent to the screen. This should be configurable, though,
349
+ because in automated test runs it is better to crash than
350
+ hang indefinitely.
351
+ """
352
+ def read(self, *args):
353
+ raise IOError("reading from stdin while output is captured")
354
+ readline = read
355
+ readlines = read
356
+ __iter__ = read
357
+
358
+ def fileno(self):
359
+ raise ValueError("redirected Stdin is pseudofile, has no fileno()")
360
+ def isatty(self):
361
+ return False
362
+ def close(self):
363
+ pass
364
+
365
+ try:
366
+ devnullpath = os.devnull
367
+ except AttributeError:
368
+ if os.name == 'nt':
369
+ devnullpath = 'NUL'
370
+ else:
371
+ devnullpath = '/dev/null'
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/saferepr.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import py
2
+ import sys
3
+
4
+ builtin_repr = repr
5
+
6
+ reprlib = py.builtin._tryimport('repr', 'reprlib')
7
+
8
+ class SafeRepr(reprlib.Repr):
9
+ """ subclass of repr.Repr that limits the resulting size of repr()
10
+ and includes information on exceptions raised during the call.
11
+ """
12
+ def repr(self, x):
13
+ return self._callhelper(reprlib.Repr.repr, self, x)
14
+
15
+ def repr_unicode(self, x, level):
16
+ # Strictly speaking wrong on narrow builds
17
+ def repr(u):
18
+ if "'" not in u:
19
+ return py.builtin._totext("'%s'") % u
20
+ elif '"' not in u:
21
+ return py.builtin._totext('"%s"') % u
22
+ else:
23
+ return py.builtin._totext("'%s'") % u.replace("'", r"\'")
24
+ s = repr(x[:self.maxstring])
25
+ if len(s) > self.maxstring:
26
+ i = max(0, (self.maxstring-3)//2)
27
+ j = max(0, self.maxstring-3-i)
28
+ s = repr(x[:i] + x[len(x)-j:])
29
+ s = s[:i] + '...' + s[len(s)-j:]
30
+ return s
31
+
32
+ def repr_instance(self, x, level):
33
+ return self._callhelper(builtin_repr, x)
34
+
35
+ def _callhelper(self, call, x, *args):
36
+ try:
37
+ # Try the vanilla repr and make sure that the result is a string
38
+ s = call(x, *args)
39
+ except py.builtin._sysex:
40
+ raise
41
+ except:
42
+ cls, e, tb = sys.exc_info()
43
+ exc_name = getattr(cls, '__name__', 'unknown')
44
+ try:
45
+ exc_info = str(e)
46
+ except py.builtin._sysex:
47
+ raise
48
+ except:
49
+ exc_info = 'unknown'
50
+ return '<[%s("%s") raised in repr()] %s object at 0x%x>' % (
51
+ exc_name, exc_info, x.__class__.__name__, id(x))
52
+ else:
53
+ if len(s) > self.maxsize:
54
+ i = max(0, (self.maxsize-3)//2)
55
+ j = max(0, self.maxsize-3-i)
56
+ s = s[:i] + '...' + s[len(s)-j:]
57
+ return s
58
+
59
+ def saferepr(obj, maxsize=240):
60
+ """ return a size-limited safe repr-string for the given object.
61
+ Failing __repr__ functions of user instances will be represented
62
+ with a short exception info and 'saferepr' generally takes
63
+ care to never raise exceptions itself. This function is a wrapper
64
+ around the Repr/reprlib functionality of the standard 2.6 lib.
65
+ """
66
+ # review exception handling
67
+ srepr = SafeRepr()
68
+ srepr.maxstring = maxsize
69
+ srepr.maxsize = maxsize
70
+ srepr.maxother = 160
71
+ return srepr.repr(obj)
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_io/terminalwriter.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Helper functions for writing to terminals and files.
4
+
5
+ """
6
+
7
+
8
+ import sys, os, unicodedata
9
+ import py
10
+ py3k = sys.version_info[0] >= 3
11
+ py33 = sys.version_info >= (3, 3)
12
+ from py.builtin import text, bytes
13
+
14
+ win32_and_ctypes = False
15
+ colorama = None
16
+ if sys.platform == "win32":
17
+ try:
18
+ import colorama
19
+ except ImportError:
20
+ try:
21
+ import ctypes
22
+ win32_and_ctypes = True
23
+ except ImportError:
24
+ pass
25
+
26
+
27
+ def _getdimensions():
28
+ if py33:
29
+ import shutil
30
+ size = shutil.get_terminal_size()
31
+ return size.lines, size.columns
32
+ else:
33
+ import termios, fcntl, struct
34
+ call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8)
35
+ height, width = struct.unpack("hhhh", call)[:2]
36
+ return height, width
37
+
38
+
39
+ def get_terminal_width():
40
+ width = 0
41
+ try:
42
+ _, width = _getdimensions()
43
+ except py.builtin._sysex:
44
+ raise
45
+ except:
46
+ # pass to fallback below
47
+ pass
48
+
49
+ if width == 0:
50
+ # FALLBACK:
51
+ # * some exception happened
52
+ # * or this is emacs terminal which reports (0,0)
53
+ width = int(os.environ.get('COLUMNS', 80))
54
+
55
+ # XXX the windows getdimensions may be bogus, let's sanify a bit
56
+ if width < 40:
57
+ width = 80
58
+ return width
59
+
60
+ terminal_width = get_terminal_width()
61
+
62
+ char_width = {
63
+ 'A': 1, # "Ambiguous"
64
+ 'F': 2, # Fullwidth
65
+ 'H': 1, # Halfwidth
66
+ 'N': 1, # Neutral
67
+ 'Na': 1, # Narrow
68
+ 'W': 2, # Wide
69
+ }
70
+
71
+
72
+ def get_line_width(text):
73
+ text = unicodedata.normalize('NFC', text)
74
+ return sum(char_width.get(unicodedata.east_asian_width(c), 1) for c in text)
75
+
76
+
77
+ # XXX unify with _escaped func below
78
+ def ansi_print(text, esc, file=None, newline=True, flush=False):
79
+ if file is None:
80
+ file = sys.stderr
81
+ text = text.rstrip()
82
+ if esc and not isinstance(esc, tuple):
83
+ esc = (esc,)
84
+ if esc and sys.platform != "win32" and file.isatty():
85
+ text = (''.join(['\x1b[%sm' % cod for cod in esc]) +
86
+ text +
87
+ '\x1b[0m') # ANSI color code "reset"
88
+ if newline:
89
+ text += '\n'
90
+
91
+ if esc and win32_and_ctypes and file.isatty():
92
+ if 1 in esc:
93
+ bold = True
94
+ esc = tuple([x for x in esc if x != 1])
95
+ else:
96
+ bold = False
97
+ esctable = {() : FOREGROUND_WHITE, # normal
98
+ (31,): FOREGROUND_RED, # red
99
+ (32,): FOREGROUND_GREEN, # green
100
+ (33,): FOREGROUND_GREEN|FOREGROUND_RED, # yellow
101
+ (34,): FOREGROUND_BLUE, # blue
102
+ (35,): FOREGROUND_BLUE|FOREGROUND_RED, # purple
103
+ (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan
104
+ (37,): FOREGROUND_WHITE, # white
105
+ (39,): FOREGROUND_WHITE, # reset
106
+ }
107
+ attr = esctable.get(esc, FOREGROUND_WHITE)
108
+ if bold:
109
+ attr |= FOREGROUND_INTENSITY
110
+ STD_OUTPUT_HANDLE = -11
111
+ STD_ERROR_HANDLE = -12
112
+ if file is sys.stderr:
113
+ handle = GetStdHandle(STD_ERROR_HANDLE)
114
+ else:
115
+ handle = GetStdHandle(STD_OUTPUT_HANDLE)
116
+ oldcolors = GetConsoleInfo(handle).wAttributes
117
+ attr |= (oldcolors & 0x0f0)
118
+ SetConsoleTextAttribute(handle, attr)
119
+ while len(text) > 32768:
120
+ file.write(text[:32768])
121
+ text = text[32768:]
122
+ if text:
123
+ file.write(text)
124
+ SetConsoleTextAttribute(handle, oldcolors)
125
+ else:
126
+ file.write(text)
127
+
128
+ if flush:
129
+ file.flush()
130
+
131
+ def should_do_markup(file):
132
+ if os.environ.get('PY_COLORS') == '1':
133
+ return True
134
+ if os.environ.get('PY_COLORS') == '0':
135
+ return False
136
+ return hasattr(file, 'isatty') and file.isatty() \
137
+ and os.environ.get('TERM') != 'dumb' \
138
+ and not (sys.platform.startswith('java') and os._name == 'nt')
139
+
140
+ class TerminalWriter(object):
141
+ _esctable = dict(black=30, red=31, green=32, yellow=33,
142
+ blue=34, purple=35, cyan=36, white=37,
143
+ Black=40, Red=41, Green=42, Yellow=43,
144
+ Blue=44, Purple=45, Cyan=46, White=47,
145
+ bold=1, light=2, blink=5, invert=7)
146
+
147
+ # XXX deprecate stringio argument
148
+ def __init__(self, file=None, stringio=False, encoding=None):
149
+ if file is None:
150
+ if stringio:
151
+ self.stringio = file = py.io.TextIO()
152
+ else:
153
+ from sys import stdout as file
154
+ elif py.builtin.callable(file) and not (
155
+ hasattr(file, "write") and hasattr(file, "flush")):
156
+ file = WriteFile(file, encoding=encoding)
157
+ if hasattr(file, "isatty") and file.isatty() and colorama:
158
+ file = colorama.AnsiToWin32(file).stream
159
+ self.encoding = encoding or getattr(file, 'encoding', "utf-8")
160
+ self._file = file
161
+ self.hasmarkup = should_do_markup(file)
162
+ self._lastlen = 0
163
+ self._chars_on_current_line = 0
164
+ self._width_of_current_line = 0
165
+
166
+ @property
167
+ def fullwidth(self):
168
+ if hasattr(self, '_terminal_width'):
169
+ return self._terminal_width
170
+ return get_terminal_width()
171
+
172
+ @fullwidth.setter
173
+ def fullwidth(self, value):
174
+ self._terminal_width = value
175
+
176
+ @property
177
+ def chars_on_current_line(self):
178
+ """Return the number of characters written so far in the current line.
179
+
180
+ Please note that this count does not produce correct results after a reline() call,
181
+ see #164.
182
+
183
+ .. versionadded:: 1.5.0
184
+
185
+ :rtype: int
186
+ """
187
+ return self._chars_on_current_line
188
+
189
+ @property
190
+ def width_of_current_line(self):
191
+ """Return an estimate of the width so far in the current line.
192
+
193
+ .. versionadded:: 1.6.0
194
+
195
+ :rtype: int
196
+ """
197
+ return self._width_of_current_line
198
+
199
+ def _escaped(self, text, esc):
200
+ if esc and self.hasmarkup:
201
+ text = (''.join(['\x1b[%sm' % cod for cod in esc]) +
202
+ text +'\x1b[0m')
203
+ return text
204
+
205
+ def markup(self, text, **kw):
206
+ esc = []
207
+ for name in kw:
208
+ if name not in self._esctable:
209
+ raise ValueError("unknown markup: %r" %(name,))
210
+ if kw[name]:
211
+ esc.append(self._esctable[name])
212
+ return self._escaped(text, tuple(esc))
213
+
214
+ def sep(self, sepchar, title=None, fullwidth=None, **kw):
215
+ if fullwidth is None:
216
+ fullwidth = self.fullwidth
217
+ # the goal is to have the line be as long as possible
218
+ # under the condition that len(line) <= fullwidth
219
+ if sys.platform == "win32":
220
+ # if we print in the last column on windows we are on a
221
+ # new line but there is no way to verify/neutralize this
222
+ # (we may not know the exact line width)
223
+ # so let's be defensive to avoid empty lines in the output
224
+ fullwidth -= 1
225
+ if title is not None:
226
+ # we want 2 + 2*len(fill) + len(title) <= fullwidth
227
+ # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth
228
+ # 2*len(sepchar)*N <= fullwidth - len(title) - 2
229
+ # N <= (fullwidth - len(title) - 2) // (2*len(sepchar))
230
+ N = max((fullwidth - len(title) - 2) // (2*len(sepchar)), 1)
231
+ fill = sepchar * N
232
+ line = "%s %s %s" % (fill, title, fill)
233
+ else:
234
+ # we want len(sepchar)*N <= fullwidth
235
+ # i.e. N <= fullwidth // len(sepchar)
236
+ line = sepchar * (fullwidth // len(sepchar))
237
+ # in some situations there is room for an extra sepchar at the right,
238
+ # in particular if we consider that with a sepchar like "_ " the
239
+ # trailing space is not important at the end of the line
240
+ if len(line) + len(sepchar.rstrip()) <= fullwidth:
241
+ line += sepchar.rstrip()
242
+
243
+ self.line(line, **kw)
244
+
245
+ def write(self, msg, **kw):
246
+ if msg:
247
+ if not isinstance(msg, (bytes, text)):
248
+ msg = text(msg)
249
+
250
+ self._update_chars_on_current_line(msg)
251
+
252
+ if self.hasmarkup and kw:
253
+ markupmsg = self.markup(msg, **kw)
254
+ else:
255
+ markupmsg = msg
256
+ write_out(self._file, markupmsg)
257
+
258
+ def _update_chars_on_current_line(self, text_or_bytes):
259
+ newline = b'\n' if isinstance(text_or_bytes, bytes) else '\n'
260
+ current_line = text_or_bytes.rsplit(newline, 1)[-1]
261
+ if isinstance(current_line, bytes):
262
+ current_line = current_line.decode('utf-8', errors='replace')
263
+ if newline in text_or_bytes:
264
+ self._chars_on_current_line = len(current_line)
265
+ self._width_of_current_line = get_line_width(current_line)
266
+ else:
267
+ self._chars_on_current_line += len(current_line)
268
+ self._width_of_current_line += get_line_width(current_line)
269
+
270
+ def line(self, s='', **kw):
271
+ self.write(s, **kw)
272
+ self._checkfill(s)
273
+ self.write('\n')
274
+
275
+ def reline(self, line, **kw):
276
+ if not self.hasmarkup:
277
+ raise ValueError("cannot use rewrite-line without terminal")
278
+ self.write(line, **kw)
279
+ self._checkfill(line)
280
+ self.write('\r')
281
+ self._lastlen = len(line)
282
+
283
+ def _checkfill(self, line):
284
+ diff2last = self._lastlen - len(line)
285
+ if diff2last > 0:
286
+ self.write(" " * diff2last)
287
+
288
+ class Win32ConsoleWriter(TerminalWriter):
289
+ def write(self, msg, **kw):
290
+ if msg:
291
+ if not isinstance(msg, (bytes, text)):
292
+ msg = text(msg)
293
+
294
+ self._update_chars_on_current_line(msg)
295
+
296
+ oldcolors = None
297
+ if self.hasmarkup and kw:
298
+ handle = GetStdHandle(STD_OUTPUT_HANDLE)
299
+ oldcolors = GetConsoleInfo(handle).wAttributes
300
+ default_bg = oldcolors & 0x00F0
301
+ attr = default_bg
302
+ if kw.pop('bold', False):
303
+ attr |= FOREGROUND_INTENSITY
304
+
305
+ if kw.pop('red', False):
306
+ attr |= FOREGROUND_RED
307
+ elif kw.pop('blue', False):
308
+ attr |= FOREGROUND_BLUE
309
+ elif kw.pop('green', False):
310
+ attr |= FOREGROUND_GREEN
311
+ elif kw.pop('yellow', False):
312
+ attr |= FOREGROUND_GREEN|FOREGROUND_RED
313
+ else:
314
+ attr |= oldcolors & 0x0007
315
+
316
+ SetConsoleTextAttribute(handle, attr)
317
+ write_out(self._file, msg)
318
+ if oldcolors:
319
+ SetConsoleTextAttribute(handle, oldcolors)
320
+
321
+ class WriteFile(object):
322
+ def __init__(self, writemethod, encoding=None):
323
+ self.encoding = encoding
324
+ self._writemethod = writemethod
325
+
326
+ def write(self, data):
327
+ if self.encoding:
328
+ data = data.encode(self.encoding, "replace")
329
+ self._writemethod(data)
330
+
331
+ def flush(self):
332
+ return
333
+
334
+
335
+ if win32_and_ctypes:
336
+ TerminalWriter = Win32ConsoleWriter
337
+ import ctypes
338
+ from ctypes import wintypes
339
+
340
+ # ctypes access to the Windows console
341
+ STD_OUTPUT_HANDLE = -11
342
+ STD_ERROR_HANDLE = -12
343
+ FOREGROUND_BLACK = 0x0000 # black text
344
+ FOREGROUND_BLUE = 0x0001 # text color contains blue.
345
+ FOREGROUND_GREEN = 0x0002 # text color contains green.
346
+ FOREGROUND_RED = 0x0004 # text color contains red.
347
+ FOREGROUND_WHITE = 0x0007
348
+ FOREGROUND_INTENSITY = 0x0008 # text color is intensified.
349
+ BACKGROUND_BLACK = 0x0000 # background color black
350
+ BACKGROUND_BLUE = 0x0010 # background color contains blue.
351
+ BACKGROUND_GREEN = 0x0020 # background color contains green.
352
+ BACKGROUND_RED = 0x0040 # background color contains red.
353
+ BACKGROUND_WHITE = 0x0070
354
+ BACKGROUND_INTENSITY = 0x0080 # background color is intensified.
355
+
356
+ SHORT = ctypes.c_short
357
+ class COORD(ctypes.Structure):
358
+ _fields_ = [('X', SHORT),
359
+ ('Y', SHORT)]
360
+ class SMALL_RECT(ctypes.Structure):
361
+ _fields_ = [('Left', SHORT),
362
+ ('Top', SHORT),
363
+ ('Right', SHORT),
364
+ ('Bottom', SHORT)]
365
+ class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
366
+ _fields_ = [('dwSize', COORD),
367
+ ('dwCursorPosition', COORD),
368
+ ('wAttributes', wintypes.WORD),
369
+ ('srWindow', SMALL_RECT),
370
+ ('dwMaximumWindowSize', COORD)]
371
+
372
+ _GetStdHandle = ctypes.windll.kernel32.GetStdHandle
373
+ _GetStdHandle.argtypes = [wintypes.DWORD]
374
+ _GetStdHandle.restype = wintypes.HANDLE
375
+ def GetStdHandle(kind):
376
+ return _GetStdHandle(kind)
377
+
378
+ SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
379
+ SetConsoleTextAttribute.argtypes = [wintypes.HANDLE, wintypes.WORD]
380
+ SetConsoleTextAttribute.restype = wintypes.BOOL
381
+
382
+ _GetConsoleScreenBufferInfo = \
383
+ ctypes.windll.kernel32.GetConsoleScreenBufferInfo
384
+ _GetConsoleScreenBufferInfo.argtypes = [wintypes.HANDLE,
385
+ ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO)]
386
+ _GetConsoleScreenBufferInfo.restype = wintypes.BOOL
387
+ def GetConsoleInfo(handle):
388
+ info = CONSOLE_SCREEN_BUFFER_INFO()
389
+ _GetConsoleScreenBufferInfo(handle, ctypes.byref(info))
390
+ return info
391
+
392
+ def _getdimensions():
393
+ handle = GetStdHandle(STD_OUTPUT_HANDLE)
394
+ info = GetConsoleInfo(handle)
395
+ # Substract one from the width, otherwise the cursor wraps
396
+ # and the ending \n causes an empty line to display.
397
+ return info.dwSize.Y, info.dwSize.X - 1
398
+
399
+ def write_out(fil, msg):
400
+ # XXX sometimes "msg" is of type bytes, sometimes text which
401
+ # complicates the situation. Should we try to enforce unicode?
402
+ try:
403
+ # on py27 and above writing out to sys.stdout with an encoding
404
+ # should usually work for unicode messages (if the encoding is
405
+ # capable of it)
406
+ fil.write(msg)
407
+ except UnicodeEncodeError:
408
+ # on py26 it might not work because stdout expects bytes
409
+ if fil.encoding:
410
+ try:
411
+ fil.write(msg.encode(fil.encoding))
412
+ except UnicodeEncodeError:
413
+ # it might still fail if the encoding is not capable
414
+ pass
415
+ else:
416
+ fil.flush()
417
+ return
418
+ # fallback: escape all unicode characters
419
+ msg = msg.encode("unicode-escape").decode("ascii")
420
+ fil.write(msg)
421
+ fil.flush()
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """ logging API ('producers' and 'consumers' connected via keywords) """
2
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/log.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ basic logging functionality based on a producer/consumer scheme.
3
+
4
+ XXX implement this API: (maybe put it into slogger.py?)
5
+
6
+ log = Logger(
7
+ info=py.log.STDOUT,
8
+ debug=py.log.STDOUT,
9
+ command=None)
10
+ log.info("hello", "world")
11
+ log.command("hello", "world")
12
+
13
+ log = Logger(info=Logger(something=...),
14
+ debug=py.log.STDOUT,
15
+ command=None)
16
+ """
17
+ import py
18
+ import sys
19
+
20
+
21
+ class Message(object):
22
+ def __init__(self, keywords, args):
23
+ self.keywords = keywords
24
+ self.args = args
25
+
26
+ def content(self):
27
+ return " ".join(map(str, self.args))
28
+
29
+ def prefix(self):
30
+ return "[%s] " % (":".join(self.keywords))
31
+
32
+ def __str__(self):
33
+ return self.prefix() + self.content()
34
+
35
+
36
+ class Producer(object):
37
+ """ (deprecated) Log producer API which sends messages to be logged
38
+ to a 'consumer' object, which then prints them to stdout,
39
+ stderr, files, etc. Used extensively by PyPy-1.1.
40
+ """
41
+
42
+ Message = Message # to allow later customization
43
+ keywords2consumer = {}
44
+
45
+ def __init__(self, keywords, keywordmapper=None, **kw):
46
+ if hasattr(keywords, 'split'):
47
+ keywords = tuple(keywords.split())
48
+ self._keywords = keywords
49
+ if keywordmapper is None:
50
+ keywordmapper = default_keywordmapper
51
+ self._keywordmapper = keywordmapper
52
+
53
+ def __repr__(self):
54
+ return "<py.log.Producer %s>" % ":".join(self._keywords)
55
+
56
+ def __getattr__(self, name):
57
+ if '_' in name:
58
+ raise AttributeError(name)
59
+ producer = self.__class__(self._keywords + (name,))
60
+ setattr(self, name, producer)
61
+ return producer
62
+
63
+ def __call__(self, *args):
64
+ """ write a message to the appropriate consumer(s) """
65
+ func = self._keywordmapper.getconsumer(self._keywords)
66
+ if func is not None:
67
+ func(self.Message(self._keywords, args))
68
+
69
+ class KeywordMapper:
70
+ def __init__(self):
71
+ self.keywords2consumer = {}
72
+
73
+ def getstate(self):
74
+ return self.keywords2consumer.copy()
75
+
76
+ def setstate(self, state):
77
+ self.keywords2consumer.clear()
78
+ self.keywords2consumer.update(state)
79
+
80
+ def getconsumer(self, keywords):
81
+ """ return a consumer matching the given keywords.
82
+
83
+ tries to find the most suitable consumer by walking, starting from
84
+ the back, the list of keywords, the first consumer matching a
85
+ keyword is returned (falling back to py.log.default)
86
+ """
87
+ for i in range(len(keywords), 0, -1):
88
+ try:
89
+ return self.keywords2consumer[keywords[:i]]
90
+ except KeyError:
91
+ continue
92
+ return self.keywords2consumer.get('default', default_consumer)
93
+
94
+ def setconsumer(self, keywords, consumer):
95
+ """ set a consumer for a set of keywords. """
96
+ # normalize to tuples
97
+ if isinstance(keywords, str):
98
+ keywords = tuple(filter(None, keywords.split()))
99
+ elif hasattr(keywords, '_keywords'):
100
+ keywords = keywords._keywords
101
+ elif not isinstance(keywords, tuple):
102
+ raise TypeError("key %r is not a string or tuple" % (keywords,))
103
+ if consumer is not None and not py.builtin.callable(consumer):
104
+ if not hasattr(consumer, 'write'):
105
+ raise TypeError(
106
+ "%r should be None, callable or file-like" % (consumer,))
107
+ consumer = File(consumer)
108
+ self.keywords2consumer[keywords] = consumer
109
+
110
+
111
+ def default_consumer(msg):
112
+ """ the default consumer, prints the message to stdout (using 'print') """
113
+ sys.stderr.write(str(msg)+"\n")
114
+
115
+ default_keywordmapper = KeywordMapper()
116
+
117
+
118
+ def setconsumer(keywords, consumer):
119
+ default_keywordmapper.setconsumer(keywords, consumer)
120
+
121
+
122
+ def setstate(state):
123
+ default_keywordmapper.setstate(state)
124
+
125
+
126
+ def getstate():
127
+ return default_keywordmapper.getstate()
128
+
129
+ #
130
+ # Consumers
131
+ #
132
+
133
+
134
+ class File(object):
135
+ """ log consumer wrapping a file(-like) object """
136
+ def __init__(self, f):
137
+ assert hasattr(f, 'write')
138
+ # assert isinstance(f, file) or not hasattr(f, 'open')
139
+ self._file = f
140
+
141
+ def __call__(self, msg):
142
+ """ write a message to the log """
143
+ self._file.write(str(msg) + "\n")
144
+ if hasattr(self._file, 'flush'):
145
+ self._file.flush()
146
+
147
+
148
+ class Path(object):
149
+ """ log consumer that opens and writes to a Path """
150
+ def __init__(self, filename, append=False,
151
+ delayed_create=False, buffering=False):
152
+ self._append = append
153
+ self._filename = str(filename)
154
+ self._buffering = buffering
155
+ if not delayed_create:
156
+ self._openfile()
157
+
158
+ def _openfile(self):
159
+ mode = self._append and 'a' or 'w'
160
+ f = open(self._filename, mode)
161
+ self._file = f
162
+
163
+ def __call__(self, msg):
164
+ """ write a message to the log """
165
+ if not hasattr(self, "_file"):
166
+ self._openfile()
167
+ self._file.write(str(msg) + "\n")
168
+ if not self._buffering:
169
+ self._file.flush()
170
+
171
+
172
+ def STDOUT(msg):
173
+ """ consumer that writes to sys.stdout """
174
+ sys.stdout.write(str(msg)+"\n")
175
+
176
+
177
+ def STDERR(msg):
178
+ """ consumer that writes to sys.stderr """
179
+ sys.stderr.write(str(msg)+"\n")
180
+
181
+
182
+ class Syslog:
183
+ """ consumer that writes to the syslog daemon """
184
+
185
+ def __init__(self, priority=None):
186
+ if priority is None:
187
+ priority = self.LOG_INFO
188
+ self.priority = priority
189
+
190
+ def __call__(self, msg):
191
+ """ write a message to the log """
192
+ import syslog
193
+ syslog.syslog(self.priority, str(msg))
194
+
195
+
196
+ try:
197
+ import syslog
198
+ except ImportError:
199
+ pass
200
+ else:
201
+ for _prio in "EMERG ALERT CRIT ERR WARNING NOTICE INFO DEBUG".split():
202
+ _prio = "LOG_" + _prio
203
+ try:
204
+ setattr(Syslog, _prio, getattr(syslog, _prio))
205
+ except AttributeError:
206
+ pass
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/py/_log/warning.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import py, sys
2
+
3
+ class DeprecationWarning(DeprecationWarning):
4
+ def __init__(self, msg, path, lineno):
5
+ self.msg = msg
6
+ self.path = path
7
+ self.lineno = lineno
8
+ def __repr__(self):
9
+ return "%s:%d: %s" %(self.path, self.lineno+1, self.msg)
10
+ def __str__(self):
11
+ return self.msg
12
+
13
+ def _apiwarn(startversion, msg, stacklevel=2, function=None):
14
+ # below is mostly COPIED from python2.4/warnings.py's def warn()
15
+ # Get context information
16
+ if isinstance(stacklevel, str):
17
+ frame = sys._getframe(1)
18
+ level = 1
19
+ found = frame.f_code.co_filename.find(stacklevel) != -1
20
+ while frame:
21
+ co = frame.f_code
22
+ if co.co_filename.find(stacklevel) == -1:
23
+ if found:
24
+ stacklevel = level
25
+ break
26
+ else:
27
+ found = True
28
+ level += 1
29
+ frame = frame.f_back
30
+ else:
31
+ stacklevel = 1
32
+ msg = "%s (since version %s)" %(msg, startversion)
33
+ warn(msg, stacklevel=stacklevel+1, function=function)
34
+
35
+
36
+ def warn(msg, stacklevel=1, function=None):
37
+ if function is not None:
38
+ import inspect
39
+ filename = inspect.getfile(function)
40
+ lineno = py.code.getrawcode(function).co_firstlineno
41
+ else:
42
+ try:
43
+ caller = sys._getframe(stacklevel)
44
+ except ValueError:
45
+ globals = sys.__dict__
46
+ lineno = 1
47
+ else:
48
+ globals = caller.f_globals
49
+ lineno = caller.f_lineno
50
+ if '__name__' in globals:
51
+ module = globals['__name__']
52
+ else:
53
+ module = "<string>"
54
+ filename = globals.get('__file__')
55
+ if filename:
56
+ fnl = filename.lower()
57
+ if fnl.endswith(".pyc") or fnl.endswith(".pyo"):
58
+ filename = filename[:-1]
59
+ elif fnl.endswith("$py.class"):
60
+ filename = filename.replace('$py.class', '.py')
61
+ else:
62
+ if module == "__main__":
63
+ try:
64
+ filename = sys.argv[0]
65
+ except AttributeError:
66
+ # embedded interpreters don't have sys.argv, see bug #839151
67
+ filename = '__main__'
68
+ if not filename:
69
+ filename = module
70
+ path = py.path.local(filename)
71
+ warning = DeprecationWarning(msg, path, lineno)
72
+ import warnings
73
+ warnings.warn_explicit(warning, category=Warning,
74
+ filename=str(warning.path),
75
+ lineno=warning.lineno,
76
+ registry=warnings.__dict__.setdefault(
77
+ "__warningsregistry__", {})
78
+ )
79
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # PLY package
2
+ # Author: David Beazley (dave@dabeaz.com)
3
+
4
+ __version__ = '3.9'
5
+ __all__ = ['lex','yacc']
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/cpp.py ADDED
@@ -0,0 +1,905 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # cpp.py
3
+ #
4
+ # Author: David Beazley (http://www.dabeaz.com)
5
+ # Copyright (C) 2017
6
+ # All rights reserved
7
+ #
8
+ # This module implements an ANSI-C style lexical preprocessor for PLY.
9
+ # -----------------------------------------------------------------------------
10
+ import sys
11
+
12
+ # Some Python 3 compatibility shims
13
+ if sys.version_info.major < 3:
14
+ STRING_TYPES = (str, unicode)
15
+ else:
16
+ STRING_TYPES = str
17
+ xrange = range
18
+
19
+ # -----------------------------------------------------------------------------
20
+ # Default preprocessor lexer definitions. These tokens are enough to get
21
+ # a basic preprocessor working. Other modules may import these if they want
22
+ # -----------------------------------------------------------------------------
23
+
24
+ tokens = (
25
+ 'CPP_ID','CPP_INTEGER', 'CPP_FLOAT', 'CPP_STRING', 'CPP_CHAR', 'CPP_WS', 'CPP_COMMENT1', 'CPP_COMMENT2', 'CPP_POUND','CPP_DPOUND'
26
+ )
27
+
28
+ literals = "+-*/%|&~^<>=!?()[]{}.,;:\\\'\""
29
+
30
+ # Whitespace
31
+ def t_CPP_WS(t):
32
+ r'\s+'
33
+ t.lexer.lineno += t.value.count("\n")
34
+ return t
35
+
36
+ t_CPP_POUND = r'\#'
37
+ t_CPP_DPOUND = r'\#\#'
38
+
39
+ # Identifier
40
+ t_CPP_ID = r'[A-Za-z_][\w_]*'
41
+
42
+ # Integer literal
43
+ def CPP_INTEGER(t):
44
+ r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)'
45
+ return t
46
+
47
+ t_CPP_INTEGER = CPP_INTEGER
48
+
49
+ # Floating literal
50
+ t_CPP_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
51
+
52
+ # String literal
53
+ def t_CPP_STRING(t):
54
+ r'\"([^\\\n]|(\\(.|\n)))*?\"'
55
+ t.lexer.lineno += t.value.count("\n")
56
+ return t
57
+
58
+ # Character constant 'c' or L'c'
59
+ def t_CPP_CHAR(t):
60
+ r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
61
+ t.lexer.lineno += t.value.count("\n")
62
+ return t
63
+
64
+ # Comment
65
+ def t_CPP_COMMENT1(t):
66
+ r'(/\*(.|\n)*?\*/)'
67
+ ncr = t.value.count("\n")
68
+ t.lexer.lineno += ncr
69
+ # replace with one space or a number of '\n'
70
+ t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
71
+ return t
72
+
73
+ # Line comment
74
+ def t_CPP_COMMENT2(t):
75
+ r'(//.*?(\n|$))'
76
+ # replace with '/n'
77
+ t.type = 'CPP_WS'; t.value = '\n'
78
+ return t
79
+
80
+ def t_error(t):
81
+ t.type = t.value[0]
82
+ t.value = t.value[0]
83
+ t.lexer.skip(1)
84
+ return t
85
+
86
+ import re
87
+ import copy
88
+ import time
89
+ import os.path
90
+
91
+ # -----------------------------------------------------------------------------
92
+ # trigraph()
93
+ #
94
+ # Given an input string, this function replaces all trigraph sequences.
95
+ # The following mapping is used:
96
+ #
97
+ # ??= #
98
+ # ??/ \
99
+ # ??' ^
100
+ # ??( [
101
+ # ??) ]
102
+ # ??! |
103
+ # ??< {
104
+ # ??> }
105
+ # ??- ~
106
+ # -----------------------------------------------------------------------------
107
+
108
+ _trigraph_pat = re.compile(r'''\?\?[=/\'\(\)\!<>\-]''')
109
+ _trigraph_rep = {
110
+ '=':'#',
111
+ '/':'\\',
112
+ "'":'^',
113
+ '(':'[',
114
+ ')':']',
115
+ '!':'|',
116
+ '<':'{',
117
+ '>':'}',
118
+ '-':'~'
119
+ }
120
+
121
+ def trigraph(input):
122
+ return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input)
123
+
124
+ # ------------------------------------------------------------------
125
+ # Macro object
126
+ #
127
+ # This object holds information about preprocessor macros
128
+ #
129
+ # .name - Macro name (string)
130
+ # .value - Macro value (a list of tokens)
131
+ # .arglist - List of argument names
132
+ # .variadic - Boolean indicating whether or not variadic macro
133
+ # .vararg - Name of the variadic parameter
134
+ #
135
+ # When a macro is created, the macro replacement token sequence is
136
+ # pre-scanned and used to create patch lists that are later used
137
+ # during macro expansion
138
+ # ------------------------------------------------------------------
139
+
140
+ class Macro(object):
141
+ def __init__(self,name,value,arglist=None,variadic=False):
142
+ self.name = name
143
+ self.value = value
144
+ self.arglist = arglist
145
+ self.variadic = variadic
146
+ if variadic:
147
+ self.vararg = arglist[-1]
148
+ self.source = None
149
+
150
+ # ------------------------------------------------------------------
151
+ # Preprocessor object
152
+ #
153
+ # Object representing a preprocessor. Contains macro definitions,
154
+ # include directories, and other information
155
+ # ------------------------------------------------------------------
156
+
157
+ class Preprocessor(object):
158
+ def __init__(self,lexer=None):
159
+ if lexer is None:
160
+ lexer = lex.lexer
161
+ self.lexer = lexer
162
+ self.macros = { }
163
+ self.path = []
164
+ self.temp_path = []
165
+
166
+ # Probe the lexer for selected tokens
167
+ self.lexprobe()
168
+
169
+ tm = time.localtime()
170
+ self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm))
171
+ self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm))
172
+ self.parser = None
173
+
174
+ # -----------------------------------------------------------------------------
175
+ # tokenize()
176
+ #
177
+ # Utility function. Given a string of text, tokenize into a list of tokens
178
+ # -----------------------------------------------------------------------------
179
+
180
+ def tokenize(self,text):
181
+ tokens = []
182
+ self.lexer.input(text)
183
+ while True:
184
+ tok = self.lexer.token()
185
+ if not tok: break
186
+ tokens.append(tok)
187
+ return tokens
188
+
189
+ # ---------------------------------------------------------------------
190
+ # error()
191
+ #
192
+ # Report a preprocessor error/warning of some kind
193
+ # ----------------------------------------------------------------------
194
+
195
+ def error(self,file,line,msg):
196
+ print("%s:%d %s" % (file,line,msg))
197
+
198
+ # ----------------------------------------------------------------------
199
+ # lexprobe()
200
+ #
201
+ # This method probes the preprocessor lexer object to discover
202
+ # the token types of symbols that are important to the preprocessor.
203
+ # If this works right, the preprocessor will simply "work"
204
+ # with any suitable lexer regardless of how tokens have been named.
205
+ # ----------------------------------------------------------------------
206
+
207
+ def lexprobe(self):
208
+
209
+ # Determine the token type for identifiers
210
+ self.lexer.input("identifier")
211
+ tok = self.lexer.token()
212
+ if not tok or tok.value != "identifier":
213
+ print("Couldn't determine identifier type")
214
+ else:
215
+ self.t_ID = tok.type
216
+
217
+ # Determine the token type for integers
218
+ self.lexer.input("12345")
219
+ tok = self.lexer.token()
220
+ if not tok or int(tok.value) != 12345:
221
+ print("Couldn't determine integer type")
222
+ else:
223
+ self.t_INTEGER = tok.type
224
+ self.t_INTEGER_TYPE = type(tok.value)
225
+
226
+ # Determine the token type for strings enclosed in double quotes
227
+ self.lexer.input("\"filename\"")
228
+ tok = self.lexer.token()
229
+ if not tok or tok.value != "\"filename\"":
230
+ print("Couldn't determine string type")
231
+ else:
232
+ self.t_STRING = tok.type
233
+
234
+ # Determine the token type for whitespace--if any
235
+ self.lexer.input(" ")
236
+ tok = self.lexer.token()
237
+ if not tok or tok.value != " ":
238
+ self.t_SPACE = None
239
+ else:
240
+ self.t_SPACE = tok.type
241
+
242
+ # Determine the token type for newlines
243
+ self.lexer.input("\n")
244
+ tok = self.lexer.token()
245
+ if not tok or tok.value != "\n":
246
+ self.t_NEWLINE = None
247
+ print("Couldn't determine token for newlines")
248
+ else:
249
+ self.t_NEWLINE = tok.type
250
+
251
+ self.t_WS = (self.t_SPACE, self.t_NEWLINE)
252
+
253
+ # Check for other characters used by the preprocessor
254
+ chars = [ '<','>','#','##','\\','(',')',',','.']
255
+ for c in chars:
256
+ self.lexer.input(c)
257
+ tok = self.lexer.token()
258
+ if not tok or tok.value != c:
259
+ print("Unable to lex '%s' required for preprocessor" % c)
260
+
261
+ # ----------------------------------------------------------------------
262
+ # add_path()
263
+ #
264
+ # Adds a search path to the preprocessor.
265
+ # ----------------------------------------------------------------------
266
+
267
+ def add_path(self,path):
268
+ self.path.append(path)
269
+
270
+ # ----------------------------------------------------------------------
271
+ # group_lines()
272
+ #
273
+ # Given an input string, this function splits it into lines. Trailing whitespace
274
+ # is removed. Any line ending with \ is grouped with the next line. This
275
+ # function forms the lowest level of the preprocessor---grouping into text into
276
+ # a line-by-line format.
277
+ # ----------------------------------------------------------------------
278
+
279
+ def group_lines(self,input):
280
+ lex = self.lexer.clone()
281
+ lines = [x.rstrip() for x in input.splitlines()]
282
+ for i in xrange(len(lines)):
283
+ j = i+1
284
+ while lines[i].endswith('\\') and (j < len(lines)):
285
+ lines[i] = lines[i][:-1]+lines[j]
286
+ lines[j] = ""
287
+ j += 1
288
+
289
+ input = "\n".join(lines)
290
+ lex.input(input)
291
+ lex.lineno = 1
292
+
293
+ current_line = []
294
+ while True:
295
+ tok = lex.token()
296
+ if not tok:
297
+ break
298
+ current_line.append(tok)
299
+ if tok.type in self.t_WS and '\n' in tok.value:
300
+ yield current_line
301
+ current_line = []
302
+
303
+ if current_line:
304
+ yield current_line
305
+
306
+ # ----------------------------------------------------------------------
307
+ # tokenstrip()
308
+ #
309
+ # Remove leading/trailing whitespace tokens from a token list
310
+ # ----------------------------------------------------------------------
311
+
312
+ def tokenstrip(self,tokens):
313
+ i = 0
314
+ while i < len(tokens) and tokens[i].type in self.t_WS:
315
+ i += 1
316
+ del tokens[:i]
317
+ i = len(tokens)-1
318
+ while i >= 0 and tokens[i].type in self.t_WS:
319
+ i -= 1
320
+ del tokens[i+1:]
321
+ return tokens
322
+
323
+
324
+ # ----------------------------------------------------------------------
325
+ # collect_args()
326
+ #
327
+ # Collects comma separated arguments from a list of tokens. The arguments
328
+ # must be enclosed in parenthesis. Returns a tuple (tokencount,args,positions)
329
+ # where tokencount is the number of tokens consumed, args is a list of arguments,
330
+ # and positions is a list of integers containing the starting index of each
331
+ # argument. Each argument is represented by a list of tokens.
332
+ #
333
+ # When collecting arguments, leading and trailing whitespace is removed
334
+ # from each argument.
335
+ #
336
+ # This function properly handles nested parenthesis and commas---these do not
337
+ # define new arguments.
338
+ # ----------------------------------------------------------------------
339
+
340
+ def collect_args(self,tokenlist):
341
+ args = []
342
+ positions = []
343
+ current_arg = []
344
+ nesting = 1
345
+ tokenlen = len(tokenlist)
346
+
347
+ # Search for the opening '('.
348
+ i = 0
349
+ while (i < tokenlen) and (tokenlist[i].type in self.t_WS):
350
+ i += 1
351
+
352
+ if (i < tokenlen) and (tokenlist[i].value == '('):
353
+ positions.append(i+1)
354
+ else:
355
+ self.error(self.source,tokenlist[0].lineno,"Missing '(' in macro arguments")
356
+ return 0, [], []
357
+
358
+ i += 1
359
+
360
+ while i < tokenlen:
361
+ t = tokenlist[i]
362
+ if t.value == '(':
363
+ current_arg.append(t)
364
+ nesting += 1
365
+ elif t.value == ')':
366
+ nesting -= 1
367
+ if nesting == 0:
368
+ if current_arg:
369
+ args.append(self.tokenstrip(current_arg))
370
+ positions.append(i)
371
+ return i+1,args,positions
372
+ current_arg.append(t)
373
+ elif t.value == ',' and nesting == 1:
374
+ args.append(self.tokenstrip(current_arg))
375
+ positions.append(i+1)
376
+ current_arg = []
377
+ else:
378
+ current_arg.append(t)
379
+ i += 1
380
+
381
+ # Missing end argument
382
+ self.error(self.source,tokenlist[-1].lineno,"Missing ')' in macro arguments")
383
+ return 0, [],[]
384
+
385
+ # ----------------------------------------------------------------------
386
+ # macro_prescan()
387
+ #
388
+ # Examine the macro value (token sequence) and identify patch points
389
+ # This is used to speed up macro expansion later on---we'll know
390
+ # right away where to apply patches to the value to form the expansion
391
+ # ----------------------------------------------------------------------
392
+
393
+ def macro_prescan(self,macro):
394
+ macro.patch = [] # Standard macro arguments
395
+ macro.str_patch = [] # String conversion expansion
396
+ macro.var_comma_patch = [] # Variadic macro comma patch
397
+ i = 0
398
+ while i < len(macro.value):
399
+ if macro.value[i].type == self.t_ID and macro.value[i].value in macro.arglist:
400
+ argnum = macro.arglist.index(macro.value[i].value)
401
+ # Conversion of argument to a string
402
+ if i > 0 and macro.value[i-1].value == '#':
403
+ macro.value[i] = copy.copy(macro.value[i])
404
+ macro.value[i].type = self.t_STRING
405
+ del macro.value[i-1]
406
+ macro.str_patch.append((argnum,i-1))
407
+ continue
408
+ # Concatenation
409
+ elif (i > 0 and macro.value[i-1].value == '##'):
410
+ macro.patch.append(('c',argnum,i-1))
411
+ del macro.value[i-1]
412
+ continue
413
+ elif ((i+1) < len(macro.value) and macro.value[i+1].value == '##'):
414
+ macro.patch.append(('c',argnum,i))
415
+ i += 1
416
+ continue
417
+ # Standard expansion
418
+ else:
419
+ macro.patch.append(('e',argnum,i))
420
+ elif macro.value[i].value == '##':
421
+ if macro.variadic and (i > 0) and (macro.value[i-1].value == ',') and \
422
+ ((i+1) < len(macro.value)) and (macro.value[i+1].type == self.t_ID) and \
423
+ (macro.value[i+1].value == macro.vararg):
424
+ macro.var_comma_patch.append(i-1)
425
+ i += 1
426
+ macro.patch.sort(key=lambda x: x[2],reverse=True)
427
+
428
+ # ----------------------------------------------------------------------
429
+ # macro_expand_args()
430
+ #
431
+ # Given a Macro and list of arguments (each a token list), this method
432
+ # returns an expanded version of a macro. The return value is a token sequence
433
+ # representing the replacement macro tokens
434
+ # ----------------------------------------------------------------------
435
+
436
+ def macro_expand_args(self,macro,args):
437
+ # Make a copy of the macro token sequence
438
+ rep = [copy.copy(_x) for _x in macro.value]
439
+
440
+ # Make string expansion patches. These do not alter the length of the replacement sequence
441
+
442
+ str_expansion = {}
443
+ for argnum, i in macro.str_patch:
444
+ if argnum not in str_expansion:
445
+ str_expansion[argnum] = ('"%s"' % "".join([x.value for x in args[argnum]])).replace("\\","\\\\")
446
+ rep[i] = copy.copy(rep[i])
447
+ rep[i].value = str_expansion[argnum]
448
+
449
+ # Make the variadic macro comma patch. If the variadic macro argument is empty, we get rid
450
+ comma_patch = False
451
+ if macro.variadic and not args[-1]:
452
+ for i in macro.var_comma_patch:
453
+ rep[i] = None
454
+ comma_patch = True
455
+
456
+ # Make all other patches. The order of these matters. It is assumed that the patch list
457
+ # has been sorted in reverse order of patch location since replacements will cause the
458
+ # size of the replacement sequence to expand from the patch point.
459
+
460
+ expanded = { }
461
+ for ptype, argnum, i in macro.patch:
462
+ # Concatenation. Argument is left unexpanded
463
+ if ptype == 'c':
464
+ rep[i:i+1] = args[argnum]
465
+ # Normal expansion. Argument is macro expanded first
466
+ elif ptype == 'e':
467
+ if argnum not in expanded:
468
+ expanded[argnum] = self.expand_macros(args[argnum])
469
+ rep[i:i+1] = expanded[argnum]
470
+
471
+ # Get rid of removed comma if necessary
472
+ if comma_patch:
473
+ rep = [_i for _i in rep if _i]
474
+
475
+ return rep
476
+
477
+
478
+ # ----------------------------------------------------------------------
479
+ # expand_macros()
480
+ #
481
+ # Given a list of tokens, this function performs macro expansion.
482
+ # The expanded argument is a dictionary that contains macros already
483
+ # expanded. This is used to prevent infinite recursion.
484
+ # ----------------------------------------------------------------------
485
+
486
+ def expand_macros(self,tokens,expanded=None):
487
+ if expanded is None:
488
+ expanded = {}
489
+ i = 0
490
+ while i < len(tokens):
491
+ t = tokens[i]
492
+ if t.type == self.t_ID:
493
+ if t.value in self.macros and t.value not in expanded:
494
+ # Yes, we found a macro match
495
+ expanded[t.value] = True
496
+
497
+ m = self.macros[t.value]
498
+ if not m.arglist:
499
+ # A simple macro
500
+ ex = self.expand_macros([copy.copy(_x) for _x in m.value],expanded)
501
+ for e in ex:
502
+ e.lineno = t.lineno
503
+ tokens[i:i+1] = ex
504
+ i += len(ex)
505
+ else:
506
+ # A macro with arguments
507
+ j = i + 1
508
+ while j < len(tokens) and tokens[j].type in self.t_WS:
509
+ j += 1
510
+ if tokens[j].value == '(':
511
+ tokcount,args,positions = self.collect_args(tokens[j:])
512
+ if not m.variadic and len(args) != len(m.arglist):
513
+ self.error(self.source,t.lineno,"Macro %s requires %d arguments" % (t.value,len(m.arglist)))
514
+ i = j + tokcount
515
+ elif m.variadic and len(args) < len(m.arglist)-1:
516
+ if len(m.arglist) > 2:
517
+ self.error(self.source,t.lineno,"Macro %s must have at least %d arguments" % (t.value, len(m.arglist)-1))
518
+ else:
519
+ self.error(self.source,t.lineno,"Macro %s must have at least %d argument" % (t.value, len(m.arglist)-1))
520
+ i = j + tokcount
521
+ else:
522
+ if m.variadic:
523
+ if len(args) == len(m.arglist)-1:
524
+ args.append([])
525
+ else:
526
+ args[len(m.arglist)-1] = tokens[j+positions[len(m.arglist)-1]:j+tokcount-1]
527
+ del args[len(m.arglist):]
528
+
529
+ # Get macro replacement text
530
+ rep = self.macro_expand_args(m,args)
531
+ rep = self.expand_macros(rep,expanded)
532
+ for r in rep:
533
+ r.lineno = t.lineno
534
+ tokens[i:j+tokcount] = rep
535
+ i += len(rep)
536
+ del expanded[t.value]
537
+ continue
538
+ elif t.value == '__LINE__':
539
+ t.type = self.t_INTEGER
540
+ t.value = self.t_INTEGER_TYPE(t.lineno)
541
+
542
+ i += 1
543
+ return tokens
544
+
545
+ # ----------------------------------------------------------------------
546
+ # evalexpr()
547
+ #
548
+ # Evaluate an expression token sequence for the purposes of evaluating
549
+ # integral expressions.
550
+ # ----------------------------------------------------------------------
551
+
552
+ def evalexpr(self,tokens):
553
+ # tokens = tokenize(line)
554
+ # Search for defined macros
555
+ i = 0
556
+ while i < len(tokens):
557
+ if tokens[i].type == self.t_ID and tokens[i].value == 'defined':
558
+ j = i + 1
559
+ needparen = False
560
+ result = "0L"
561
+ while j < len(tokens):
562
+ if tokens[j].type in self.t_WS:
563
+ j += 1
564
+ continue
565
+ elif tokens[j].type == self.t_ID:
566
+ if tokens[j].value in self.macros:
567
+ result = "1L"
568
+ else:
569
+ result = "0L"
570
+ if not needparen: break
571
+ elif tokens[j].value == '(':
572
+ needparen = True
573
+ elif tokens[j].value == ')':
574
+ break
575
+ else:
576
+ self.error(self.source,tokens[i].lineno,"Malformed defined()")
577
+ j += 1
578
+ tokens[i].type = self.t_INTEGER
579
+ tokens[i].value = self.t_INTEGER_TYPE(result)
580
+ del tokens[i+1:j+1]
581
+ i += 1
582
+ tokens = self.expand_macros(tokens)
583
+ for i,t in enumerate(tokens):
584
+ if t.type == self.t_ID:
585
+ tokens[i] = copy.copy(t)
586
+ tokens[i].type = self.t_INTEGER
587
+ tokens[i].value = self.t_INTEGER_TYPE("0L")
588
+ elif t.type == self.t_INTEGER:
589
+ tokens[i] = copy.copy(t)
590
+ # Strip off any trailing suffixes
591
+ tokens[i].value = str(tokens[i].value)
592
+ while tokens[i].value[-1] not in "0123456789abcdefABCDEF":
593
+ tokens[i].value = tokens[i].value[:-1]
594
+
595
+ expr = "".join([str(x.value) for x in tokens])
596
+ expr = expr.replace("&&"," and ")
597
+ expr = expr.replace("||"," or ")
598
+ expr = expr.replace("!"," not ")
599
+ try:
600
+ result = eval(expr)
601
+ except Exception:
602
+ self.error(self.source,tokens[0].lineno,"Couldn't evaluate expression")
603
+ result = 0
604
+ return result
605
+
606
+ # ----------------------------------------------------------------------
607
+ # parsegen()
608
+ #
609
+ # Parse an input string/
610
+ # ----------------------------------------------------------------------
611
+ def parsegen(self,input,source=None):
612
+
613
+ # Replace trigraph sequences
614
+ t = trigraph(input)
615
+ lines = self.group_lines(t)
616
+
617
+ if not source:
618
+ source = ""
619
+
620
+ self.define("__FILE__ \"%s\"" % source)
621
+
622
+ self.source = source
623
+ chunk = []
624
+ enable = True
625
+ iftrigger = False
626
+ ifstack = []
627
+
628
+ for x in lines:
629
+ for i,tok in enumerate(x):
630
+ if tok.type not in self.t_WS: break
631
+ if tok.value == '#':
632
+ # Preprocessor directive
633
+
634
+ # insert necessary whitespace instead of eaten tokens
635
+ for tok in x:
636
+ if tok.type in self.t_WS and '\n' in tok.value:
637
+ chunk.append(tok)
638
+
639
+ dirtokens = self.tokenstrip(x[i+1:])
640
+ if dirtokens:
641
+ name = dirtokens[0].value
642
+ args = self.tokenstrip(dirtokens[1:])
643
+ else:
644
+ name = ""
645
+ args = []
646
+
647
+ if name == 'define':
648
+ if enable:
649
+ for tok in self.expand_macros(chunk):
650
+ yield tok
651
+ chunk = []
652
+ self.define(args)
653
+ elif name == 'include':
654
+ if enable:
655
+ for tok in self.expand_macros(chunk):
656
+ yield tok
657
+ chunk = []
658
+ oldfile = self.macros['__FILE__']
659
+ for tok in self.include(args):
660
+ yield tok
661
+ self.macros['__FILE__'] = oldfile
662
+ self.source = source
663
+ elif name == 'undef':
664
+ if enable:
665
+ for tok in self.expand_macros(chunk):
666
+ yield tok
667
+ chunk = []
668
+ self.undef(args)
669
+ elif name == 'ifdef':
670
+ ifstack.append((enable,iftrigger))
671
+ if enable:
672
+ if not args[0].value in self.macros:
673
+ enable = False
674
+ iftrigger = False
675
+ else:
676
+ iftrigger = True
677
+ elif name == 'ifndef':
678
+ ifstack.append((enable,iftrigger))
679
+ if enable:
680
+ if args[0].value in self.macros:
681
+ enable = False
682
+ iftrigger = False
683
+ else:
684
+ iftrigger = True
685
+ elif name == 'if':
686
+ ifstack.append((enable,iftrigger))
687
+ if enable:
688
+ result = self.evalexpr(args)
689
+ if not result:
690
+ enable = False
691
+ iftrigger = False
692
+ else:
693
+ iftrigger = True
694
+ elif name == 'elif':
695
+ if ifstack:
696
+ if ifstack[-1][0]: # We only pay attention if outer "if" allows this
697
+ if enable: # If already true, we flip enable False
698
+ enable = False
699
+ elif not iftrigger: # If False, but not triggered yet, we'll check expression
700
+ result = self.evalexpr(args)
701
+ if result:
702
+ enable = True
703
+ iftrigger = True
704
+ else:
705
+ self.error(self.source,dirtokens[0].lineno,"Misplaced #elif")
706
+
707
+ elif name == 'else':
708
+ if ifstack:
709
+ if ifstack[-1][0]:
710
+ if enable:
711
+ enable = False
712
+ elif not iftrigger:
713
+ enable = True
714
+ iftrigger = True
715
+ else:
716
+ self.error(self.source,dirtokens[0].lineno,"Misplaced #else")
717
+
718
+ elif name == 'endif':
719
+ if ifstack:
720
+ enable,iftrigger = ifstack.pop()
721
+ else:
722
+ self.error(self.source,dirtokens[0].lineno,"Misplaced #endif")
723
+ else:
724
+ # Unknown preprocessor directive
725
+ pass
726
+
727
+ else:
728
+ # Normal text
729
+ if enable:
730
+ chunk.extend(x)
731
+
732
+ for tok in self.expand_macros(chunk):
733
+ yield tok
734
+ chunk = []
735
+
736
+ # ----------------------------------------------------------------------
737
+ # include()
738
+ #
739
+ # Implementation of file-inclusion
740
+ # ----------------------------------------------------------------------
741
+
742
+ def include(self,tokens):
743
+ # Try to extract the filename and then process an include file
744
+ if not tokens:
745
+ return
746
+ if tokens:
747
+ if tokens[0].value != '<' and tokens[0].type != self.t_STRING:
748
+ tokens = self.expand_macros(tokens)
749
+
750
+ if tokens[0].value == '<':
751
+ # Include <...>
752
+ i = 1
753
+ while i < len(tokens):
754
+ if tokens[i].value == '>':
755
+ break
756
+ i += 1
757
+ else:
758
+ print("Malformed #include <...>")
759
+ return
760
+ filename = "".join([x.value for x in tokens[1:i]])
761
+ path = self.path + [""] + self.temp_path
762
+ elif tokens[0].type == self.t_STRING:
763
+ filename = tokens[0].value[1:-1]
764
+ path = self.temp_path + [""] + self.path
765
+ else:
766
+ print("Malformed #include statement")
767
+ return
768
+ for p in path:
769
+ iname = os.path.join(p,filename)
770
+ try:
771
+ data = open(iname,"r").read()
772
+ dname = os.path.dirname(iname)
773
+ if dname:
774
+ self.temp_path.insert(0,dname)
775
+ for tok in self.parsegen(data,filename):
776
+ yield tok
777
+ if dname:
778
+ del self.temp_path[0]
779
+ break
780
+ except IOError:
781
+ pass
782
+ else:
783
+ print("Couldn't find '%s'" % filename)
784
+
785
+ # ----------------------------------------------------------------------
786
+ # define()
787
+ #
788
+ # Define a new macro
789
+ # ----------------------------------------------------------------------
790
+
791
+ def define(self,tokens):
792
+ if isinstance(tokens,STRING_TYPES):
793
+ tokens = self.tokenize(tokens)
794
+
795
+ linetok = tokens
796
+ try:
797
+ name = linetok[0]
798
+ if len(linetok) > 1:
799
+ mtype = linetok[1]
800
+ else:
801
+ mtype = None
802
+ if not mtype:
803
+ m = Macro(name.value,[])
804
+ self.macros[name.value] = m
805
+ elif mtype.type in self.t_WS:
806
+ # A normal macro
807
+ m = Macro(name.value,self.tokenstrip(linetok[2:]))
808
+ self.macros[name.value] = m
809
+ elif mtype.value == '(':
810
+ # A macro with arguments
811
+ tokcount, args, positions = self.collect_args(linetok[1:])
812
+ variadic = False
813
+ for a in args:
814
+ if variadic:
815
+ print("No more arguments may follow a variadic argument")
816
+ break
817
+ astr = "".join([str(_i.value) for _i in a])
818
+ if astr == "...":
819
+ variadic = True
820
+ a[0].type = self.t_ID
821
+ a[0].value = '__VA_ARGS__'
822
+ variadic = True
823
+ del a[1:]
824
+ continue
825
+ elif astr[-3:] == "..." and a[0].type == self.t_ID:
826
+ variadic = True
827
+ del a[1:]
828
+ # If, for some reason, "." is part of the identifier, strip off the name for the purposes
829
+ # of macro expansion
830
+ if a[0].value[-3:] == '...':
831
+ a[0].value = a[0].value[:-3]
832
+ continue
833
+ if len(a) > 1 or a[0].type != self.t_ID:
834
+ print("Invalid macro argument")
835
+ break
836
+ else:
837
+ mvalue = self.tokenstrip(linetok[1+tokcount:])
838
+ i = 0
839
+ while i < len(mvalue):
840
+ if i+1 < len(mvalue):
841
+ if mvalue[i].type in self.t_WS and mvalue[i+1].value == '##':
842
+ del mvalue[i]
843
+ continue
844
+ elif mvalue[i].value == '##' and mvalue[i+1].type in self.t_WS:
845
+ del mvalue[i+1]
846
+ i += 1
847
+ m = Macro(name.value,mvalue,[x[0].value for x in args],variadic)
848
+ self.macro_prescan(m)
849
+ self.macros[name.value] = m
850
+ else:
851
+ print("Bad macro definition")
852
+ except LookupError:
853
+ print("Bad macro definition")
854
+
855
+ # ----------------------------------------------------------------------
856
+ # undef()
857
+ #
858
+ # Undefine a macro
859
+ # ----------------------------------------------------------------------
860
+
861
+ def undef(self,tokens):
862
+ id = tokens[0].value
863
+ try:
864
+ del self.macros[id]
865
+ except LookupError:
866
+ pass
867
+
868
+ # ----------------------------------------------------------------------
869
+ # parse()
870
+ #
871
+ # Parse input text.
872
+ # ----------------------------------------------------------------------
873
+ def parse(self,input,source=None,ignore={}):
874
+ self.ignore = ignore
875
+ self.parser = self.parsegen(input,source)
876
+
877
+ # ----------------------------------------------------------------------
878
+ # token()
879
+ #
880
+ # Method to return individual tokens
881
+ # ----------------------------------------------------------------------
882
+ def token(self):
883
+ try:
884
+ while True:
885
+ tok = next(self.parser)
886
+ if tok.type not in self.ignore: return tok
887
+ except StopIteration:
888
+ self.parser = None
889
+ return None
890
+
891
+ if __name__ == '__main__':
892
+ import ply.lex as lex
893
+ lexer = lex.lex()
894
+
895
+ # Run a preprocessor
896
+ import sys
897
+ f = open(sys.argv[1])
898
+ input = f.read()
899
+
900
+ p = Preprocessor(lexer)
901
+ p.parse(input,sys.argv[1])
902
+ while True:
903
+ tok = p.token()
904
+ if not tok: break
905
+ print(p.source, tok)
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/ctokens.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ----------------------------------------------------------------------
2
+ # ctokens.py
3
+ #
4
+ # Token specifications for symbols in ANSI C and C++. This file is
5
+ # meant to be used as a library in other tokenizers.
6
+ # ----------------------------------------------------------------------
7
+
8
+ # Reserved words
9
+
10
+ tokens = [
11
+ # Literals (identifier, integer constant, float constant, string constant, char const)
12
+ 'ID', 'TYPEID', 'INTEGER', 'FLOAT', 'STRING', 'CHARACTER',
13
+
14
+ # Operators (+,-,*,/,%,|,&,~,^,<<,>>, ||, &&, !, <, <=, >, >=, ==, !=)
15
+ 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MODULO',
16
+ 'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT',
17
+ 'LOR', 'LAND', 'LNOT',
18
+ 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE',
19
+
20
+ # Assignment (=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=)
21
+ 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL',
22
+ 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL',
23
+
24
+ # Increment/decrement (++,--)
25
+ 'INCREMENT', 'DECREMENT',
26
+
27
+ # Structure dereference (->)
28
+ 'ARROW',
29
+
30
+ # Ternary operator (?)
31
+ 'TERNARY',
32
+
33
+ # Delimeters ( ) [ ] { } , . ; :
34
+ 'LPAREN', 'RPAREN',
35
+ 'LBRACKET', 'RBRACKET',
36
+ 'LBRACE', 'RBRACE',
37
+ 'COMMA', 'PERIOD', 'SEMI', 'COLON',
38
+
39
+ # Ellipsis (...)
40
+ 'ELLIPSIS',
41
+ ]
42
+
43
+ # Operators
44
+ t_PLUS = r'\+'
45
+ t_MINUS = r'-'
46
+ t_TIMES = r'\*'
47
+ t_DIVIDE = r'/'
48
+ t_MODULO = r'%'
49
+ t_OR = r'\|'
50
+ t_AND = r'&'
51
+ t_NOT = r'~'
52
+ t_XOR = r'\^'
53
+ t_LSHIFT = r'<<'
54
+ t_RSHIFT = r'>>'
55
+ t_LOR = r'\|\|'
56
+ t_LAND = r'&&'
57
+ t_LNOT = r'!'
58
+ t_LT = r'<'
59
+ t_GT = r'>'
60
+ t_LE = r'<='
61
+ t_GE = r'>='
62
+ t_EQ = r'=='
63
+ t_NE = r'!='
64
+
65
+ # Assignment operators
66
+
67
+ t_EQUALS = r'='
68
+ t_TIMESEQUAL = r'\*='
69
+ t_DIVEQUAL = r'/='
70
+ t_MODEQUAL = r'%='
71
+ t_PLUSEQUAL = r'\+='
72
+ t_MINUSEQUAL = r'-='
73
+ t_LSHIFTEQUAL = r'<<='
74
+ t_RSHIFTEQUAL = r'>>='
75
+ t_ANDEQUAL = r'&='
76
+ t_OREQUAL = r'\|='
77
+ t_XOREQUAL = r'\^='
78
+
79
+ # Increment/decrement
80
+ t_INCREMENT = r'\+\+'
81
+ t_DECREMENT = r'--'
82
+
83
+ # ->
84
+ t_ARROW = r'->'
85
+
86
+ # ?
87
+ t_TERNARY = r'\?'
88
+
89
+ # Delimeters
90
+ t_LPAREN = r'\('
91
+ t_RPAREN = r'\)'
92
+ t_LBRACKET = r'\['
93
+ t_RBRACKET = r'\]'
94
+ t_LBRACE = r'\{'
95
+ t_RBRACE = r'\}'
96
+ t_COMMA = r','
97
+ t_PERIOD = r'\.'
98
+ t_SEMI = r';'
99
+ t_COLON = r':'
100
+ t_ELLIPSIS = r'\.\.\.'
101
+
102
+ # Identifiers
103
+ t_ID = r'[A-Za-z_][A-Za-z0-9_]*'
104
+
105
+ # Integer literal
106
+ t_INTEGER = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?'
107
+
108
+ # Floating literal
109
+ t_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
110
+
111
+ # String literal
112
+ t_STRING = r'\"([^\\\n]|(\\.))*?\"'
113
+
114
+ # Character constant 'c' or L'c'
115
+ t_CHARACTER = r'(L)?\'([^\\\n]|(\\.))*?\''
116
+
117
+ # Comment (C-Style)
118
+ def t_COMMENT(t):
119
+ r'/\*(.|\n)*?\*/'
120
+ t.lexer.lineno += t.value.count('\n')
121
+ return t
122
+
123
+ # Comment (C++-Style)
124
+ def t_CPPCOMMENT(t):
125
+ r'//.*\n'
126
+ t.lexer.lineno += 1
127
+ return t
128
+
129
+
130
+
131
+
132
+
133
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/lex.py ADDED
@@ -0,0 +1,1099 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------
2
+ # ply: lex.py
3
+ #
4
+ # Copyright (C) 2001-2017
5
+ # David M. Beazley (Dabeaz LLC)
6
+ # All rights reserved.
7
+ #
8
+ # Redistribution and use in source and binary forms, with or without
9
+ # modification, are permitted provided that the following conditions are
10
+ # met:
11
+ #
12
+ # * Redistributions of source code must retain the above copyright notice,
13
+ # this list of conditions and the following disclaimer.
14
+ # * Redistributions in binary form must reproduce the above copyright notice,
15
+ # this list of conditions and the following disclaimer in the documentation
16
+ # and/or other materials provided with the distribution.
17
+ # * Neither the name of the David Beazley or Dabeaz LLC may be used to
18
+ # endorse or promote products derived from this software without
19
+ # specific prior written permission.
20
+ #
21
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+ # -----------------------------------------------------------------------------
33
+
34
+ __version__ = '3.10'
35
+ __tabversion__ = '3.10'
36
+
37
+ import re
38
+ import sys
39
+ import types
40
+ import copy
41
+ import os
42
+ import inspect
43
+
44
+ # This tuple contains known string types
45
+ try:
46
+ # Python 2.6
47
+ StringTypes = (types.StringType, types.UnicodeType)
48
+ except AttributeError:
49
+ # Python 3.0
50
+ StringTypes = (str, bytes)
51
+
52
+ # This regular expression is used to match valid token names
53
+ _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$')
54
+
55
+ # Exception thrown when invalid token encountered and no default error
56
+ # handler is defined.
57
+ class LexError(Exception):
58
+ def __init__(self, message, s):
59
+ self.args = (message,)
60
+ self.text = s
61
+
62
+
63
+ # Token class. This class is used to represent the tokens produced.
64
+ class LexToken(object):
65
+ def __str__(self):
66
+ return 'LexToken(%s,%r,%d,%d)' % (self.type, self.value, self.lineno, self.lexpos)
67
+
68
+ def __repr__(self):
69
+ return str(self)
70
+
71
+
72
+ # This object is a stand-in for a logging object created by the
73
+ # logging module.
74
+
75
+ class PlyLogger(object):
76
+ def __init__(self, f):
77
+ self.f = f
78
+
79
+ def critical(self, msg, *args, **kwargs):
80
+ self.f.write((msg % args) + '\n')
81
+
82
+ def warning(self, msg, *args, **kwargs):
83
+ self.f.write('WARNING: ' + (msg % args) + '\n')
84
+
85
+ def error(self, msg, *args, **kwargs):
86
+ self.f.write('ERROR: ' + (msg % args) + '\n')
87
+
88
+ info = critical
89
+ debug = critical
90
+
91
+
92
+ # Null logger is used when no output is generated. Does nothing.
93
+ class NullLogger(object):
94
+ def __getattribute__(self, name):
95
+ return self
96
+
97
+ def __call__(self, *args, **kwargs):
98
+ return self
99
+
100
+
101
+ # -----------------------------------------------------------------------------
102
+ # === Lexing Engine ===
103
+ #
104
+ # The following Lexer class implements the lexer runtime. There are only
105
+ # a few public methods and attributes:
106
+ #
107
+ # input() - Store a new string in the lexer
108
+ # token() - Get the next token
109
+ # clone() - Clone the lexer
110
+ #
111
+ # lineno - Current line number
112
+ # lexpos - Current position in the input string
113
+ # -----------------------------------------------------------------------------
114
+
115
+ class Lexer:
116
+ def __init__(self):
117
+ self.lexre = None # Master regular expression. This is a list of
118
+ # tuples (re, findex) where re is a compiled
119
+ # regular expression and findex is a list
120
+ # mapping regex group numbers to rules
121
+ self.lexretext = None # Current regular expression strings
122
+ self.lexstatere = {} # Dictionary mapping lexer states to master regexs
123
+ self.lexstateretext = {} # Dictionary mapping lexer states to regex strings
124
+ self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names
125
+ self.lexstate = 'INITIAL' # Current lexer state
126
+ self.lexstatestack = [] # Stack of lexer states
127
+ self.lexstateinfo = None # State information
128
+ self.lexstateignore = {} # Dictionary of ignored characters for each state
129
+ self.lexstateerrorf = {} # Dictionary of error functions for each state
130
+ self.lexstateeoff = {} # Dictionary of eof functions for each state
131
+ self.lexreflags = 0 # Optional re compile flags
132
+ self.lexdata = None # Actual input data (as a string)
133
+ self.lexpos = 0 # Current position in input text
134
+ self.lexlen = 0 # Length of the input text
135
+ self.lexerrorf = None # Error rule (if any)
136
+ self.lexeoff = None # EOF rule (if any)
137
+ self.lextokens = None # List of valid tokens
138
+ self.lexignore = '' # Ignored characters
139
+ self.lexliterals = '' # Literal characters that can be passed through
140
+ self.lexmodule = None # Module
141
+ self.lineno = 1 # Current line number
142
+ self.lexoptimize = False # Optimized mode
143
+
144
+ def clone(self, object=None):
145
+ c = copy.copy(self)
146
+
147
+ # If the object parameter has been supplied, it means we are attaching the
148
+ # lexer to a new object. In this case, we have to rebind all methods in
149
+ # the lexstatere and lexstateerrorf tables.
150
+
151
+ if object:
152
+ newtab = {}
153
+ for key, ritem in self.lexstatere.items():
154
+ newre = []
155
+ for cre, findex in ritem:
156
+ newfindex = []
157
+ for f in findex:
158
+ if not f or not f[0]:
159
+ newfindex.append(f)
160
+ continue
161
+ newfindex.append((getattr(object, f[0].__name__), f[1]))
162
+ newre.append((cre, newfindex))
163
+ newtab[key] = newre
164
+ c.lexstatere = newtab
165
+ c.lexstateerrorf = {}
166
+ for key, ef in self.lexstateerrorf.items():
167
+ c.lexstateerrorf[key] = getattr(object, ef.__name__)
168
+ c.lexmodule = object
169
+ return c
170
+
171
+ # ------------------------------------------------------------
172
+ # writetab() - Write lexer information to a table file
173
+ # ------------------------------------------------------------
174
+ def writetab(self, lextab, outputdir=''):
175
+ if isinstance(lextab, types.ModuleType):
176
+ raise IOError("Won't overwrite existing lextab module")
177
+ basetabmodule = lextab.split('.')[-1]
178
+ filename = os.path.join(outputdir, basetabmodule) + '.py'
179
+ with open(filename, 'w') as tf:
180
+ tf.write('# %s.py. This file automatically created by PLY (version %s). Don\'t edit!\n' % (basetabmodule, __version__))
181
+ tf.write('_tabversion = %s\n' % repr(__tabversion__))
182
+ tf.write('_lextokens = set(%s)\n' % repr(tuple(self.lextokens)))
183
+ tf.write('_lexreflags = %s\n' % repr(self.lexreflags))
184
+ tf.write('_lexliterals = %s\n' % repr(self.lexliterals))
185
+ tf.write('_lexstateinfo = %s\n' % repr(self.lexstateinfo))
186
+
187
+ # Rewrite the lexstatere table, replacing function objects with function names
188
+ tabre = {}
189
+ for statename, lre in self.lexstatere.items():
190
+ titem = []
191
+ for (pat, func), retext, renames in zip(lre, self.lexstateretext[statename], self.lexstaterenames[statename]):
192
+ titem.append((retext, _funcs_to_names(func, renames)))
193
+ tabre[statename] = titem
194
+
195
+ tf.write('_lexstatere = %s\n' % repr(tabre))
196
+ tf.write('_lexstateignore = %s\n' % repr(self.lexstateignore))
197
+
198
+ taberr = {}
199
+ for statename, ef in self.lexstateerrorf.items():
200
+ taberr[statename] = ef.__name__ if ef else None
201
+ tf.write('_lexstateerrorf = %s\n' % repr(taberr))
202
+
203
+ tabeof = {}
204
+ for statename, ef in self.lexstateeoff.items():
205
+ tabeof[statename] = ef.__name__ if ef else None
206
+ tf.write('_lexstateeoff = %s\n' % repr(tabeof))
207
+
208
+ # ------------------------------------------------------------
209
+ # readtab() - Read lexer information from a tab file
210
+ # ------------------------------------------------------------
211
+ def readtab(self, tabfile, fdict):
212
+ if isinstance(tabfile, types.ModuleType):
213
+ lextab = tabfile
214
+ else:
215
+ exec('import %s' % tabfile)
216
+ lextab = sys.modules[tabfile]
217
+
218
+ if getattr(lextab, '_tabversion', '0.0') != __tabversion__:
219
+ raise ImportError('Inconsistent PLY version')
220
+
221
+ self.lextokens = lextab._lextokens
222
+ self.lexreflags = lextab._lexreflags
223
+ self.lexliterals = lextab._lexliterals
224
+ self.lextokens_all = self.lextokens | set(self.lexliterals)
225
+ self.lexstateinfo = lextab._lexstateinfo
226
+ self.lexstateignore = lextab._lexstateignore
227
+ self.lexstatere = {}
228
+ self.lexstateretext = {}
229
+ for statename, lre in lextab._lexstatere.items():
230
+ titem = []
231
+ txtitem = []
232
+ for pat, func_name in lre:
233
+ titem.append((re.compile(pat, lextab._lexreflags), _names_to_funcs(func_name, fdict)))
234
+
235
+ self.lexstatere[statename] = titem
236
+ self.lexstateretext[statename] = txtitem
237
+
238
+ self.lexstateerrorf = {}
239
+ for statename, ef in lextab._lexstateerrorf.items():
240
+ self.lexstateerrorf[statename] = fdict[ef]
241
+
242
+ self.lexstateeoff = {}
243
+ for statename, ef in lextab._lexstateeoff.items():
244
+ self.lexstateeoff[statename] = fdict[ef]
245
+
246
+ self.begin('INITIAL')
247
+
248
+ # ------------------------------------------------------------
249
+ # input() - Push a new string into the lexer
250
+ # ------------------------------------------------------------
251
+ def input(self, s):
252
+ # Pull off the first character to see if s looks like a string
253
+ c = s[:1]
254
+ if not isinstance(c, StringTypes):
255
+ raise ValueError('Expected a string')
256
+ self.lexdata = s
257
+ self.lexpos = 0
258
+ self.lexlen = len(s)
259
+
260
+ # ------------------------------------------------------------
261
+ # begin() - Changes the lexing state
262
+ # ------------------------------------------------------------
263
+ def begin(self, state):
264
+ if state not in self.lexstatere:
265
+ raise ValueError('Undefined state')
266
+ self.lexre = self.lexstatere[state]
267
+ self.lexretext = self.lexstateretext[state]
268
+ self.lexignore = self.lexstateignore.get(state, '')
269
+ self.lexerrorf = self.lexstateerrorf.get(state, None)
270
+ self.lexeoff = self.lexstateeoff.get(state, None)
271
+ self.lexstate = state
272
+
273
+ # ------------------------------------------------------------
274
+ # push_state() - Changes the lexing state and saves old on stack
275
+ # ------------------------------------------------------------
276
+ def push_state(self, state):
277
+ self.lexstatestack.append(self.lexstate)
278
+ self.begin(state)
279
+
280
+ # ------------------------------------------------------------
281
+ # pop_state() - Restores the previous state
282
+ # ------------------------------------------------------------
283
+ def pop_state(self):
284
+ self.begin(self.lexstatestack.pop())
285
+
286
+ # ------------------------------------------------------------
287
+ # current_state() - Returns the current lexing state
288
+ # ------------------------------------------------------------
289
+ def current_state(self):
290
+ return self.lexstate
291
+
292
+ # ------------------------------------------------------------
293
+ # skip() - Skip ahead n characters
294
+ # ------------------------------------------------------------
295
+ def skip(self, n):
296
+ self.lexpos += n
297
+
298
+ # ------------------------------------------------------------
299
+ # opttoken() - Return the next token from the Lexer
300
+ #
301
+ # Note: This function has been carefully implemented to be as fast
302
+ # as possible. Don't make changes unless you really know what
303
+ # you are doing
304
+ # ------------------------------------------------------------
305
+ def token(self):
306
+ # Make local copies of frequently referenced attributes
307
+ lexpos = self.lexpos
308
+ lexlen = self.lexlen
309
+ lexignore = self.lexignore
310
+ lexdata = self.lexdata
311
+
312
+ while lexpos < lexlen:
313
+ # This code provides some short-circuit code for whitespace, tabs, and other ignored characters
314
+ if lexdata[lexpos] in lexignore:
315
+ lexpos += 1
316
+ continue
317
+
318
+ # Look for a regular expression match
319
+ for lexre, lexindexfunc in self.lexre:
320
+ m = lexre.match(lexdata, lexpos)
321
+ if not m:
322
+ continue
323
+
324
+ # Create a token for return
325
+ tok = LexToken()
326
+ tok.value = m.group()
327
+ tok.lineno = self.lineno
328
+ tok.lexpos = lexpos
329
+
330
+ i = m.lastindex
331
+ func, tok.type = lexindexfunc[i]
332
+
333
+ if not func:
334
+ # If no token type was set, it's an ignored token
335
+ if tok.type:
336
+ self.lexpos = m.end()
337
+ return tok
338
+ else:
339
+ lexpos = m.end()
340
+ break
341
+
342
+ lexpos = m.end()
343
+
344
+ # If token is processed by a function, call it
345
+
346
+ tok.lexer = self # Set additional attributes useful in token rules
347
+ self.lexmatch = m
348
+ self.lexpos = lexpos
349
+
350
+ newtok = func(tok)
351
+
352
+ # Every function must return a token, if nothing, we just move to next token
353
+ if not newtok:
354
+ lexpos = self.lexpos # This is here in case user has updated lexpos.
355
+ lexignore = self.lexignore # This is here in case there was a state change
356
+ break
357
+
358
+ # Verify type of the token. If not in the token map, raise an error
359
+ if not self.lexoptimize:
360
+ if newtok.type not in self.lextokens_all:
361
+ raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
362
+ func.__code__.co_filename, func.__code__.co_firstlineno,
363
+ func.__name__, newtok.type), lexdata[lexpos:])
364
+
365
+ return newtok
366
+ else:
367
+ # No match, see if in literals
368
+ if lexdata[lexpos] in self.lexliterals:
369
+ tok = LexToken()
370
+ tok.value = lexdata[lexpos]
371
+ tok.lineno = self.lineno
372
+ tok.type = tok.value
373
+ tok.lexpos = lexpos
374
+ self.lexpos = lexpos + 1
375
+ return tok
376
+
377
+ # No match. Call t_error() if defined.
378
+ if self.lexerrorf:
379
+ tok = LexToken()
380
+ tok.value = self.lexdata[lexpos:]
381
+ tok.lineno = self.lineno
382
+ tok.type = 'error'
383
+ tok.lexer = self
384
+ tok.lexpos = lexpos
385
+ self.lexpos = lexpos
386
+ newtok = self.lexerrorf(tok)
387
+ if lexpos == self.lexpos:
388
+ # Error method didn't change text position at all. This is an error.
389
+ raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:])
390
+ lexpos = self.lexpos
391
+ if not newtok:
392
+ continue
393
+ return newtok
394
+
395
+ self.lexpos = lexpos
396
+ raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos], lexpos), lexdata[lexpos:])
397
+
398
+ if self.lexeoff:
399
+ tok = LexToken()
400
+ tok.type = 'eof'
401
+ tok.value = ''
402
+ tok.lineno = self.lineno
403
+ tok.lexpos = lexpos
404
+ tok.lexer = self
405
+ self.lexpos = lexpos
406
+ newtok = self.lexeoff(tok)
407
+ return newtok
408
+
409
+ self.lexpos = lexpos + 1
410
+ if self.lexdata is None:
411
+ raise RuntimeError('No input string given with input()')
412
+ return None
413
+
414
+ # Iterator interface
415
+ def __iter__(self):
416
+ return self
417
+
418
+ def next(self):
419
+ t = self.token()
420
+ if t is None:
421
+ raise StopIteration
422
+ return t
423
+
424
+ __next__ = next
425
+
426
+ # -----------------------------------------------------------------------------
427
+ # ==== Lex Builder ===
428
+ #
429
+ # The functions and classes below are used to collect lexing information
430
+ # and build a Lexer object from it.
431
+ # -----------------------------------------------------------------------------
432
+
433
+ # -----------------------------------------------------------------------------
434
+ # _get_regex(func)
435
+ #
436
+ # Returns the regular expression assigned to a function either as a doc string
437
+ # or as a .regex attribute attached by the @TOKEN decorator.
438
+ # -----------------------------------------------------------------------------
439
+ def _get_regex(func):
440
+ return getattr(func, 'regex', func.__doc__)
441
+
442
+ # -----------------------------------------------------------------------------
443
+ # get_caller_module_dict()
444
+ #
445
+ # This function returns a dictionary containing all of the symbols defined within
446
+ # a caller further down the call stack. This is used to get the environment
447
+ # associated with the yacc() call if none was provided.
448
+ # -----------------------------------------------------------------------------
449
+ def get_caller_module_dict(levels):
450
+ f = sys._getframe(levels)
451
+ ldict = f.f_globals.copy()
452
+ if f.f_globals != f.f_locals:
453
+ ldict.update(f.f_locals)
454
+ return ldict
455
+
456
+ # -----------------------------------------------------------------------------
457
+ # _funcs_to_names()
458
+ #
459
+ # Given a list of regular expression functions, this converts it to a list
460
+ # suitable for output to a table file
461
+ # -----------------------------------------------------------------------------
462
+ def _funcs_to_names(funclist, namelist):
463
+ result = []
464
+ for f, name in zip(funclist, namelist):
465
+ if f and f[0]:
466
+ result.append((name, f[1]))
467
+ else:
468
+ result.append(f)
469
+ return result
470
+
471
+ # -----------------------------------------------------------------------------
472
+ # _names_to_funcs()
473
+ #
474
+ # Given a list of regular expression function names, this converts it back to
475
+ # functions.
476
+ # -----------------------------------------------------------------------------
477
+ def _names_to_funcs(namelist, fdict):
478
+ result = []
479
+ for n in namelist:
480
+ if n and n[0]:
481
+ result.append((fdict[n[0]], n[1]))
482
+ else:
483
+ result.append(n)
484
+ return result
485
+
486
+ # -----------------------------------------------------------------------------
487
+ # _form_master_re()
488
+ #
489
+ # This function takes a list of all of the regex components and attempts to
490
+ # form the master regular expression. Given limitations in the Python re
491
+ # module, it may be necessary to break the master regex into separate expressions.
492
+ # -----------------------------------------------------------------------------
493
+ def _form_master_re(relist, reflags, ldict, toknames):
494
+ if not relist:
495
+ return []
496
+ regex = '|'.join(relist)
497
+ try:
498
+ lexre = re.compile(regex, reflags)
499
+
500
+ # Build the index to function map for the matching engine
501
+ lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1)
502
+ lexindexnames = lexindexfunc[:]
503
+
504
+ for f, i in lexre.groupindex.items():
505
+ handle = ldict.get(f, None)
506
+ if type(handle) in (types.FunctionType, types.MethodType):
507
+ lexindexfunc[i] = (handle, toknames[f])
508
+ lexindexnames[i] = f
509
+ elif handle is not None:
510
+ lexindexnames[i] = f
511
+ if f.find('ignore_') > 0:
512
+ lexindexfunc[i] = (None, None)
513
+ else:
514
+ lexindexfunc[i] = (None, toknames[f])
515
+
516
+ return [(lexre, lexindexfunc)], [regex], [lexindexnames]
517
+ except Exception:
518
+ m = int(len(relist)/2)
519
+ if m == 0:
520
+ m = 1
521
+ llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames)
522
+ rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames)
523
+ return (llist+rlist), (lre+rre), (lnames+rnames)
524
+
525
+ # -----------------------------------------------------------------------------
526
+ # def _statetoken(s,names)
527
+ #
528
+ # Given a declaration name s of the form "t_" and a dictionary whose keys are
529
+ # state names, this function returns a tuple (states,tokenname) where states
530
+ # is a tuple of state names and tokenname is the name of the token. For example,
531
+ # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
532
+ # -----------------------------------------------------------------------------
533
+ def _statetoken(s, names):
534
+ nonstate = 1
535
+ parts = s.split('_')
536
+ for i, part in enumerate(parts[1:], 1):
537
+ if part not in names and part != 'ANY':
538
+ break
539
+
540
+ if i > 1:
541
+ states = tuple(parts[1:i])
542
+ else:
543
+ states = ('INITIAL',)
544
+
545
+ if 'ANY' in states:
546
+ states = tuple(names)
547
+
548
+ tokenname = '_'.join(parts[i:])
549
+ return (states, tokenname)
550
+
551
+
552
+ # -----------------------------------------------------------------------------
553
+ # LexerReflect()
554
+ #
555
+ # This class represents information needed to build a lexer as extracted from a
556
+ # user's input file.
557
+ # -----------------------------------------------------------------------------
558
+ class LexerReflect(object):
559
+ def __init__(self, ldict, log=None, reflags=0):
560
+ self.ldict = ldict
561
+ self.error_func = None
562
+ self.tokens = []
563
+ self.reflags = reflags
564
+ self.stateinfo = {'INITIAL': 'inclusive'}
565
+ self.modules = set()
566
+ self.error = False
567
+ self.log = PlyLogger(sys.stderr) if log is None else log
568
+
569
+ # Get all of the basic information
570
+ def get_all(self):
571
+ self.get_tokens()
572
+ self.get_literals()
573
+ self.get_states()
574
+ self.get_rules()
575
+
576
+ # Validate all of the information
577
+ def validate_all(self):
578
+ self.validate_tokens()
579
+ self.validate_literals()
580
+ self.validate_rules()
581
+ return self.error
582
+
583
+ # Get the tokens map
584
+ def get_tokens(self):
585
+ tokens = self.ldict.get('tokens', None)
586
+ if not tokens:
587
+ self.log.error('No token list is defined')
588
+ self.error = True
589
+ return
590
+
591
+ if not isinstance(tokens, (list, tuple)):
592
+ self.log.error('tokens must be a list or tuple')
593
+ self.error = True
594
+ return
595
+
596
+ if not tokens:
597
+ self.log.error('tokens is empty')
598
+ self.error = True
599
+ return
600
+
601
+ self.tokens = tokens
602
+
603
+ # Validate the tokens
604
+ def validate_tokens(self):
605
+ terminals = {}
606
+ for n in self.tokens:
607
+ if not _is_identifier.match(n):
608
+ self.log.error("Bad token name '%s'", n)
609
+ self.error = True
610
+ if n in terminals:
611
+ self.log.warning("Token '%s' multiply defined", n)
612
+ terminals[n] = 1
613
+
614
+ # Get the literals specifier
615
+ def get_literals(self):
616
+ self.literals = self.ldict.get('literals', '')
617
+ if not self.literals:
618
+ self.literals = ''
619
+
620
+ # Validate literals
621
+ def validate_literals(self):
622
+ try:
623
+ for c in self.literals:
624
+ if not isinstance(c, StringTypes) or len(c) > 1:
625
+ self.log.error('Invalid literal %s. Must be a single character', repr(c))
626
+ self.error = True
627
+
628
+ except TypeError:
629
+ self.log.error('Invalid literals specification. literals must be a sequence of characters')
630
+ self.error = True
631
+
632
+ def get_states(self):
633
+ self.states = self.ldict.get('states', None)
634
+ # Build statemap
635
+ if self.states:
636
+ if not isinstance(self.states, (tuple, list)):
637
+ self.log.error('states must be defined as a tuple or list')
638
+ self.error = True
639
+ else:
640
+ for s in self.states:
641
+ if not isinstance(s, tuple) or len(s) != 2:
642
+ self.log.error("Invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')", repr(s))
643
+ self.error = True
644
+ continue
645
+ name, statetype = s
646
+ if not isinstance(name, StringTypes):
647
+ self.log.error('State name %s must be a string', repr(name))
648
+ self.error = True
649
+ continue
650
+ if not (statetype == 'inclusive' or statetype == 'exclusive'):
651
+ self.log.error("State type for state %s must be 'inclusive' or 'exclusive'", name)
652
+ self.error = True
653
+ continue
654
+ if name in self.stateinfo:
655
+ self.log.error("State '%s' already defined", name)
656
+ self.error = True
657
+ continue
658
+ self.stateinfo[name] = statetype
659
+
660
+ # Get all of the symbols with a t_ prefix and sort them into various
661
+ # categories (functions, strings, error functions, and ignore characters)
662
+
663
+ def get_rules(self):
664
+ tsymbols = [f for f in self.ldict if f[:2] == 't_']
665
+
666
+ # Now build up a list of functions and a list of strings
667
+ self.toknames = {} # Mapping of symbols to token names
668
+ self.funcsym = {} # Symbols defined as functions
669
+ self.strsym = {} # Symbols defined as strings
670
+ self.ignore = {} # Ignore strings by state
671
+ self.errorf = {} # Error functions by state
672
+ self.eoff = {} # EOF functions by state
673
+
674
+ for s in self.stateinfo:
675
+ self.funcsym[s] = []
676
+ self.strsym[s] = []
677
+
678
+ if len(tsymbols) == 0:
679
+ self.log.error('No rules of the form t_rulename are defined')
680
+ self.error = True
681
+ return
682
+
683
+ for f in tsymbols:
684
+ t = self.ldict[f]
685
+ states, tokname = _statetoken(f, self.stateinfo)
686
+ self.toknames[f] = tokname
687
+
688
+ if hasattr(t, '__call__'):
689
+ if tokname == 'error':
690
+ for s in states:
691
+ self.errorf[s] = t
692
+ elif tokname == 'eof':
693
+ for s in states:
694
+ self.eoff[s] = t
695
+ elif tokname == 'ignore':
696
+ line = t.__code__.co_firstlineno
697
+ file = t.__code__.co_filename
698
+ self.log.error("%s:%d: Rule '%s' must be defined as a string", file, line, t.__name__)
699
+ self.error = True
700
+ else:
701
+ for s in states:
702
+ self.funcsym[s].append((f, t))
703
+ elif isinstance(t, StringTypes):
704
+ if tokname == 'ignore':
705
+ for s in states:
706
+ self.ignore[s] = t
707
+ if '\\' in t:
708
+ self.log.warning("%s contains a literal backslash '\\'", f)
709
+
710
+ elif tokname == 'error':
711
+ self.log.error("Rule '%s' must be defined as a function", f)
712
+ self.error = True
713
+ else:
714
+ for s in states:
715
+ self.strsym[s].append((f, t))
716
+ else:
717
+ self.log.error('%s not defined as a function or string', f)
718
+ self.error = True
719
+
720
+ # Sort the functions by line number
721
+ for f in self.funcsym.values():
722
+ f.sort(key=lambda x: x[1].__code__.co_firstlineno)
723
+
724
+ # Sort the strings by regular expression length
725
+ for s in self.strsym.values():
726
+ s.sort(key=lambda x: len(x[1]), reverse=True)
727
+
728
+ # Validate all of the t_rules collected
729
+ def validate_rules(self):
730
+ for state in self.stateinfo:
731
+ # Validate all rules defined by functions
732
+
733
+ for fname, f in self.funcsym[state]:
734
+ line = f.__code__.co_firstlineno
735
+ file = f.__code__.co_filename
736
+ module = inspect.getmodule(f)
737
+ self.modules.add(module)
738
+
739
+ tokname = self.toknames[fname]
740
+ if isinstance(f, types.MethodType):
741
+ reqargs = 2
742
+ else:
743
+ reqargs = 1
744
+ nargs = f.__code__.co_argcount
745
+ if nargs > reqargs:
746
+ self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__)
747
+ self.error = True
748
+ continue
749
+
750
+ if nargs < reqargs:
751
+ self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__)
752
+ self.error = True
753
+ continue
754
+
755
+ if not _get_regex(f):
756
+ self.log.error("%s:%d: No regular expression defined for rule '%s'", file, line, f.__name__)
757
+ self.error = True
758
+ continue
759
+
760
+ try:
761
+ c = re.compile('(?P<%s>%s)' % (fname, _get_regex(f)), self.reflags)
762
+ if c.match(''):
763
+ self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file, line, f.__name__)
764
+ self.error = True
765
+ except re.error as e:
766
+ self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e)
767
+ if '#' in _get_regex(f):
768
+ self.log.error("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'", file, line, f.__name__)
769
+ self.error = True
770
+
771
+ # Validate all rules defined by strings
772
+ for name, r in self.strsym[state]:
773
+ tokname = self.toknames[name]
774
+ if tokname == 'error':
775
+ self.log.error("Rule '%s' must be defined as a function", name)
776
+ self.error = True
777
+ continue
778
+
779
+ if tokname not in self.tokens and tokname.find('ignore_') < 0:
780
+ self.log.error("Rule '%s' defined for an unspecified token %s", name, tokname)
781
+ self.error = True
782
+ continue
783
+
784
+ try:
785
+ c = re.compile('(?P<%s>%s)' % (name, r), self.reflags)
786
+ if (c.match('')):
787
+ self.log.error("Regular expression for rule '%s' matches empty string", name)
788
+ self.error = True
789
+ except re.error as e:
790
+ self.log.error("Invalid regular expression for rule '%s'. %s", name, e)
791
+ if '#' in r:
792
+ self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'", name)
793
+ self.error = True
794
+
795
+ if not self.funcsym[state] and not self.strsym[state]:
796
+ self.log.error("No rules defined for state '%s'", state)
797
+ self.error = True
798
+
799
+ # Validate the error function
800
+ efunc = self.errorf.get(state, None)
801
+ if efunc:
802
+ f = efunc
803
+ line = f.__code__.co_firstlineno
804
+ file = f.__code__.co_filename
805
+ module = inspect.getmodule(f)
806
+ self.modules.add(module)
807
+
808
+ if isinstance(f, types.MethodType):
809
+ reqargs = 2
810
+ else:
811
+ reqargs = 1
812
+ nargs = f.__code__.co_argcount
813
+ if nargs > reqargs:
814
+ self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__)
815
+ self.error = True
816
+
817
+ if nargs < reqargs:
818
+ self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__)
819
+ self.error = True
820
+
821
+ for module in self.modules:
822
+ self.validate_module(module)
823
+
824
+ # -----------------------------------------------------------------------------
825
+ # validate_module()
826
+ #
827
+ # This checks to see if there are duplicated t_rulename() functions or strings
828
+ # in the parser input file. This is done using a simple regular expression
829
+ # match on each line in the source code of the given module.
830
+ # -----------------------------------------------------------------------------
831
+
832
+ def validate_module(self, module):
833
+ try:
834
+ lines, linen = inspect.getsourcelines(module)
835
+ except IOError:
836
+ return
837
+
838
+ fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
839
+ sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
840
+
841
+ counthash = {}
842
+ linen += 1
843
+ for line in lines:
844
+ m = fre.match(line)
845
+ if not m:
846
+ m = sre.match(line)
847
+ if m:
848
+ name = m.group(1)
849
+ prev = counthash.get(name)
850
+ if not prev:
851
+ counthash[name] = linen
852
+ else:
853
+ filename = inspect.getsourcefile(module)
854
+ self.log.error('%s:%d: Rule %s redefined. Previously defined on line %d', filename, linen, name, prev)
855
+ self.error = True
856
+ linen += 1
857
+
858
+ # -----------------------------------------------------------------------------
859
+ # lex(module)
860
+ #
861
+ # Build all of the regular expression rules from definitions in the supplied module
862
+ # -----------------------------------------------------------------------------
863
+ def lex(module=None, object=None, debug=False, optimize=False, lextab='lextab',
864
+ reflags=int(re.VERBOSE), nowarn=False, outputdir=None, debuglog=None, errorlog=None):
865
+
866
+ if lextab is None:
867
+ lextab = 'lextab'
868
+
869
+ global lexer
870
+
871
+ ldict = None
872
+ stateinfo = {'INITIAL': 'inclusive'}
873
+ lexobj = Lexer()
874
+ lexobj.lexoptimize = optimize
875
+ global token, input
876
+
877
+ if errorlog is None:
878
+ errorlog = PlyLogger(sys.stderr)
879
+
880
+ if debug:
881
+ if debuglog is None:
882
+ debuglog = PlyLogger(sys.stderr)
883
+
884
+ # Get the module dictionary used for the lexer
885
+ if object:
886
+ module = object
887
+
888
+ # Get the module dictionary used for the parser
889
+ if module:
890
+ _items = [(k, getattr(module, k)) for k in dir(module)]
891
+ ldict = dict(_items)
892
+ # If no __file__ attribute is available, try to obtain it from the __module__ instead
893
+ if '__file__' not in ldict:
894
+ ldict['__file__'] = sys.modules[ldict['__module__']].__file__
895
+ else:
896
+ ldict = get_caller_module_dict(2)
897
+
898
+ # Determine if the module is package of a package or not.
899
+ # If so, fix the tabmodule setting so that tables load correctly
900
+ pkg = ldict.get('__package__')
901
+ if pkg and isinstance(lextab, str):
902
+ if '.' not in lextab:
903
+ lextab = pkg + '.' + lextab
904
+
905
+ # Collect parser information from the dictionary
906
+ linfo = LexerReflect(ldict, log=errorlog, reflags=reflags)
907
+ linfo.get_all()
908
+ if not optimize:
909
+ if linfo.validate_all():
910
+ raise SyntaxError("Can't build lexer")
911
+
912
+ if optimize and lextab:
913
+ try:
914
+ lexobj.readtab(lextab, ldict)
915
+ token = lexobj.token
916
+ input = lexobj.input
917
+ lexer = lexobj
918
+ return lexobj
919
+
920
+ except ImportError:
921
+ pass
922
+
923
+ # Dump some basic debugging information
924
+ if debug:
925
+ debuglog.info('lex: tokens = %r', linfo.tokens)
926
+ debuglog.info('lex: literals = %r', linfo.literals)
927
+ debuglog.info('lex: states = %r', linfo.stateinfo)
928
+
929
+ # Build a dictionary of valid token names
930
+ lexobj.lextokens = set()
931
+ for n in linfo.tokens:
932
+ lexobj.lextokens.add(n)
933
+
934
+ # Get literals specification
935
+ if isinstance(linfo.literals, (list, tuple)):
936
+ lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals)
937
+ else:
938
+ lexobj.lexliterals = linfo.literals
939
+
940
+ lexobj.lextokens_all = lexobj.lextokens | set(lexobj.lexliterals)
941
+
942
+ # Get the stateinfo dictionary
943
+ stateinfo = linfo.stateinfo
944
+
945
+ regexs = {}
946
+ # Build the master regular expressions
947
+ for state in stateinfo:
948
+ regex_list = []
949
+
950
+ # Add rules defined by functions first
951
+ for fname, f in linfo.funcsym[state]:
952
+ line = f.__code__.co_firstlineno
953
+ file = f.__code__.co_filename
954
+ regex_list.append('(?P<%s>%s)' % (fname, _get_regex(f)))
955
+ if debug:
956
+ debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", fname, _get_regex(f), state)
957
+
958
+ # Now add all of the simple rules
959
+ for name, r in linfo.strsym[state]:
960
+ regex_list.append('(?P<%s>%s)' % (name, r))
961
+ if debug:
962
+ debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", name, r, state)
963
+
964
+ regexs[state] = regex_list
965
+
966
+ # Build the master regular expressions
967
+
968
+ if debug:
969
+ debuglog.info('lex: ==== MASTER REGEXS FOLLOW ====')
970
+
971
+ for state in regexs:
972
+ lexre, re_text, re_names = _form_master_re(regexs[state], reflags, ldict, linfo.toknames)
973
+ lexobj.lexstatere[state] = lexre
974
+ lexobj.lexstateretext[state] = re_text
975
+ lexobj.lexstaterenames[state] = re_names
976
+ if debug:
977
+ for i, text in enumerate(re_text):
978
+ debuglog.info("lex: state '%s' : regex[%d] = '%s'", state, i, text)
979
+
980
+ # For inclusive states, we need to add the regular expressions from the INITIAL state
981
+ for state, stype in stateinfo.items():
982
+ if state != 'INITIAL' and stype == 'inclusive':
983
+ lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL'])
984
+ lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL'])
985
+ lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL'])
986
+
987
+ lexobj.lexstateinfo = stateinfo
988
+ lexobj.lexre = lexobj.lexstatere['INITIAL']
989
+ lexobj.lexretext = lexobj.lexstateretext['INITIAL']
990
+ lexobj.lexreflags = reflags
991
+
992
+ # Set up ignore variables
993
+ lexobj.lexstateignore = linfo.ignore
994
+ lexobj.lexignore = lexobj.lexstateignore.get('INITIAL', '')
995
+
996
+ # Set up error functions
997
+ lexobj.lexstateerrorf = linfo.errorf
998
+ lexobj.lexerrorf = linfo.errorf.get('INITIAL', None)
999
+ if not lexobj.lexerrorf:
1000
+ errorlog.warning('No t_error rule is defined')
1001
+
1002
+ # Set up eof functions
1003
+ lexobj.lexstateeoff = linfo.eoff
1004
+ lexobj.lexeoff = linfo.eoff.get('INITIAL', None)
1005
+
1006
+ # Check state information for ignore and error rules
1007
+ for s, stype in stateinfo.items():
1008
+ if stype == 'exclusive':
1009
+ if s not in linfo.errorf:
1010
+ errorlog.warning("No error rule is defined for exclusive state '%s'", s)
1011
+ if s not in linfo.ignore and lexobj.lexignore:
1012
+ errorlog.warning("No ignore rule is defined for exclusive state '%s'", s)
1013
+ elif stype == 'inclusive':
1014
+ if s not in linfo.errorf:
1015
+ linfo.errorf[s] = linfo.errorf.get('INITIAL', None)
1016
+ if s not in linfo.ignore:
1017
+ linfo.ignore[s] = linfo.ignore.get('INITIAL', '')
1018
+
1019
+ # Create global versions of the token() and input() functions
1020
+ token = lexobj.token
1021
+ input = lexobj.input
1022
+ lexer = lexobj
1023
+
1024
+ # If in optimize mode, we write the lextab
1025
+ if lextab and optimize:
1026
+ if outputdir is None:
1027
+ # If no output directory is set, the location of the output files
1028
+ # is determined according to the following rules:
1029
+ # - If lextab specifies a package, files go into that package directory
1030
+ # - Otherwise, files go in the same directory as the specifying module
1031
+ if isinstance(lextab, types.ModuleType):
1032
+ srcfile = lextab.__file__
1033
+ else:
1034
+ if '.' not in lextab:
1035
+ srcfile = ldict['__file__']
1036
+ else:
1037
+ parts = lextab.split('.')
1038
+ pkgname = '.'.join(parts[:-1])
1039
+ exec('import %s' % pkgname)
1040
+ srcfile = getattr(sys.modules[pkgname], '__file__', '')
1041
+ outputdir = os.path.dirname(srcfile)
1042
+ try:
1043
+ lexobj.writetab(lextab, outputdir)
1044
+ except IOError as e:
1045
+ errorlog.warning("Couldn't write lextab module %r. %s" % (lextab, e))
1046
+
1047
+ return lexobj
1048
+
1049
+ # -----------------------------------------------------------------------------
1050
+ # runmain()
1051
+ #
1052
+ # This runs the lexer as a main program
1053
+ # -----------------------------------------------------------------------------
1054
+
1055
+ def runmain(lexer=None, data=None):
1056
+ if not data:
1057
+ try:
1058
+ filename = sys.argv[1]
1059
+ f = open(filename)
1060
+ data = f.read()
1061
+ f.close()
1062
+ except IndexError:
1063
+ sys.stdout.write('Reading from standard input (type EOF to end):\n')
1064
+ data = sys.stdin.read()
1065
+
1066
+ if lexer:
1067
+ _input = lexer.input
1068
+ else:
1069
+ _input = input
1070
+ _input(data)
1071
+ if lexer:
1072
+ _token = lexer.token
1073
+ else:
1074
+ _token = token
1075
+
1076
+ while True:
1077
+ tok = _token()
1078
+ if not tok:
1079
+ break
1080
+ sys.stdout.write('(%s,%r,%d,%d)\n' % (tok.type, tok.value, tok.lineno, tok.lexpos))
1081
+
1082
+ # -----------------------------------------------------------------------------
1083
+ # @TOKEN(regex)
1084
+ #
1085
+ # This decorator function can be used to set the regex expression on a function
1086
+ # when its docstring might need to be set in an alternative way
1087
+ # -----------------------------------------------------------------------------
1088
+
1089
+ def TOKEN(r):
1090
+ def set_regex(f):
1091
+ if hasattr(r, '__call__'):
1092
+ f.regex = _get_regex(r)
1093
+ else:
1094
+ f.regex = r
1095
+ return f
1096
+ return set_regex
1097
+
1098
+ # Alternative spelling of the TOKEN decorator
1099
+ Token = TOKEN
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/yacc.py ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pycparser/ply/ygen.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ply: ygen.py
2
+ #
3
+ # This is a support program that auto-generates different versions of the YACC parsing
4
+ # function with different features removed for the purposes of performance.
5
+ #
6
+ # Users should edit the method LParser.parsedebug() in yacc.py. The source code
7
+ # for that method is then used to create the other methods. See the comments in
8
+ # yacc.py for further details.
9
+
10
+ import os.path
11
+ import shutil
12
+
13
+ def get_source_range(lines, tag):
14
+ srclines = enumerate(lines)
15
+ start_tag = '#--! %s-start' % tag
16
+ end_tag = '#--! %s-end' % tag
17
+
18
+ for start_index, line in srclines:
19
+ if line.strip().startswith(start_tag):
20
+ break
21
+
22
+ for end_index, line in srclines:
23
+ if line.strip().endswith(end_tag):
24
+ break
25
+
26
+ return (start_index + 1, end_index)
27
+
28
+ def filter_section(lines, tag):
29
+ filtered_lines = []
30
+ include = True
31
+ tag_text = '#--! %s' % tag
32
+ for line in lines:
33
+ if line.strip().startswith(tag_text):
34
+ include = not include
35
+ elif include:
36
+ filtered_lines.append(line)
37
+ return filtered_lines
38
+
39
+ def main():
40
+ dirname = os.path.dirname(__file__)
41
+ shutil.copy2(os.path.join(dirname, 'yacc.py'), os.path.join(dirname, 'yacc.py.bak'))
42
+ with open(os.path.join(dirname, 'yacc.py'), 'r') as f:
43
+ lines = f.readlines()
44
+
45
+ parse_start, parse_end = get_source_range(lines, 'parsedebug')
46
+ parseopt_start, parseopt_end = get_source_range(lines, 'parseopt')
47
+ parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack')
48
+
49
+ # Get the original source
50
+ orig_lines = lines[parse_start:parse_end]
51
+
52
+ # Filter the DEBUG sections out
53
+ parseopt_lines = filter_section(orig_lines, 'DEBUG')
54
+
55
+ # Filter the TRACKING sections out
56
+ parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING')
57
+
58
+ # Replace the parser source sections with updated versions
59
+ lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines
60
+ lines[parseopt_start:parseopt_end] = parseopt_lines
61
+
62
+ lines = [line.rstrip()+'\n' for line in lines]
63
+ with open(os.path.join(dirname, 'yacc.py'), 'w') as f:
64
+ f.writelines(lines)
65
+
66
+ print('Updated yacc.py')
67
+
68
+ if __name__ == '__main__':
69
+ main()
70
+
71
+
72
+
73
+
74
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/San_Juan ADDED
Binary file (1.09 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/San_Luis ADDED
Binary file (1.1 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/Tucuman ADDED
Binary file (1.1 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia ADDED
Binary file (1.08 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis ADDED
Binary file (1.67 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/America/Indiana/Knox ADDED
Binary file (2.43 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Mountain ADDED
Binary file (2.39 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Newfoundland ADDED
Binary file (3.66 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Pacific ADDED
Binary file (2.89 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Saskatchewan ADDED
Binary file (980 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Canada/Yukon ADDED
Binary file (2.08 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Chile/Continental ADDED
Binary file (2.53 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Chile/EasterIsland ADDED
Binary file (2.23 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT ADDED
Binary file (114 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+0 ADDED
Binary file (114 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+1 ADDED
Binary file (116 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+10 ADDED
Binary file (117 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+11 ADDED
Binary file (117 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT+12 ADDED
Binary file (117 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT-7 ADDED
Binary file (117 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Etc/GMT-8 ADDED
Binary file (117 Bytes). View file