├── .gitignore ├── .idea ├── artifacts │ └── ACHelper_jar.xml ├── codeStyleSettings.xml ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── kotlinc.xml ├── libraries │ ├── chelper.xml │ ├── commons_lang_2_6.xml │ ├── jackson_annotations_2_7_0.xml │ ├── jackson_core_2_7_4.xml │ └── openapi_7_0_3.xml ├── misc.xml ├── modules.xml ├── uiDesigner.xml ├── vcs.xml └── xcode.xml ├── ACHelper.iml ├── ACHelper.xml ├── LICENSE ├── README.md ├── TestLinks.txt ├── lib ├── chelper.jar ├── commons-lang-2.6.jar ├── jackson-annotations-2.7.0.jar ├── jackson-core-2.7.4.jar ├── jackson-databind-2.7.4.jar └── openapi-7.0.3.jar ├── scripts └── launcher.sh ├── src ├── META-INF │ └── MANIFEST.MF └── ua │ └── alcash │ ├── Configuration.java │ ├── Problem.java │ ├── TestCase.java │ ├── filesystem │ ├── Generator.java │ ├── ProblemSync.java │ └── WorkspaceManager.java │ ├── network │ └── ChromeListener.java │ ├── parsing │ └── ParseManager.java │ ├── ui │ ├── MainFrame.form │ ├── MainFrame.java │ ├── MultilineTableCellRenderer.java │ ├── NewContestDialog.form │ ├── NewContestDialog.java │ ├── NewProblemDialog.form │ ├── NewProblemDialog.java │ ├── ProblemPanel.form │ ├── ProblemPanel.java │ ├── TestCaseDialog.form │ ├── TestCaseDialog.java │ └── TestsTableModel.java │ └── util │ └── AbstractActionWithInteger.java └── templates ├── checker.cpp ├── cpp ├── CMakeLists.txt ├── CMakeScripts.txt ├── main.cpp ├── problem_limits.cpp ├── problem_limits.h ├── solution.h ├── source_multi_eof.cpp ├── source_multi_number.cpp ├── source_single.cpp └── tester.cpp └── default_checker.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/workspace.xml 2 | .idea/tasks.xml 3 | out 4 | templates/testlib.h 5 | -------------------------------------------------------------------------------- /.idea/artifacts/ACHelper_jar.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | $PROJECT_DIR$/out/artifacts/ACHelper_jar 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 13 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/libraries/chelper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/libraries/commons_lang_2_6.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/libraries/jackson_annotations_2_7_0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/libraries/jackson_core_2_7_4.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/libraries/openapi_7_0_3.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/xcode.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /ACHelper.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /ACHelper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ACHelper configuration file 5 | 6 | AtCoder 7 | CodeChef 8 | Codeforces 9 | CS Academy 10 | Facebook Hacker Cup 11 | Google Code Jam 12 | HackerEarth 13 | HackerRank 14 | Kattis 15 | Google Code Jam New 16 | Russian Code Cup 17 | Timus 18 | USACO 19 | Yandex Algorithm 20 | 21 | ctrl C 22 | ctrl P 23 | ctrl A 24 | ctrl D 25 | ctrl W 26 | ctrl T 27 | ctrl E 28 | DELETE 29 | ctrl S 30 | ctrl Q 31 | 32 | 4243 33 | 34 | @problem_id@ 35 | 2 36 | 256 37 | -std=c++11 -O2 -DEPSILON=1e-9 -DABSOLUTE -DRELATIVE 38 | 39 | sample 40 | manual 41 | tests 42 | 10000 43 | 100 44 | 8 45 | 46 | in 47 | ans 48 | out 49 | 50 | # problems 51 | templates/cpp/CMakeScripts.txt 52 | /usr/local/bin/cmake -DRELEASE_DIR=Project/RelWithDebInfo -P CMakeScripts.txt 53 | templates/cpp/CMakeLists.txt 54 | /usr/local/bin/cmake -B Project -G Xcode 55 | 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **ACHelper** is a competitive programming tool. Check [wiki](https://github.com/AlCash07/ACHelper/wiki) for more information. 2 | -------------------------------------------------------------------------------- /TestLinks.txt: -------------------------------------------------------------------------------- 1 | c = works from Chrome extension only 2 | 3 | + http://agc015.contest.atcoder.jp/tasks/agc015_f 4 | - https://www.codechef.com/problems/INTERVAL 5 | + http://codeforces.com/problemset/problem/484/E 6 | - https://csacademy.com/contest/archive/task/addition/ 7 | + https://www.facebook.com/hackercup/problem/1703546573272198/ 8 | c https://code.google.com/codejam/contest/8304486/dashboard 9 | c https://www.hackerearth.com/challenge/test/indiahacks-algorithm-finals/algorithm/2103dcc3b35e421cbec9aee15d71e6cd/ 10 | - https://www.hackerrank.com/challenges/a-very-big-sum 11 | c https://www.hackerrank.com/contests/world-codesprint-8/challenges/snake-case 12 | + https://open.kattis.com/problems/fizzbuzz 13 | + http://www.russiancodecup.ru/en/championship/round/59/ 14 | c http://www.usaco.org/index.php?page=viewproblem2&cpid=744 15 | c https://contest.yandex.com/algorithm2017/contest/4598/problems/F/ 16 | -------------------------------------------------------------------------------- /lib/chelper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/chelper.jar -------------------------------------------------------------------------------- /lib/commons-lang-2.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/commons-lang-2.6.jar -------------------------------------------------------------------------------- /lib/jackson-annotations-2.7.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/jackson-annotations-2.7.0.jar -------------------------------------------------------------------------------- /lib/jackson-core-2.7.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/jackson-core-2.7.4.jar -------------------------------------------------------------------------------- /lib/jackson-databind-2.7.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/jackson-databind-2.7.4.jar -------------------------------------------------------------------------------- /lib/openapi-7.0.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlCash07/ACHelper/eb649fb0f6c1bb70b8211ed29af5ad95d4be75e2/lib/openapi-7.0.3.jar -------------------------------------------------------------------------------- /scripts/launcher.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | "$@" > /dev/null 2>&1 & 4 | -------------------------------------------------------------------------------- /src/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: ua.alcash.ui.MainFrame 3 | 4 | -------------------------------------------------------------------------------- /src/ua/alcash/Configuration.java: -------------------------------------------------------------------------------- 1 | package ua.alcash; 2 | 3 | import javax.swing.*; 4 | import java.io.FileInputStream; 5 | import java.util.Properties; 6 | 7 | /** 8 | * Created by Al.Cash on 5/8/17. 9 | */ 10 | public class Configuration { 11 | static final public String PROJECT_NAME = "ACHelper"; 12 | 13 | static final public String CONFIGURATION_FILE_NAME = PROJECT_NAME + ".xml"; 14 | 15 | static private Properties properties; 16 | 17 | static public String get(String key) { return properties.getProperty(key); } 18 | 19 | static public KeyStroke getShortcut(String action) { return KeyStroke.getKeyStroke(get("shortcut " + action)); } 20 | 21 | static public String getPlatform(String key) { return get("platform " + key); } 22 | 23 | static public String getExtension(String key) { return get("extension " + key); } 24 | 25 | static public boolean load(String workspaceDirectory) { 26 | try { 27 | FileInputStream input = new FileInputStream( 28 | workspaceDirectory + java.io.File.separator + CONFIGURATION_FILE_NAME); 29 | Properties loadedProperties = new Properties(); 30 | loadedProperties.loadFromXML(input); 31 | properties = loadedProperties; 32 | return true; 33 | } catch (Throwable exception) { 34 | return false; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/ua/alcash/Problem.java: -------------------------------------------------------------------------------- 1 | package ua.alcash; 2 | 3 | import net.egork.chelper.task.StreamConfiguration; 4 | import net.egork.chelper.task.Task; 5 | import net.egork.chelper.task.TestType; 6 | import ua.alcash.parsing.ParseManager; 7 | 8 | import java.util.ArrayList; 9 | 10 | /** 11 | * Created by Al.Cash on 5/8/17. 12 | */ 13 | public class Problem { 14 | private static double defaultTimeLimit; 15 | private static double defaultMemoryLimit; 16 | private static String defaultCheckerParams; 17 | private static String sampleTestName; 18 | 19 | static public void configure() { 20 | defaultTimeLimit = Double.parseDouble(Configuration.get("default time limit")); 21 | defaultMemoryLimit = Double.parseDouble(Configuration.get("default memory limit")); 22 | defaultCheckerParams = Configuration.get("default checker compiler options"); 23 | sampleTestName = Configuration.get("test sample"); 24 | } 25 | 26 | private String problemId; 27 | private String problemName; 28 | private String platformId; 29 | private String contestName; 30 | 31 | private double timeLimit = defaultTimeLimit; 32 | private double memoryLimit = defaultMemoryLimit; 33 | 34 | private String inputFile = ""; 35 | private String outputFile = ""; 36 | 37 | private TestType testType = TestType.SINGLE; 38 | 39 | private boolean interactive = false; 40 | private boolean customChecker = false; 41 | private String checkerParams = defaultCheckerParams; 42 | 43 | private ArrayList testCases = new ArrayList<>(); 44 | 45 | private static final int timeLimitBit = 0; 46 | private static final int memoryLimitBit = 1; 47 | private static final int inputFileBit = 2; 48 | private static final int outputFileBit = 3; 49 | private static final int testTypeBit = 4; 50 | private static final int interactiveBit = 5; 51 | private static final int customCheckerBit = 6; 52 | private static final int checkerParamsBit = 7; 53 | 54 | private int changesMask = (1 << 8) - 1; 55 | 56 | public Problem(String problemId, String problemName, String platformId, String contestName) { 57 | this.problemId = problemId; 58 | this.problemName = problemName; 59 | this.platformId = platformId; 60 | this.contestName = contestName; 61 | } 62 | 63 | public Problem(String platformId, Task task) { 64 | problemId = task.taskClass; 65 | if (problemId.startsWith("Task")) { 66 | problemId = problemId.substring(4); 67 | } 68 | problemName = task.name; 69 | this.platformId = platformId; 70 | contestName = task.contestName; 71 | if (contestName == null) contestName = ""; 72 | 73 | // for GCJ and FHC ignore the file name, because the program is executed only locally 74 | if (task.input.type != StreamConfiguration.StreamType.LOCAL_REGEXP) { 75 | if (task.input.fileName != null) inputFile = task.input.fileName; 76 | if (task.output.fileName != null) outputFile = task.output.fileName; 77 | } 78 | if (task.testType != null) testType = task.testType; 79 | 80 | for (int i = 0; i < task.tests.length; ++i) { 81 | String testName = sampleTestName + (i + 1); 82 | testCases.add(new TestCase(testName, task.tests[i].input, task.tests[i].output)); 83 | } 84 | } 85 | 86 | public String getValue(String key, boolean nameOnly) { 87 | switch (key) { 88 | case "problem_id": 89 | return problemId; 90 | case "problem_name": 91 | return problemName; 92 | case "platform_id": 93 | return platformId; 94 | case "platform_name": 95 | return ParseManager.getPlatformName(platformId); 96 | case "contest_name": 97 | return contestName; 98 | } 99 | if (nameOnly) return Configuration.get(key); 100 | switch (key) { 101 | case "time_limit": 102 | return String.valueOf(timeLimit); 103 | case "memory_limit": 104 | return String.valueOf(memoryLimit); 105 | case "input_file_name": 106 | return inputFile; 107 | case "output_file_name": 108 | return outputFile; 109 | case "test_type": 110 | switch (testType) { 111 | case SINGLE: 112 | return "single"; 113 | case MULTI_NUMBER: 114 | return "multi_number"; 115 | case MULTI_EOF: 116 | return "multi_eof"; 117 | } 118 | case "interactive": 119 | return String.valueOf(interactive); 120 | case "custom_checker": 121 | return String.valueOf(customChecker); 122 | case "checker_compiler_options": 123 | return checkerParams; 124 | case "time_limit_changed": 125 | return String.valueOf((changesMask >> timeLimitBit & 1) > 0); 126 | case "memory_limit_changed": 127 | return String.valueOf((changesMask >> memoryLimitBit & 1) > 0); 128 | case "input_file_name_changed": 129 | return String.valueOf((changesMask >> inputFileBit & 1) > 0); 130 | case "output_file_name_changed": 131 | return String.valueOf((changesMask >> outputFileBit & 1) > 0); 132 | case "test_type_changed": 133 | return String.valueOf((changesMask >> testTypeBit & 1) > 0); 134 | case "interactive_changed": 135 | return String.valueOf((changesMask >> interactiveBit & 1) > 0); 136 | case "custom_checker_changed": 137 | return String.valueOf((changesMask >> customCheckerBit & 1) > 0); 138 | case "checker_compiler_options_changed": 139 | return String.valueOf((changesMask >> checkerParamsBit & 1) > 0); 140 | default: 141 | return Configuration.get(key); 142 | } 143 | } 144 | 145 | public String getId() { return problemId; } 146 | 147 | public String getFullName() { 148 | String name = (problemName != null && !problemName.isEmpty()) ? problemName : problemId; 149 | return contestName + " " + name; 150 | } 151 | 152 | public double getTimeLimit() { return timeLimit; } 153 | public void setTimeLimit(double value) { 154 | if (timeLimit != value) changesMask |= 1 << timeLimitBit; 155 | timeLimit = value; 156 | } 157 | 158 | public double getMemoryLimit() { return memoryLimit; } 159 | public void setMemoryLimit(double value) { 160 | if (memoryLimit != value) changesMask |= 1 << memoryLimitBit; 161 | memoryLimit = value; 162 | } 163 | 164 | public String getInputFile() { return inputFile; } 165 | public void setInputFile(String value) { 166 | if (!inputFile.equals(value)) changesMask |= 1 << inputFileBit; 167 | inputFile = value; 168 | } 169 | 170 | public String getOutputFile() { return outputFile; } 171 | public void setOutputFile(String value) { 172 | if (!outputFile.equals(value)) changesMask |= 1 << outputFileBit; 173 | outputFile = value; 174 | } 175 | 176 | public TestType getTestType() { return testType; } 177 | public void setTestType(TestType value) { 178 | if (testType != value) changesMask |= 1 << testTypeBit; 179 | testType = value; 180 | } 181 | 182 | public boolean getInteractive() { return interactive; } 183 | public void setInteractive(boolean value) { 184 | if (interactive != value) changesMask |= 1 << interactiveBit; 185 | interactive = value; 186 | } 187 | 188 | public boolean getCustomChecker() { return customChecker; } 189 | public void setCustomChecker(boolean value) { 190 | if (customChecker != value) changesMask |= 1 << customCheckerBit; 191 | customChecker = value; 192 | } 193 | 194 | public String getCheckerParams() { return checkerParams; } 195 | public void setCheckerParams(String value) { 196 | if (!checkerParams.equals(value)) changesMask |= 1 << checkerParamsBit; 197 | checkerParams = value; 198 | } 199 | 200 | public ArrayList getTestCaseSet() { return testCases; } 201 | 202 | public boolean projectRegenerationRequired() { 203 | return (changesMask & (1 << interactiveBit | 1 << customCheckerBit)) > 0 204 | || (customChecker && (changesMask & (1 << checkerParamsBit)) > 0); 205 | } 206 | 207 | public void markUnchanged() { changesMask = 0; } 208 | } 209 | -------------------------------------------------------------------------------- /src/ua/alcash/TestCase.java: -------------------------------------------------------------------------------- 1 | package ua.alcash; 2 | 3 | /** 4 | * Created by Al.Cash on 5/8/17. 5 | */ 6 | public class TestCase { 7 | private final static String UNKNOWN_KEY = "UNKNOWN"; 8 | private final static String SKIPPED_KEY = "SKIPPED"; 9 | private final static String RUNNING_KEY = "RUNNING"; 10 | 11 | private String name; 12 | private String input = ""; 13 | private String expectedOutput = ""; 14 | private String programOutput = ""; 15 | private String[] executionResults = new String[] {UNKNOWN_KEY}; 16 | 17 | public TestCase(String name) { this.name = name; } 18 | 19 | public TestCase(String name, String input, String output) { 20 | this.name = name; 21 | this.input = input; 22 | this.expectedOutput = output; 23 | } 24 | 25 | public String getName() { return name; } 26 | 27 | public String getInput() { return input; } 28 | public void setInput(String value) { input = value; } 29 | 30 | public String getExpectedOutput() { return expectedOutput; } 31 | public void setExpectedOutput(String value) { expectedOutput = value; } 32 | 33 | public String getProgramOutput() { return programOutput; } 34 | public void setProgramOutput(String value) { programOutput = value; } 35 | 36 | public String getExecutionResults(String delimiter) { return String.join(delimiter, executionResults); } 37 | public void setExecutionResults(String value) { executionResults = value.split(" ", 2); } 38 | 39 | public void flipSkipped() { 40 | if (executionResults.length == 1 && executionResults[0].equals(SKIPPED_KEY)) { 41 | executionResults[0] = UNKNOWN_KEY; 42 | } else { 43 | executionResults = new String[] {SKIPPED_KEY}; 44 | } 45 | } 46 | 47 | public boolean isRunning() { return executionResults.length == 1 && executionResults[0].equals(RUNNING_KEY); } 48 | } 49 | -------------------------------------------------------------------------------- /src/ua/alcash/filesystem/Generator.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.filesystem; 2 | 3 | import ua.alcash.Configuration; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.nio.file.Paths; 10 | import java.util.ArrayList; 11 | import java.util.Collection; 12 | import java.util.List; 13 | import java.util.Scanner; 14 | 15 | /** 16 | * Created by Al.Cash on 5/23/17. 17 | */ 18 | class Generator { 19 | static void generate(String directory, Collection problemSyncs, boolean project) throws IOException { 20 | if (!project) { 21 | for (ProblemSync problemSync : problemSyncs) { 22 | project = project || problemSync.projectRegenerationRequired(); 23 | } 24 | } 25 | configureFile(directory, Configuration.get("generate files template"), problemSyncs); 26 | executeCommand(directory, Configuration.get("generate files command")); 27 | if (project) { 28 | configureFile(directory, Configuration.get("generate project template"), problemSyncs); 29 | executeCommand(directory, Configuration.get("generate project command")); 30 | } 31 | for (ProblemSync problemSync : problemSyncs) { 32 | problemSync.markUnchanged(); 33 | } 34 | } 35 | 36 | private static void configureFile(String directory, String templatePath, Collection problemSyncs) 37 | throws IOException { 38 | String delimiter = Configuration.get("problems delimiter"); 39 | Path inputPath = Paths.get(templatePath); 40 | Path outputPath = Paths.get(directory, inputPath.getFileName().toString()); 41 | try { 42 | List inputLines = Files.readAllLines(inputPath); 43 | ArrayList outputLines = new ArrayList<>(); 44 | for (int i = 0; i < inputLines.size(); ++i) { 45 | if (inputLines.get(i).equals(delimiter)) { 46 | ++i; 47 | int last = i; 48 | while (last < inputLines.size() && !inputLines.get(last).equals(delimiter)) { 49 | ++last; 50 | } 51 | for (ProblemSync problemSync : problemSyncs) { 52 | for (int j = i; j < last; ++j) { 53 | outputLines.add(problemSync.substituteKeys(inputLines.get(j), false)); 54 | } 55 | } 56 | i = last; 57 | } else { 58 | String[] tokens = inputLines.get(i).split("@"); 59 | for (int j = 1; j < tokens.length; j += 2) { 60 | tokens[j] = Configuration.get(tokens[j]); 61 | } 62 | outputLines.add(String.join("", tokens)); 63 | } 64 | } 65 | Files.write(outputPath, outputLines); 66 | } catch (IOException exception) { 67 | throw new IOException(outputPath.getFileName() + " file generation failed:\n" + exception.getMessage()); 68 | } 69 | } 70 | 71 | private static void executeCommand(String directory, String command) throws IOException { 72 | Runtime runtime = Runtime.getRuntime(); 73 | Process process = runtime.exec(command, null, new File(directory)); 74 | Scanner outScanner = new Scanner(process.getInputStream()).useDelimiter("\\A"); 75 | System.out.println(outScanner.hasNext() ? outScanner.next() : ""); 76 | Scanner errScanner = new Scanner(process.getErrorStream()).useDelimiter("\\A"); 77 | System.err.println(errScanner.hasNext() ? errScanner.next() : ""); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/ua/alcash/filesystem/ProblemSync.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.filesystem; 2 | 3 | import ua.alcash.Configuration; 4 | import ua.alcash.Problem; 5 | import ua.alcash.TestCase; 6 | import ua.alcash.ui.TestsTableModel; 7 | 8 | import javax.swing.table.AbstractTableModel; 9 | import java.io.BufferedReader; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.nio.charset.StandardCharsets; 13 | import java.nio.file.*; 14 | import java.nio.file.attribute.BasicFileAttributes; 15 | import java.util.*; 16 | 17 | import static java.nio.file.Files.newBufferedReader; 18 | import static java.nio.file.StandardWatchEventKinds.*; 19 | 20 | /** 21 | * Created by Al.Cash on 5/25/17. 22 | */ 23 | public class ProblemSync { 24 | private static String testListFileName; 25 | private static String inputExtension; 26 | private static String expectedOutputExtension; 27 | private static String programOutputExtension; 28 | private static String manualTestName; 29 | private static int maxLength; 30 | 31 | private Problem problem; 32 | private String directory; 33 | 34 | private ArrayList testCases; 35 | private Set testCaseNames = new HashSet<>(); 36 | private int manualTestIndex = 1; 37 | 38 | private TestsTableModel testsTableModel; // used to notify testsTable about the testCaseSet changes 39 | private boolean testSetChanged = true; 40 | 41 | private final Set modifiedFiles = new HashSet<>(); 42 | 43 | private boolean testsAreRunning = false; 44 | 45 | ProblemSync(String workspaceDirectory, Problem problem) { 46 | this.problem = problem; 47 | directory = Paths.get(workspaceDirectory, 48 | substituteKeys(Configuration.get("problem directory"), true)).toString(); 49 | testCases = problem.getTestCaseSet(); 50 | testsTableModel = new TestsTableModel(testCases); 51 | for (TestCase testCase : testCases) { 52 | testCaseNames.add(testCase.getName()); 53 | } 54 | } 55 | 56 | void initialize() throws IOException { 57 | Path problemPath = Paths.get(directory); 58 | Files.createDirectories(problemPath); 59 | for (int i = 0; i < testCases.size(); ++i) { 60 | createTestCaseFiles(i); 61 | } 62 | // add existing test cases from the disk 63 | Files.walkFileTree(problemPath, new SimpleFileVisitor() { 64 | @Override 65 | public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { 66 | String fileName = path.getFileName().toString(); 67 | if (fileName.endsWith(inputExtension)) { 68 | String testName = fileName.substring(0, fileName.lastIndexOf(".")); 69 | if (!testCaseNames.contains(testName)) { 70 | addTestCaseFromDisk(testName); 71 | } 72 | } 73 | return FileVisitResult.CONTINUE; 74 | } 75 | }); 76 | testsListChanged(); 77 | modifiedFiles.clear(); 78 | } 79 | 80 | static void configure() { 81 | Problem.configure(); 82 | testListFileName = Configuration.get("test list file"); 83 | inputExtension = "." + Configuration.getExtension("input"); 84 | expectedOutputExtension = "." + Configuration.getExtension("expected output"); 85 | programOutputExtension = "." + Configuration.getExtension("program output"); 86 | manualTestName = Configuration.get("test manual"); 87 | maxLength = Integer.parseInt(Configuration.get("test maximum loaded length")); 88 | } 89 | 90 | public Problem getProblem() { return problem; } 91 | 92 | public String getDirectory() { return directory; } 93 | 94 | public AbstractTableModel getTableModel() { return testsTableModel; } 95 | 96 | public TestCase getTestCase(int index) { return testCases.get(index); } 97 | 98 | public String getNextTestName() { 99 | while (testCaseNames.contains(manualTestName + manualTestIndex)) { 100 | ++manualTestIndex; 101 | } 102 | return manualTestName + manualTestIndex; 103 | } 104 | 105 | public void addTestCase(TestCase testCase, boolean createFiles) throws IOException { 106 | checkNotRunning(); 107 | testSetChanged = true; 108 | int index = testCases.size(); 109 | testCases.add(testCase); 110 | testCaseNames.add(testCase.getName()); 111 | testsTableModel.testCaseAdded(); 112 | if (createFiles) { 113 | createTestCaseFiles(index); 114 | } 115 | testsListChanged(); 116 | } 117 | 118 | private void addTestCaseFromDisk(String name) throws IOException { 119 | TestCase testCase = new TestCase(name, 120 | readFromFile(name + inputExtension), 121 | readFromFile(name + expectedOutputExtension)); 122 | testCase.setProgramOutput(readFromFile(name + programOutputExtension)); 123 | addTestCase(testCase, false); 124 | } 125 | 126 | private String readFromFile(String fileName) throws IOException { 127 | Path path = Paths.get(directory, fileName); 128 | if (!Files.exists(path)) { 129 | writeToFile(fileName, ""); 130 | return ""; 131 | } else { 132 | int fileSize = (int) new File(path.toString()).length(); 133 | char[] data = new char[Math.min(fileSize, maxLength)]; 134 | BufferedReader reader = newBufferedReader(path, StandardCharsets.UTF_8); 135 | fileSize = reader.read(data, 0, data.length); 136 | String result = new String(data, 0, fileSize); 137 | if (fileSize == maxLength) { 138 | result += "..."; 139 | } 140 | return result; 141 | } 142 | } 143 | 144 | private void writeToFile(String fileName, String data) throws IOException { 145 | synchronized (modifiedFiles) { 146 | modifiedFiles.add(fileName); 147 | } 148 | Path inputFile = Paths.get(directory, fileName); 149 | Files.write(inputFile, data.getBytes()); 150 | } 151 | 152 | public void testInputChanged(int index) throws IOException { 153 | testsTableModel.testCaseUpdated(index); 154 | writeToFile(testCases.get(index).getName() + inputExtension, testCases.get(index).getInput()); 155 | } 156 | 157 | public void testAnswerChanged(int index) throws IOException { 158 | testsTableModel.testCaseUpdated(index); 159 | writeToFile(testCases.get(index).getName() + expectedOutputExtension, 160 | testCases.get(index).getExpectedOutput()); 161 | } 162 | 163 | private void createTestCaseFiles(int index) throws IOException { 164 | testInputChanged(index); 165 | testAnswerChanged(index); 166 | writeToFile(testCases.get(index).getName() + programOutputExtension, ""); 167 | } 168 | 169 | public void setTestSolved(int index) throws IOException { 170 | TestCase testCase = testCases.get(index); 171 | String name = testCase.getName(); 172 | synchronized (modifiedFiles) { 173 | modifiedFiles.add(name + expectedOutputExtension); 174 | } 175 | Files.copy(Paths.get(directory, name + programOutputExtension), 176 | Paths.get(directory, name + expectedOutputExtension), 177 | StandardCopyOption.REPLACE_EXISTING); 178 | testCase.setExpectedOutput(testCase.getProgramOutput()); 179 | testsTableModel.testCaseUpdated(index); 180 | } 181 | 182 | public void flipTestSkipped(int index) throws IOException { 183 | checkNotRunning(); 184 | testCases.get(index).flipSkipped(); 185 | testsTableModel.testCaseUpdated(index); 186 | testsListChanged(); 187 | } 188 | 189 | public void swapTestCases(int index1, int index2) throws IOException { 190 | checkNotRunning(); 191 | Collections.swap(testCases, index1, index2); 192 | testsTableModel.testCaseUpdated(index1); 193 | testsTableModel.testCaseUpdated(index2); 194 | testsListChanged(); 195 | } 196 | 197 | private void deleteFile(String fileName) throws IOException { 198 | synchronized (modifiedFiles) { 199 | modifiedFiles.add(fileName); 200 | } 201 | Files.delete(Paths.get(directory, fileName)); 202 | } 203 | 204 | public void deleteTestCase(int index, boolean deleteFiles) throws IOException { 205 | checkNotRunning(); 206 | testSetChanged = true; 207 | String name = testCases.get(index).getName(); 208 | testCaseNames.remove(name); 209 | testCases.remove(index); 210 | testsTableModel.testCaseDeleted(index); 211 | testsListChanged(); 212 | if (deleteFiles) { 213 | deleteFile(name + inputExtension); 214 | deleteFile(name + expectedOutputExtension); 215 | deleteFile(name + programOutputExtension); 216 | } 217 | } 218 | 219 | private void checkNotRunning() throws IOException { 220 | if (testsAreRunning) throw new IOException("Cannot perform an action when tests are running."); 221 | } 222 | 223 | private void testsListChanged() throws IOException { 224 | StringBuilder builder = new StringBuilder(); 225 | for (TestCase testCase : testCases) { 226 | builder.append(String.join(" ", testCase.getName(), testCase.getExecutionResults(" "))); 227 | builder.append("\n"); 228 | } 229 | writeToFile(testListFileName, builder.toString()); 230 | } 231 | 232 | void deleteFromDisk() throws IOException { 233 | Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor() { 234 | @Override 235 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 236 | Files.delete(file); 237 | return FileVisitResult.CONTINUE; 238 | } 239 | 240 | @Override 241 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 242 | Files.delete(dir); 243 | return FileVisitResult.CONTINUE; 244 | } 245 | }); 246 | } 247 | 248 | boolean fileChanged(final WatchEvent.Kind kind, String fileName) throws IOException { 249 | synchronized (modifiedFiles) { 250 | if (modifiedFiles.contains(fileName)) { 251 | modifiedFiles.remove(fileName); 252 | return true; 253 | } 254 | if (fileName.equals(testListFileName)) { // tests list file change 255 | testsAreRunning = false; 256 | if (kind == ENTRY_CREATE) { 257 | return false; 258 | } else if (kind == ENTRY_MODIFY) { 259 | List lines = Files.readAllLines(Paths.get(directory, fileName)); 260 | if (lines.size() != testCases.size()) { 261 | return false; 262 | } 263 | for (int i = 0; i < lines.size(); ++i) { 264 | String[] tokens = lines.get(i).split(" ", 2); 265 | if (tokens.length != 2 || !tokens[0].equals(testCases.get(i).getName())) { 266 | return false; 267 | } 268 | testCases.get(i).setExecutionResults(tokens[1]); 269 | if (testCases.get(i).isRunning()) { 270 | testsAreRunning = true; 271 | } 272 | } 273 | testsTableModel.executionResultsUpdated(); 274 | } else { // ENTRY_DELETE 275 | testsListChanged(); 276 | } 277 | } else { // other file change 278 | int type = -1; 279 | if (fileName.endsWith(inputExtension)) { 280 | type = 0; 281 | } else if (fileName.endsWith(expectedOutputExtension)) { 282 | type = 1; 283 | } else if (fileName.endsWith(programOutputExtension)) { 284 | type = 2; 285 | } 286 | if (type == -1) { // not a test file 287 | return true; 288 | } 289 | String testName = fileName.substring(0, fileName.lastIndexOf(".")); 290 | if (!testCaseNames.contains(testName)) { // unknown test case file change 291 | if (type != 0) { 292 | return true; 293 | } 294 | if (kind == ENTRY_CREATE) { 295 | addTestCaseFromDisk(testName); 296 | } else { 297 | return false; 298 | } 299 | } else { // known test case file change 300 | int testIndex = 0; 301 | for (; !testCases.get(testIndex).getName().equals(testName); ++testIndex); 302 | TestCase testCase = testCases.get(testIndex); 303 | if (kind == ENTRY_CREATE) { 304 | return false; 305 | } else if (kind == ENTRY_MODIFY) { 306 | String data = readFromFile(fileName); 307 | switch (type) { 308 | case 0: 309 | testCase.setInput(data); 310 | break; 311 | case 1: 312 | testCase.setExpectedOutput(data); 313 | break; 314 | case 2: 315 | testCase.setProgramOutput(data); 316 | break; 317 | } 318 | testsTableModel.testCaseUpdated(testIndex); 319 | // tests list file change may not be signalled after the last test case, 320 | // so we manually signal it 321 | if (testIndex + 1 == testCases.size()) { 322 | fileChanged(ENTRY_MODIFY, testListFileName); 323 | } 324 | } else { // ENTRY_DELETE 325 | if (type == 0) { 326 | deleteTestCase(testIndex, false); 327 | } else { 328 | if (type == 1) { 329 | testCase.setExpectedOutput(""); 330 | } else { 331 | testCase.setProgramOutput(""); 332 | } 333 | testsTableModel.testCaseUpdated(testIndex); 334 | writeToFile(fileName, ""); 335 | } 336 | } 337 | } 338 | } 339 | return true; 340 | } 341 | } 342 | 343 | String substituteKeys(String input, boolean namesOnly) { 344 | String[] tokens = input.split("@"); 345 | for (int i = 1; i < tokens.length; i += 2) { 346 | tokens[i] = tokens[i].equals("problem_dir") ? directory : problem.getValue(tokens[i], namesOnly); 347 | } 348 | return String.join("", tokens); 349 | } 350 | 351 | boolean projectRegenerationRequired() { 352 | return problem.projectRegenerationRequired() || testSetChanged; 353 | } 354 | 355 | void markUnchanged() { 356 | problem.markUnchanged(); 357 | testSetChanged = false; 358 | } 359 | } 360 | -------------------------------------------------------------------------------- /src/ua/alcash/filesystem/WorkspaceManager.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.filesystem; 2 | 3 | import com.sun.nio.file.SensitivityWatchEventModifier; 4 | import ua.alcash.Configuration; 5 | import ua.alcash.Problem; 6 | import ua.alcash.network.ChromeListener; 7 | import ua.alcash.ui.MainFrame; 8 | 9 | import javax.swing.*; 10 | import java.io.IOException; 11 | import java.nio.file.*; 12 | import java.util.ArrayList; 13 | import java.util.concurrent.atomic.AtomicInteger; 14 | 15 | import static java.nio.file.StandardWatchEventKinds.*; 16 | 17 | /** 18 | * Created by Al.Cash on 5/24/17. 19 | */ 20 | public class WorkspaceManager { 21 | private MainFrame parent; 22 | 23 | private String workspaceDirectory = System.getProperty("user.dir"); 24 | 25 | private final ChromeListener chromeListener; 26 | 27 | private final WatchService workspaceWatcher; 28 | private final Thread watcherThread; 29 | 30 | private ArrayList problemSyncs = new ArrayList<>(); 31 | private ArrayList watchKeys = new ArrayList<>(); 32 | 33 | public WorkspaceManager(MainFrame parent) throws InstantiationException, IOException { 34 | this.parent = parent; 35 | if (!Configuration.load(workspaceDirectory)) { 36 | parent.receiveWarning("Current directory doesn't contain valid configuration file " 37 | + Configuration.CONFIGURATION_FILE_NAME + "\nPlease, select another directory."); 38 | while (true) { 39 | int result = selectWorkspace(); 40 | if (result == JOptionPane.CLOSED_OPTION) { 41 | throw new InstantiationException("Working directory wasn't provided."); 42 | } else if (result == JOptionPane.YES_OPTION) { 43 | break; 44 | } 45 | } 46 | } 47 | chromeListener = new ChromeListener(parent); 48 | workspaceWatcher = FileSystems.getDefault().newWatchService(); 49 | watcherThread = new Thread(this::processEvents,"WorkspaceWatcherThread"); 50 | watcherThread.start(); 51 | } 52 | 53 | public void configure() { 54 | ProblemSync.configure(); 55 | chromeListener.start(Configuration.get("CHelper port")); 56 | } 57 | 58 | public int selectWorkspace() { 59 | JFileChooser fileChooser = new JFileChooser(workspaceDirectory); 60 | fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 61 | final AtomicInteger result = new AtomicInteger(); 62 | try { 63 | SwingUtilities.invokeAndWait(() -> result.set(fileChooser.showOpenDialog(parent))); 64 | } catch (Exception ignored) { 65 | } 66 | if (result.get() == JFileChooser.APPROVE_OPTION) { 67 | String directory = fileChooser.getSelectedFile().getAbsolutePath(); 68 | if (!Configuration.load(directory)) { 69 | parent.receiveWarning("Selected directory doesn't contain valid configuration file " 70 | + Configuration.CONFIGURATION_FILE_NAME); 71 | return JOptionPane.NO_OPTION; 72 | } 73 | closeAllProblems(false); 74 | workspaceDirectory = directory; 75 | return JOptionPane.YES_OPTION; 76 | } 77 | return JOptionPane.CLOSED_OPTION; 78 | } 79 | 80 | public void updateWorkspace(boolean problemSetChanged) { 81 | new Thread(() -> { 82 | try { 83 | Generator.generate(workspaceDirectory, problemSyncs, problemSetChanged); 84 | } catch (IOException exception) { 85 | SwingUtilities.invokeLater(() -> parent.receiveError(exception.getMessage())); 86 | } 87 | }, "WorkspaceUpdateThread").start(); 88 | } 89 | 90 | public ProblemSync addProblem(Problem newProblem) throws IOException { 91 | ProblemSync newProblemSync = new ProblemSync(workspaceDirectory, newProblem); 92 | String directory = newProblemSync.getDirectory(); 93 | for (ProblemSync problemSync : problemSyncs) { 94 | if (problemSync.getDirectory().equals(directory)) { 95 | throw new IOException("Problem with such directory already exists: " + problemSync.getDirectory()); 96 | } 97 | } 98 | newProblemSync.initialize(); 99 | synchronized (workspaceWatcher) { 100 | problemSyncs.add(newProblemSync); 101 | WatchKey key = Paths.get(directory).register(workspaceWatcher, 102 | new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}, 103 | SensitivityWatchEventModifier.HIGH); 104 | watchKeys.add(key); 105 | } 106 | return newProblemSync; 107 | } 108 | 109 | public void closeProblem(int index, boolean delete) { 110 | if (delete) { 111 | try { 112 | problemSyncs.get(index).deleteFromDisk(); 113 | } catch (IOException exception) { 114 | parent.receiveError("Deleting folder " + problemSyncs.get(index).getDirectory() + " caused an error:\n" 115 | + exception.getMessage()); 116 | } 117 | } 118 | synchronized (workspaceWatcher) { 119 | problemSyncs.remove(index); 120 | watchKeys.get(index).cancel(); 121 | watchKeys.remove(index); 122 | } 123 | } 124 | 125 | public void closeAllProblems(boolean delete) { 126 | while (!problemSyncs.isEmpty()) { 127 | closeProblem(0, delete); 128 | } 129 | } 130 | 131 | @SuppressWarnings("unchecked") 132 | private static WatchEvent cast(WatchEvent event) { return (WatchEvent)event; } 133 | 134 | private void processEvents() { 135 | for (;;) { 136 | WatchKey key; 137 | try { 138 | key = workspaceWatcher.take(); 139 | } catch (InterruptedException exception) { 140 | break; 141 | } 142 | 143 | synchronized (workspaceWatcher) { 144 | int index = 0; 145 | for (; index < watchKeys.size() && key != watchKeys.get(index); ++index); 146 | if (index == watchKeys.size()) continue; 147 | 148 | for (WatchEvent event: key.pollEvents()) { 149 | WatchEvent.Kind kind = event.kind(); 150 | if (kind == OVERFLOW) continue; 151 | WatchEvent watchEvent = cast(event); 152 | Path file = watchEvent.context(); 153 | try { 154 | if (!problemSyncs.get(index).fileChanged(kind, file.toString())) { 155 | throw new IOException("Unexpected changes were observed in file " + file.toString()); 156 | } 157 | } catch (IOException exception) { 158 | SwingUtilities.invokeLater(() -> parent.receiveError(exception.getMessage())); 159 | } 160 | } 161 | } 162 | key.reset(); 163 | } 164 | } 165 | 166 | public void stop() { 167 | chromeListener.stop(); 168 | watcherThread.interrupt(); 169 | try { 170 | workspaceWatcher.close(); 171 | } catch (IOException ignored) { 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/ua/alcash/network/ChromeListener.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.network; 2 | 3 | import ua.alcash.Problem; 4 | import ua.alcash.parsing.ParseManager; 5 | import ua.alcash.ui.MainFrame; 6 | 7 | import javax.swing.*; 8 | import javax.xml.parsers.ParserConfigurationException; 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStreamReader; 12 | import java.net.ServerSocket; 13 | import java.net.Socket; 14 | import java.util.Collection; 15 | 16 | /** 17 | * Created by Al.Cash on 5/11/17. 18 | */ 19 | public class ChromeListener implements Runnable { 20 | private MainFrame receiver; 21 | private ServerSocket serverSocket; 22 | 23 | public ChromeListener(MainFrame receiver) { this.receiver = receiver; } 24 | 25 | public void start(String portString) { 26 | stop(); 27 | if (portString == null) { 28 | return; 29 | } 30 | try { 31 | int port = Integer.parseInt(portString); 32 | serverSocket = new ServerSocket(port); 33 | new Thread(this, "ChromeListenerThread").start(); 34 | } catch (IOException exception) { 35 | receiver.receiveError("Could not create serverSocket for Chrome parser, " + 36 | "probably another CHelper-eligible project is running."); 37 | } 38 | } 39 | 40 | public void stop() { 41 | try { 42 | serverSocket.close(); 43 | } catch (Throwable ignored) { 44 | } 45 | } 46 | 47 | @Override 48 | public void run() { 49 | while (true) try { 50 | if (serverSocket.isClosed()) 51 | return; 52 | try (Socket socket = serverSocket.accept()) { 53 | BufferedReader reader = new BufferedReader( 54 | new InputStreamReader(socket.getInputStream(), "UTF-8")); 55 | while (!reader.readLine().isEmpty()); 56 | final String platformId = reader.readLine(); 57 | StringBuilder builder = new StringBuilder(); 58 | String s; 59 | while ((s = reader.readLine()) != null) 60 | builder.append(s).append('\n'); 61 | final String page = builder.toString(); 62 | try { 63 | final Collection problems = ParseManager.parseProblemsFromHtml(platformId, page); 64 | SwingUtilities.invokeLater(() -> receiver.receiveProblems(problems)); 65 | } catch (ParserConfigurationException exception) { 66 | SwingUtilities.invokeLater(() -> receiver.receiveError(getErrorMessage(platformId))); 67 | } 68 | } 69 | } catch (Throwable ignored) { 70 | } 71 | } 72 | 73 | private String getErrorMessage(String platformId) { 74 | String message = "Failed to parse message from CHelper Chrome extension.\n"; 75 | if (platformId.isEmpty()) { 76 | message += "Message is empty."; 77 | } else { 78 | message += "Possibly, " + platformId + " platform was deleted from configuration file" 79 | + " or the format has changed"; 80 | } 81 | return message; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/ua/alcash/parsing/ParseManager.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.parsing; 2 | 3 | import net.egork.chelper.parser.*; 4 | import net.egork.chelper.task.Task; 5 | import net.egork.chelper.util.FileUtilities; 6 | import ua.alcash.Configuration; 7 | import ua.alcash.Problem; 8 | 9 | import javax.xml.parsers.ParserConfigurationException; 10 | import java.net.MalformedURLException; 11 | import java.util.*; 12 | 13 | /** 14 | * Created by Al.Cash on 5/8/17. 15 | */ 16 | public class ParseManager { 17 | private static final Map PLATFORM_ID_TO_PARSER; 18 | 19 | private static final Map PLATFORM_ID_TO_URL; 20 | private static final Map PLATFORM_ID_TO_CONTEST_URL; 21 | 22 | private static Map platformIdToName = new HashMap<>(); 23 | 24 | static { 25 | Map platforms = new HashMap<>(); 26 | platforms.put("atcoder", new AtCoderParser()); 27 | platforms.put("codechef", new CodeChefParser()); 28 | platforms.put("codeforces", new CodeforcesParser()); 29 | platforms.put("csacademy", new CSAcademyParser()); 30 | platforms.put("facebook", new FacebookParser()); 31 | platforms.put("gcj", new GCJParser()); 32 | platforms.put("hackerearth", new HackerEarthParser()); 33 | platforms.put("hackerrank", new HackerRankParser()); 34 | platforms.put("kattis", new KattisParser()); 35 | platforms.put("new-gcj", new NewGCJParser()); 36 | platforms.put("rcc", new RCCParser()); 37 | platforms.put("timus", new TimusParser()); 38 | platforms.put("usaco", new UsacoParser()); 39 | platforms.put("yandex", new YandexParser()); 40 | PLATFORM_ID_TO_PARSER = Collections.unmodifiableMap(platforms); 41 | 42 | Map platformUrls = new HashMap<>(); 43 | platformUrls.put("atcoder", "atcoder.jp"); 44 | platformUrls.put("codechef", "codechef.com"); 45 | platformUrls.put("codeforces", "codeforces.com"); 46 | platformUrls.put("csacademy", "csacademy.com"); 47 | platformUrls.put("facebook", "facebook.com/hackercup"); 48 | platformUrls.put("gcj", "code.google.com/codejam"); 49 | platformUrls.put("hackerearth", "hackerearth.com"); 50 | platformUrls.put("hackerrank", "hackerrank.com"); 51 | platformUrls.put("kattis", "open.kattis.com"); 52 | platformUrls.put("new-gcj", "codejam.withgoogle.com"); 53 | platformUrls.put("rcc", "russiancodecup.ru"); 54 | platformUrls.put("timus", "acm.timus.ru"); 55 | platformUrls.put("usaco", "usaco.org"); 56 | platformUrls.put("yandex", "contest.yandex"); 57 | PLATFORM_ID_TO_URL = Collections.unmodifiableMap(platformUrls); 58 | 59 | Map contestUrls = new HashMap<>(); 60 | contestUrls.put("codechef", "www.codechef.com/"); 61 | contestUrls.put("codeforces", "codeforces.com/contest/"); 62 | contestUrls.put("gcj", "code.google.com/codejam/contest/"); 63 | contestUrls.put("kattis", "open.kattis.com/contests/"); 64 | contestUrls.put("new-gcj", "codejam.withgoogle.com/"); 65 | contestUrls.put("rcc", "/championship/round/"); 66 | contestUrls.put("timus", "acm.timus.ru/problemset.aspx?space="); 67 | PLATFORM_ID_TO_CONTEST_URL = Collections.unmodifiableMap(contestUrls); 68 | } 69 | 70 | public static void configure() { 71 | platformIdToName.clear(); 72 | PLATFORM_ID_TO_PARSER.forEach((key, value) -> { 73 | String platformName = Configuration.getPlatform(key); 74 | if (platformName != null) { 75 | platformIdToName.put(key, platformName); 76 | } 77 | }); 78 | } 79 | 80 | public static String getPlatformName(String platformId) { 81 | String platformName = platformIdToName.get(platformId); 82 | return platformName != null ? platformName : ""; 83 | } 84 | 85 | public static List getPlatformIds() { 86 | List platformIds = new ArrayList<>(); 87 | platformIdToName.forEach((key, value) -> platformIds.add(key)); 88 | return platformIds; 89 | } 90 | 91 | private static String getPlatformByUrl(String url) throws MalformedURLException { 92 | List platformIds = new ArrayList<>(); 93 | PLATFORM_ID_TO_URL.forEach((key, value) -> { 94 | if (url.contains(value)) platformIds.add(key); 95 | }); 96 | if (platformIds.isEmpty()) { 97 | throw new MalformedURLException("Unrecognized platform."); 98 | } else if (platformIds.size() > 1) { 99 | throw new MalformedURLException("Ambiguous platform."); 100 | } else { 101 | return platformIds.get(0); 102 | } 103 | } 104 | 105 | public static Collection parseProblemsFromHtml(String platformId, String page) 106 | throws ParserConfigurationException { 107 | if (!platformIdToName.containsKey(platformId)) { 108 | throw new ParserConfigurationException("Unsupported platform."); 109 | } 110 | Parser parser = PLATFORM_ID_TO_PARSER.get(platformId); 111 | Collection tasks = parser.parseTaskFromHTML(page); 112 | if (tasks.isEmpty()) { 113 | throw new ParserConfigurationException("Parsing failed."); 114 | } 115 | ArrayList problems = new ArrayList<>(); 116 | for (Task task : tasks) { 117 | problems.add(new Problem(platformId, task)); 118 | } 119 | return problems; 120 | } 121 | 122 | public static Collection parseProblemByUrl(String url) 123 | throws MalformedURLException, ParserConfigurationException { 124 | String platformId = getPlatformByUrl(url); 125 | String html = FileUtilities.getWebPageContent(url); 126 | if (html == null) { 127 | throw new MalformedURLException("Unable to get web page content."); 128 | } 129 | return parseProblemsFromHtml(platformId, html); 130 | } 131 | 132 | private static class ContestReceiver implements DescriptionReceiver { 133 | String platformId; 134 | Parser parser; 135 | Collection problems = new ArrayList<>(); 136 | 137 | ContestReceiver(String platformId, Parser parser) { 138 | this.platformId = platformId; 139 | this.parser = parser; 140 | } 141 | 142 | @Override 143 | public boolean isStopped() { return false; } 144 | 145 | @Override 146 | public void receiveDescriptions(Collection descriptions) { 147 | for (Description description : descriptions) { 148 | problems.add(new Problem(platformId, parser.parseTask(description))); 149 | } 150 | } 151 | } 152 | 153 | public static Collection parseContestByUrl(String url) 154 | throws MalformedURLException, ParserConfigurationException { 155 | String platformId = getPlatformByUrl(url); 156 | if (!PLATFORM_ID_TO_CONTEST_URL.containsKey(platformId)) { 157 | throw new MalformedURLException("Contest parsing is not supported for " + platformId); 158 | } 159 | String contestUrl = PLATFORM_ID_TO_CONTEST_URL.get(platformId); 160 | int index = url.indexOf(contestUrl); 161 | if (index == -1) { 162 | throw new MalformedURLException("Invalid contest URL for " + platformId); 163 | } 164 | String contestId = url.substring(index + contestUrl.length()); 165 | contestId = contestId.replaceFirst("[\\$\\?#/\\\\].*", ""); 166 | Parser parser = PLATFORM_ID_TO_PARSER.get(platformId); 167 | ContestReceiver contestReceiver = new ContestReceiver(platformId, parser); 168 | parser.parseContest(contestId, contestReceiver); 169 | return contestReceiver.problems; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/MainFrame.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/MainFrame.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.Configuration; 4 | import ua.alcash.Problem; 5 | import ua.alcash.filesystem.ProblemSync; 6 | import ua.alcash.filesystem.WorkspaceManager; 7 | import ua.alcash.parsing.ParseManager; 8 | import ua.alcash.util.AbstractActionWithInteger; 9 | 10 | import javax.swing.*; 11 | import java.awt.event.*; 12 | import java.io.IOException; 13 | import java.util.Collection; 14 | 15 | /** 16 | * Created by Al.Cash on 5/9/17. 17 | */ 18 | public class MainFrame extends JFrame { 19 | private JPanel rootPanel; 20 | private JTabbedPane problemsPane; 21 | 22 | private JMenuItem newContest; 23 | private JMenuItem newProblem; 24 | private JMenuItem saveWorkspace; 25 | private JMenuItem switchWorkspace; 26 | private JMenuItem clearWorkspace; 27 | private JMenuItem exitApp; 28 | 29 | private NewProblemDialog problemDialog = new NewProblemDialog(this); 30 | private NewContestDialog contestDialog = new NewContestDialog(this); 31 | 32 | private WorkspaceManager workspaceManager; 33 | 34 | private MainFrame() throws InstantiationException { 35 | try { 36 | workspaceManager = new WorkspaceManager(this); 37 | } catch (IOException exception) { 38 | receiveError("Failed to start workspace watcher, it's highly recommended to restart " + 39 | Configuration.PROJECT_NAME + "\n" + exception.getMessage()); 40 | } 41 | setTitle(Configuration.PROJECT_NAME); 42 | setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 43 | addWindowListener(new WindowAdapter() { 44 | public void windowClosing(WindowEvent event) { 45 | confirmAndExit(); 46 | } 47 | }); 48 | setContentPane(rootPanel); 49 | createMainMenu(); 50 | createPopupMenu(); 51 | 52 | // set system proxy if there is one 53 | try { 54 | System.setProperty("java.net.useSystemProxies", "true"); 55 | } catch (Exception ignored) { 56 | } 57 | configure(); 58 | 59 | pack(); 60 | setLocationRelativeTo(null); 61 | } 62 | 63 | private void configure() { 64 | ParseManager.configure(); 65 | workspaceManager.configure(); 66 | problemDialog.configure(); 67 | setupShortcuts(); 68 | } 69 | 70 | private void createMainMenu() { 71 | JMenuBar menuBar = new JMenuBar(); 72 | JMenu newMenu = new JMenu(); 73 | newContest = new JMenuItem(); 74 | newProblem = new JMenuItem(); 75 | JMenu workspaceMenu = new JMenu(); 76 | saveWorkspace = new JMenuItem(); 77 | clearWorkspace = new JMenuItem(); 78 | switchWorkspace = new JMenuItem(); 79 | JMenu systemMenu = new JMenu(); 80 | exitApp = new JMenuItem(); 81 | 82 | newMenu.setText("New..."); 83 | 84 | newContest.setText("Contest"); 85 | newContest.addActionListener(event -> contestDialog.display()); 86 | newMenu.add(newContest); 87 | 88 | newProblem.setText("Problem"); 89 | newProblem.addActionListener(event -> problemDialog.display()); 90 | newMenu.add(newProblem); 91 | 92 | menuBar.add(newMenu); 93 | 94 | workspaceMenu.setText("Workspace"); 95 | 96 | saveWorkspace.setText("Apply changes"); 97 | saveWorkspace.addActionListener(event -> { 98 | for (int i = 0; i < problemsPane.getTabCount(); ++i) { 99 | ((ProblemPanel) problemsPane.getComponentAt(i)).updateProblemFromInterface(); 100 | } 101 | workspaceManager.updateWorkspace(false); 102 | }); 103 | workspaceMenu.add(saveWorkspace); 104 | 105 | clearWorkspace.setText("Close problems"); 106 | clearWorkspace.addActionListener(event -> closeWorkspace()); 107 | workspaceMenu.add(clearWorkspace); 108 | 109 | switchWorkspace.setText("Switch"); 110 | switchWorkspace.addActionListener(event -> { 111 | if (workspaceManager.selectWorkspace() == JOptionPane.YES_OPTION) { 112 | workspaceManager.closeAllProblems(false); 113 | problemsPane.removeAll(); 114 | configure(); 115 | } 116 | }); 117 | workspaceMenu.add(switchWorkspace); 118 | 119 | menuBar.add(workspaceMenu); 120 | 121 | systemMenu.setText("System"); 122 | 123 | exitApp.setText("Exit"); 124 | exitApp.addActionListener(event -> confirmAndExit()); 125 | systemMenu.add(exitApp); 126 | 127 | menuBar.add(systemMenu); 128 | 129 | setJMenuBar(menuBar); 130 | } 131 | 132 | private void createPopupMenu() { 133 | // adds popup menu to tabs with options to close or delete a problem 134 | final JPopupMenu singleTabPopupMenu = new JPopupMenu(); 135 | JMenuItem closeProblem = new JMenuItem("Close problem"); 136 | closeProblem.addActionListener(event -> closeProblem(false)); 137 | singleTabPopupMenu.add(closeProblem); 138 | JMenuItem deleteProblem = new JMenuItem("Delete problem"); 139 | deleteProblem.addActionListener(event -> closeProblem(true)); 140 | singleTabPopupMenu.add(deleteProblem); 141 | 142 | problemsPane.addMouseListener(new MouseAdapter() { 143 | @Override 144 | public void mousePressed(MouseEvent event) { 145 | if (event.isPopupTrigger()) { 146 | doPop(event); 147 | } 148 | } 149 | 150 | @Override 151 | public void mouseReleased(MouseEvent event) { 152 | if (event.isPopupTrigger()) { 153 | doPop(event); 154 | } 155 | } 156 | 157 | private void doPop(MouseEvent event) { 158 | singleTabPopupMenu.show(event.getComponent(), event.getX(), event.getY()); 159 | } 160 | }); 161 | } 162 | 163 | private void setupShortcuts() { 164 | newContest.setAccelerator(Configuration.getShortcut("new contest")); 165 | newProblem.setAccelerator(Configuration.getShortcut("new problem")); 166 | saveWorkspace.setAccelerator(Configuration.getShortcut("workspace apply changes")); 167 | clearWorkspace.setAccelerator(Configuration.getShortcut("workspace close problems")); 168 | switchWorkspace.setAccelerator(Configuration.getShortcut("workspace switch")); 169 | exitApp.setAccelerator(Configuration.getShortcut("exit")); 170 | 171 | for (int index = 1; index <= 9; index++) { 172 | problemsPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 173 | KeyStroke.getKeyStroke("alt " + index), "switch tab " + index); 174 | problemsPane.getActionMap().put("switch tab " + index, new AbstractActionWithInteger(index) { 175 | @Override 176 | public void actionPerformed(ActionEvent e) { 177 | if (problemsPane.getTabCount() >= getInteger()) { 178 | problemsPane.setSelectedIndex(getInteger() - 1); 179 | } 180 | } 181 | }); 182 | } 183 | } 184 | 185 | public void receiveProblems(Collection problems) { 186 | int firstProblemIndex = problemsPane.getTabCount(); 187 | for (Problem problem : problems) { 188 | try { 189 | ProblemSync problemSync = workspaceManager.addProblem(problem); 190 | ProblemPanel panel = new ProblemPanel(this, problemSync); 191 | problemsPane.addTab(problem.getId(), panel); 192 | } catch (IOException exception) { 193 | receiveError(exception.getMessage()); 194 | } 195 | } 196 | if (firstProblemIndex < problemsPane.getTabCount()) { 197 | problemsPane.setSelectedIndex(firstProblemIndex); 198 | } 199 | workspaceManager.updateWorkspace(true); 200 | } 201 | 202 | public void receiveError(String message) { 203 | JOptionPane.showMessageDialog(this, message, 204 | Configuration.PROJECT_NAME, JOptionPane.ERROR_MESSAGE); 205 | } 206 | 207 | public void receiveWarning(String message) { 208 | JOptionPane.showMessageDialog(this, message, 209 | Configuration.PROJECT_NAME, JOptionPane.WARNING_MESSAGE); 210 | } 211 | 212 | private void closeProblem(boolean delete) { 213 | int index = problemsPane.getSelectedIndex(); 214 | workspaceManager.closeProblem(index, delete); 215 | problemsPane.removeTabAt(index); 216 | workspaceManager.updateWorkspace(true); 217 | } 218 | 219 | private boolean closeWorkspace() { 220 | int confirm = JOptionPane.showConfirmDialog(this, 221 | "Keep the workspace content on the disk?", 222 | Configuration.PROJECT_NAME, 223 | JOptionPane.YES_NO_CANCEL_OPTION); 224 | if (confirm != JOptionPane.CANCEL_OPTION && confirm != JOptionPane.CLOSED_OPTION) { 225 | workspaceManager.closeAllProblems(confirm == JOptionPane.NO_OPTION); 226 | problemsPane.removeAll(); 227 | return true; 228 | } 229 | return false; 230 | } 231 | 232 | private void confirmAndExit() { 233 | if (closeWorkspace()) { 234 | workspaceManager.stop(); 235 | System.exit(0); 236 | } 237 | } 238 | 239 | public static void main(String args[]) { 240 | try { 241 | new MainFrame().setVisible(true); 242 | } catch (InstantiationException exception) { 243 | System.exit(0); 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/MultilineTableCellRenderer.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.Configuration; 4 | 5 | import javax.swing.*; 6 | import javax.swing.border.EmptyBorder; 7 | import javax.swing.table.TableCellRenderer; 8 | import java.awt.*; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Multiline Table Cell Renderer. 14 | * Taken from http://blog.botunge.dk/post/2009/10/09/JTable-multiline-cell-renderer.aspx 15 | */ 16 | public class MultilineTableCellRenderer extends JTextArea implements TableCellRenderer { 17 | private List> rowColHeight = new ArrayList<>(); 18 | 19 | private int maxLength; 20 | private int maxLines; 21 | 22 | MultilineTableCellRenderer() { 23 | maxLength = Integer.parseInt(Configuration.get("test maximum displayed length")); 24 | maxLines = Integer.parseInt(Configuration.get("test maximum displayed lines")); 25 | setLineWrap(true); 26 | setWrapStyleWord(true); 27 | setOpaque(true); 28 | } 29 | 30 | private String shorten(String value) { 31 | String displayed = value; 32 | for (int i = 0, count = 0; i < displayed.length(); ++i) { 33 | if (displayed.charAt(i) == '\n') { 34 | ++count; 35 | if (count >= maxLines - 1) { 36 | displayed = displayed.substring(0, i) + "\n..."; 37 | break; 38 | } 39 | } 40 | } 41 | if (displayed.length() > maxLength) { 42 | displayed = displayed.substring(0, maxLength - 3) + "..."; 43 | } 44 | return displayed; 45 | } 46 | 47 | @Override 48 | public Component getTableCellRendererComponent( 49 | JTable table, Object value, boolean isSelected, boolean hasFocus, 50 | int row, int column) { 51 | if (isSelected) { 52 | setForeground(table.getSelectionForeground()); 53 | setBackground(table.getSelectionBackground()); 54 | } else { 55 | setForeground(table.getForeground()); 56 | setBackground(table.getBackground()); 57 | } 58 | setFont(table.getFont()); 59 | if (hasFocus) { 60 | setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); 61 | if (table.isCellEditable(row, column)) { 62 | setForeground(UIManager.getColor("Table.focusCellForeground")); 63 | setBackground(UIManager.getColor("Table.focusCellBackground")); 64 | } 65 | } else { 66 | setBorder(new EmptyBorder(1, 2, 1, 2)); 67 | } 68 | if (value != null) { 69 | setText(shorten(value.toString())); 70 | } else { 71 | setText(""); 72 | } 73 | adjustRowHeight(table, row, column); 74 | return this; 75 | } 76 | 77 | /** 78 | * Calculates the new preferred height for a given row, and sets the height on the table. 79 | */ 80 | private void adjustRowHeight(JTable table, int row, int column) { 81 | // The trick to get this to work properly is to set the width of the column to the 82 | // text area. The reason for this is that getPreferredSize(), without a width tries 83 | // to place all the text in one line. By setting the size with the with of the column, 84 | // getPreferredSize() returns the proper height which the row should have in 85 | // order to make room for the text. 86 | int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth(); 87 | setSize(new Dimension(cWidth, 1000)); 88 | int prefH = getPreferredSize().height; 89 | while (rowColHeight.size() <= row) { 90 | rowColHeight.add(new ArrayList<>(column)); 91 | } 92 | List colHeights = rowColHeight.get(row); 93 | while (colHeights.size() <= column) { 94 | colHeights.add(0); 95 | } 96 | colHeights.set(column, prefH); 97 | int maxH = prefH; 98 | for (Integer colHeight : colHeights) { 99 | if (colHeight > maxH) { 100 | maxH = colHeight; 101 | } 102 | } 103 | if (table.getRowHeight(row) != maxH) { 104 | table.setRowHeight(row, maxH); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/NewContestDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/NewContestDialog.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.Problem; 4 | import ua.alcash.parsing.ParseManager; 5 | 6 | import javax.swing.*; 7 | import javax.xml.parsers.ParserConfigurationException; 8 | import java.awt.event.ActionEvent; 9 | import java.awt.event.KeyEvent; 10 | import java.awt.event.WindowAdapter; 11 | import java.awt.event.WindowEvent; 12 | import java.net.MalformedURLException; 13 | import java.text.ParseException; 14 | import java.util.Calendar; 15 | import java.util.Collection; 16 | import java.util.Random; 17 | import java.util.concurrent.ExecutionException; 18 | import java.util.concurrent.Executors; 19 | import java.util.concurrent.ScheduledExecutorService; 20 | import java.util.concurrent.TimeUnit; 21 | 22 | /** 23 | * Created by Al.Cash on 5/13/17. 24 | */ 25 | public class NewContestDialog extends JDialog { 26 | private final static String PARSING = "Parsing..."; 27 | 28 | private JPanel rootPanel; 29 | private JTextField urlField; 30 | private JButton scheduleButton; 31 | private JButton parseButton; 32 | private JButton abortButton; 33 | private JSpinner hourSpinner; 34 | private JSpinner minuteSpinner; 35 | 36 | private MainFrame parent; 37 | 38 | NewContestDialog(MainFrame parent) { 39 | super(parent, true); 40 | this.parent = parent; 41 | setTitle("Enter contest URL to parse"); 42 | setContentPane(rootPanel); 43 | hourSpinner.setModel(new SpinnerNumberModel(0, 0, 23, 1)); 44 | minuteSpinner.setModel(new SpinnerNumberModel(0, 0, 59, 1)); 45 | setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 46 | addWindowListener(new WindowAdapter() { 47 | public void windowClosing(WindowEvent event) { 48 | closeDialog(); 49 | } 50 | }); 51 | scheduleButton.addActionListener(event -> schedule()); 52 | parseButton.addActionListener(event -> startParsing()); 53 | abortButton.addActionListener(event -> abort()); 54 | pack(); 55 | setupShortcuts(); 56 | } 57 | 58 | void display() { 59 | urlField.requestFocus(); // set cursor in url field 60 | if (scheduleButton.isEnabled()) { 61 | int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); 62 | int minute = Calendar.getInstance().get(Calendar.MINUTE); 63 | minute = (minute + 14) / 15 * 15; 64 | if (minute == 60) { 65 | hour = (hour + 1) % 24; 66 | minute = 0; 67 | } 68 | hourSpinner.setValue(hour); 69 | minuteSpinner.setValue(minute); 70 | } 71 | setLocationRelativeTo(parent); 72 | setVisible(true); 73 | } 74 | 75 | private void setupShortcuts() { 76 | // escape key will close the dialog 77 | getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put( 78 | KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); 79 | getRootPane().getActionMap().put("close", new AbstractAction() { 80 | @Override 81 | public void actionPerformed(ActionEvent event) { 82 | closeDialog(); 83 | } 84 | }); 85 | // hitting enter will perform the same action as clicking parse button 86 | urlField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); 87 | urlField.getActionMap().put("enter", new AbstractAction() { 88 | @Override 89 | public void actionPerformed(ActionEvent event) { 90 | startParsing(); 91 | } 92 | }); 93 | } 94 | 95 | private void toggleButtons(boolean enabled) { 96 | if (enabled) { 97 | scheduleButton.setText("Schedule"); 98 | parseButton.setText("Parse"); 99 | } 100 | scheduleButton.setEnabled(enabled); 101 | hourSpinner.setEnabled(enabled); 102 | minuteSpinner.setEnabled(enabled); 103 | parseButton.setEnabled(enabled); 104 | abortButton.setEnabled(!enabled); 105 | } 106 | 107 | class BackgroundContestParser extends SwingWorker, Object> { 108 | NewContestDialog dialog; 109 | String url; 110 | 111 | BackgroundContestParser(NewContestDialog dialog, String url) { 112 | this.dialog = dialog; 113 | this.url = url; 114 | } 115 | 116 | @Override 117 | public Collection doInBackground() throws MalformedURLException, ParserConfigurationException { 118 | return ParseManager.parseContestByUrl(url); 119 | } 120 | 121 | @Override 122 | protected void done() { 123 | try { 124 | dialog.parent.receiveProblems(get()); 125 | dialog.closeDialog(); 126 | } catch (ExecutionException exception) { 127 | dialog.parent.receiveError(exception.getMessage()); 128 | } catch (Exception ignored) { 129 | } finally { 130 | dialog.toggleButtons(true); 131 | } 132 | } 133 | } 134 | 135 | private BackgroundContestParser contestParser; 136 | private ScheduledExecutorService scheduler; 137 | 138 | private void schedule() { 139 | scheduleButton.setText("Scheduled..."); 140 | toggleButtons(false); 141 | Calendar calendar = Calendar.getInstance(); 142 | try { 143 | hourSpinner.commitEdit(); 144 | minuteSpinner.commitEdit(); 145 | } catch (ParseException ignored) { 146 | } 147 | calendar.set(Calendar.HOUR_OF_DAY, (Integer) hourSpinner.getValue()); 148 | calendar.set(Calendar.MINUTE, (Integer) minuteSpinner.getValue()); 149 | // set random 10-20 seconds delay 150 | calendar.set(Calendar.SECOND, new Random().nextInt(11) + 10); 151 | long delay = calendar.getTimeInMillis() - System.currentTimeMillis(); 152 | if (delay < 0) { 153 | delay += 24 * 60 * 60 * 1000; // day in milliseconds 154 | } 155 | scheduler = Executors.newSingleThreadScheduledExecutor(); 156 | scheduler.schedule(() -> { 157 | scheduleButton.setText("Schedule"); 158 | startParsing(); 159 | }, delay, TimeUnit.MILLISECONDS); 160 | } 161 | 162 | private void startParsing() { 163 | parseButton.setText(PARSING); 164 | toggleButtons(false); 165 | contestParser = new BackgroundContestParser(this, urlField.getText()); 166 | contestParser.execute(); 167 | } 168 | 169 | private void abort() { 170 | if (parseButton.getText().equals(PARSING)) { 171 | contestParser.cancel(true); 172 | } else { 173 | scheduler.shutdownNow(); 174 | } 175 | toggleButtons(true); 176 | } 177 | 178 | private void closeDialog() { 179 | if (parseButton.getText().equals(PARSING)) { 180 | abort(); 181 | } 182 | setVisible(false); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/NewProblemDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/NewProblemDialog.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.Configuration; 4 | import ua.alcash.Problem; 5 | import ua.alcash.parsing.ParseManager; 6 | 7 | import javax.swing.*; 8 | import javax.xml.parsers.ParserConfigurationException; 9 | import java.awt.event.*; 10 | import java.net.MalformedURLException; 11 | import java.util.Collection; 12 | import java.util.Collections; 13 | import java.util.List; 14 | import java.util.concurrent.ExecutionException; 15 | 16 | /** 17 | * Created by Al.Cash on 5/9/17. 18 | */ 19 | public class NewProblemDialog extends JDialog { 20 | private JPanel rootPanel; 21 | private JComboBox platformComboBox; 22 | private JTextField contestNameField; 23 | private JTextField problemIdField; 24 | private JTextField problemNameField; 25 | private JTextField urlField; 26 | private JButton parseButton; 27 | private JButton abortParsingButton; 28 | private JButton createProblemButton; 29 | 30 | private MainFrame parent; 31 | 32 | NewProblemDialog(MainFrame parent) { 33 | super(parent, true); 34 | this.parent = parent; 35 | setTitle("Enter problem information or URL to parse"); 36 | setContentPane(rootPanel); 37 | setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 38 | addWindowListener(new WindowAdapter() { 39 | public void windowClosing(WindowEvent event) { 40 | closeDialog(); 41 | } 42 | }); 43 | parseButton.addActionListener(event -> startParsing()); 44 | abortParsingButton.addActionListener(event -> abortParsing()); 45 | createProblemButton.addActionListener(event -> createProblem()); 46 | } 47 | 48 | void display() { 49 | problemIdField.requestFocus(); // set cursor in problem ID field 50 | setLocationRelativeTo(parent); 51 | setVisible(true); 52 | } 53 | 54 | void configure() { 55 | List platformIds; 56 | platformIds = ParseManager.getPlatformIds(); 57 | Collections.sort(platformIds); 58 | platformComboBox.setMaximumRowCount(platformIds.size()); 59 | platformComboBox.setModel(new DefaultComboBoxModel<>(platformIds.toArray(new String[0]))); 60 | pack(); 61 | setupShortcuts(); 62 | } 63 | 64 | private void setupShortcuts() { 65 | // escape key will close the dialog 66 | getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put( 67 | KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); 68 | getRootPane().getActionMap().put("close", new AbstractAction() { 69 | @Override 70 | public void actionPerformed(ActionEvent event) { 71 | closeDialog(); 72 | } 73 | }); 74 | // hitting enter will perform the same action as clicking create button 75 | problemIdField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); 76 | problemIdField.getActionMap().put("enter", new AbstractAction() { 77 | @Override 78 | public void actionPerformed(ActionEvent event) { 79 | createProblem(); 80 | } 81 | }); 82 | // hitting enter will perform the same action as clicking startParsing button 83 | urlField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); 84 | urlField.getActionMap().put("enter", new AbstractAction() { 85 | @Override 86 | public void actionPerformed(ActionEvent event) { 87 | startParsing(); 88 | } 89 | }); 90 | } 91 | 92 | private void createProblem() { 93 | String problemId = problemIdField.getText(); 94 | if (problemId.isEmpty()) { 95 | JOptionPane.showMessageDialog(this, 96 | "Problem ID is empty.", 97 | Configuration.PROJECT_NAME, 98 | JOptionPane.ERROR_MESSAGE); 99 | return; 100 | } 101 | Problem problem = new Problem(problemId, problemNameField.getText(), 102 | (String) platformComboBox.getSelectedItem(), contestNameField.getText()); 103 | parent.receiveProblems(Collections.singletonList(problem)); 104 | closeDialog(); 105 | } 106 | 107 | class BackgroundProblemParser extends SwingWorker, Object> { 108 | NewProblemDialog dialog; 109 | String url; 110 | 111 | BackgroundProblemParser(NewProblemDialog dialog, String url) { 112 | this.dialog = dialog; 113 | this.url = url; 114 | } 115 | 116 | @Override 117 | public Collection doInBackground() throws MalformedURLException, ParserConfigurationException { 118 | return ParseManager.parseProblemByUrl(url); 119 | } 120 | 121 | @Override 122 | protected void done() { 123 | try { 124 | dialog.parent.receiveProblems(get()); 125 | dialog.closeDialog(); 126 | } catch (ExecutionException exception) { 127 | dialog.parent.receiveError(exception.getMessage()); 128 | } catch (Exception exception) { 129 | } finally { 130 | dialog.restoreButtonStateAfterParsing(); 131 | } 132 | } 133 | } 134 | 135 | private BackgroundProblemParser problemParser; 136 | 137 | private void startParsing() { 138 | createProblemButton.setEnabled(false); 139 | parseButton.setEnabled(false); 140 | parseButton.setText("Parsing..."); 141 | abortParsingButton.setEnabled(true); 142 | problemParser = new BackgroundProblemParser(this, urlField.getText()); 143 | problemParser.execute(); 144 | } 145 | 146 | private void abortParsing() { 147 | problemParser.cancel(true); 148 | } 149 | 150 | private void restoreButtonStateAfterParsing() { 151 | createProblemButton.setEnabled(true); 152 | parseButton.setEnabled(true); 153 | parseButton.setText("Parse"); 154 | abortParsingButton.setEnabled(false); 155 | } 156 | 157 | private void closeDialog() { 158 | if (!parseButton.isEnabled()) { 159 | abortParsing(); 160 | } 161 | setVisible(false); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/ProblemPanel.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/ProblemPanel.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import net.egork.chelper.task.TestType; 4 | import ua.alcash.Configuration; 5 | import ua.alcash.Problem; 6 | import ua.alcash.TestCase; 7 | import ua.alcash.filesystem.ProblemSync; 8 | 9 | import javax.swing.*; 10 | import javax.swing.event.ListSelectionListener; 11 | import java.awt.*; 12 | import java.awt.event.ActionEvent; 13 | import java.awt.event.MouseAdapter; 14 | import java.awt.event.MouseEvent; 15 | import java.io.IOException; 16 | import java.text.ParseException; 17 | 18 | /** 19 | * Created by Al.Cash on 5/9/17. 20 | */ 21 | public class ProblemPanel extends JPanel { 22 | private Frame parentFrame; 23 | private JPanel rootPanel; 24 | private JLabel problemName; 25 | private JSpinner timeLimitSpinner; 26 | private JSpinner memoryLimitSpinner; 27 | private JTextField inputFileField; 28 | private JTextField outputFileField; 29 | private JComboBox testTypeComboBox; 30 | private JCheckBox interactiveCheckBox; 31 | private JCheckBox customCheckerCheckBox; 32 | private JTextField checkerParamsField; 33 | 34 | private JButton newButton; 35 | private JButton editButton; 36 | private JButton solvedButton; 37 | private JButton skipButton; 38 | private JButton upButton; 39 | private JButton downButton; 40 | private JButton deleteButton; 41 | 42 | private JTable testsTable; 43 | 44 | private ProblemSync problemSync; 45 | 46 | ProblemPanel(Frame parentFrame, ProblemSync problemSync) { 47 | this.parentFrame = parentFrame; 48 | setLayout(new GridLayout(1, 1)); 49 | add(rootPanel); 50 | 51 | this.problemSync = problemSync; 52 | Problem problem = problemSync.getProblem(); 53 | problemName.setText(problem.getFullName()); 54 | timeLimitSpinner.setModel(new SpinnerNumberModel( 55 | problem.getTimeLimit(), 0, 9999, 1)); 56 | memoryLimitSpinner.setModel(new SpinnerNumberModel( 57 | problem.getMemoryLimit(), 0, 9999, 1)); 58 | testTypeComboBox.setModel(new DefaultComboBoxModel<>(new String[]{ 59 | TestType.SINGLE.toString(), 60 | TestType.MULTI_NUMBER.toString(), 61 | TestType.MULTI_EOF.toString() 62 | })); 63 | testTypeComboBox.setSelectedIndex(problem.getTestType().ordinal()); 64 | inputFileField.setText(problem.getInputFile()); 65 | outputFileField.setText(problem.getOutputFile()); 66 | interactiveCheckBox.setSelected(problem.getInteractive()); 67 | customCheckerCheckBox.setSelected(problem.getCustomChecker()); 68 | checkerParamsField.setText(problem.getCheckerParams()); 69 | 70 | testsTable.setDefaultRenderer(String.class, new MultilineTableCellRenderer()); 71 | testsTable.setModel(problemSync.getTableModel()); 72 | testsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 73 | 74 | ListSelectionListener listSelectionListener = event -> { 75 | boolean enable = !(testsTable.getSelectionModel().isSelectionEmpty()); 76 | editButton.setEnabled(enable); 77 | solvedButton.setEnabled(enable); 78 | skipButton.setEnabled(enable); 79 | upButton.setEnabled(enable && getSelectedIndex() > 0); 80 | downButton.setEnabled(enable && getSelectedIndex() < testsTable.getRowCount() - 1); 81 | deleteButton.setEnabled(enable); 82 | }; 83 | testsTable.getSelectionModel().addListSelectionListener(listSelectionListener); 84 | 85 | testsTable.addMouseListener(new MouseAdapter() { 86 | public void mouseClicked(MouseEvent event) { 87 | if (event.getClickCount() == 2) { // double-click 88 | editTestCase(); 89 | } 90 | } 91 | }); 92 | 93 | newButton.addActionListener(event -> newTestCase()); 94 | editButton.addActionListener(event -> editTestCase()); 95 | solvedButton.addActionListener(event -> runAndCheck(() -> problemSync.setTestSolved(getSelectedIndex()))); 96 | skipButton.addActionListener(event -> runAndCheck(() -> problemSync.flipTestSkipped(getSelectedIndex()))); 97 | upButton.addActionListener(event -> swapTestCases(getSelectedIndex() - 1)); 98 | downButton.addActionListener(event -> swapTestCases(getSelectedIndex() + 1)); 99 | deleteButton.addActionListener(event -> deleteTestCase()); 100 | setupShortcuts(); 101 | } 102 | 103 | private void setupShortcuts() { 104 | String keyNew = "test case new"; 105 | getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(Configuration.getShortcut(keyNew), keyNew); 106 | getActionMap().put(keyNew, new AbstractAction() { 107 | @Override 108 | public void actionPerformed(ActionEvent event) { 109 | newTestCase(); 110 | } 111 | }); 112 | String keyEdit = "test case edit"; 113 | testsTable.getInputMap().put(Configuration.getShortcut(keyEdit), keyEdit); 114 | testsTable.getActionMap().put(keyEdit, new AbstractAction() { 115 | @Override 116 | public void actionPerformed(ActionEvent event) { 117 | editTestCase(); 118 | } 119 | }); 120 | String keyDelete = "test case delete"; 121 | testsTable.getInputMap().put(Configuration.getShortcut(keyDelete), keyDelete); 122 | testsTable.getActionMap().put(keyDelete, new AbstractAction() { 123 | @Override 124 | public void actionPerformed(ActionEvent event) { 125 | deleteTestCase(); 126 | } 127 | }); 128 | } 129 | 130 | private int getSelectedIndex() throws UnsupportedOperationException { 131 | int index = testsTable.getSelectedRow(); 132 | if (index == -1) { 133 | throw new UnsupportedOperationException("No row selected to perform an action"); 134 | } 135 | return index; 136 | } 137 | 138 | interface RunnableIO { void run() throws IOException; } 139 | 140 | private void runAndCheck(RunnableIO f) { 141 | try { 142 | f.run(); 143 | } catch (IOException exception) { 144 | JOptionPane.showMessageDialog(this, exception.getMessage(), 145 | Configuration.PROJECT_NAME, 146 | JOptionPane.ERROR_MESSAGE); 147 | } 148 | } 149 | 150 | private void newTestCase() { 151 | TestCase newTestCase = new TestCase(problemSync.getNextTestName()); 152 | TestCaseDialog dialog = new TestCaseDialog(parentFrame, newTestCase); 153 | dialog.setVisible(true); 154 | if (dialog.somethingChanged()) { 155 | runAndCheck(() -> problemSync.addTestCase(newTestCase, true)); 156 | } 157 | } 158 | 159 | private void editTestCase() { 160 | int index = getSelectedIndex(); 161 | TestCase editedTestCase = problemSync.getTestCase(index); 162 | TestCaseDialog dialog = new TestCaseDialog(parentFrame, editedTestCase); 163 | dialog.setVisible(true); 164 | if (dialog.inputChanged()) { 165 | runAndCheck(() -> problemSync.testInputChanged(index)); 166 | } 167 | if (dialog.markedSolved()) { 168 | runAndCheck(() -> problemSync.setTestSolved(index)); 169 | } else if (dialog.answerChanged()) { 170 | runAndCheck(() -> problemSync.testAnswerChanged(index)); 171 | } 172 | } 173 | 174 | private void swapTestCases(int swapIndex) { 175 | runAndCheck(() -> problemSync.swapTestCases(getSelectedIndex(), swapIndex)); 176 | testsTable.setRowSelectionInterval(swapIndex, swapIndex); 177 | } 178 | 179 | private void deleteTestCase() { 180 | int confirmed = JOptionPane.showConfirmDialog(this, 181 | "Are you sure you want to delete this test case?", 182 | Configuration.PROJECT_NAME, 183 | JOptionPane.YES_NO_OPTION); 184 | if (confirmed == JOptionPane.YES_OPTION) { 185 | runAndCheck(() -> problemSync.deleteTestCase(getSelectedIndex(), true)); 186 | } 187 | } 188 | 189 | void updateProblemFromInterface() { 190 | try { 191 | timeLimitSpinner.commitEdit(); 192 | memoryLimitSpinner.commitEdit(); 193 | } catch (ParseException ignored) { 194 | } 195 | Problem problem = problemSync.getProblem(); 196 | problem.setTimeLimit((Double) timeLimitSpinner.getValue()); 197 | problem.setMemoryLimit((Double) memoryLimitSpinner.getValue()); 198 | problem.setInputFile(inputFileField.getText()); 199 | problem.setOutputFile(outputFileField.getText()); 200 | problem.setTestType(TestType.values()[testTypeComboBox.getSelectedIndex()]); 201 | problem.setInteractive(interactiveCheckBox.isSelected()); 202 | problem.setCustomChecker(customCheckerCheckBox.isSelected()); 203 | problem.setCheckerParams(checkerParamsField.getText()); 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/TestCaseDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/TestCaseDialog.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.Configuration; 4 | import ua.alcash.TestCase; 5 | 6 | import javax.swing.*; 7 | import javax.swing.event.DocumentEvent; 8 | import javax.swing.event.DocumentListener; 9 | import java.awt.*; 10 | import java.awt.event.ActionEvent; 11 | import java.awt.event.KeyEvent; 12 | import java.awt.event.WindowAdapter; 13 | import java.awt.event.WindowEvent; 14 | 15 | /** 16 | * Created by Al.Cash on 5/10/17. 17 | */ 18 | public class TestCaseDialog extends JDialog { 19 | private JPanel rootPanel; 20 | private JTextArea inputTextArea; 21 | private JTextArea expectedOutputTextArea; 22 | private JTextArea programOutputTextArea; 23 | private JButton saveButton; 24 | private JButton discardButton; 25 | private JCheckBox solvedCheckBox; 26 | 27 | private TestCase testCase; 28 | 29 | class UpdateListener implements DocumentListener { 30 | boolean updated = false; 31 | 32 | @Override 33 | public void changedUpdate(DocumentEvent event) { update(); } 34 | 35 | @Override 36 | public void removeUpdate(DocumentEvent event) { update(); } 37 | 38 | @Override 39 | public void insertUpdate(DocumentEvent event) { update(); } 40 | 41 | private void update() { 42 | updated = true; 43 | saveButton.setEnabled(true); 44 | } 45 | } 46 | 47 | private UpdateListener inputListener = new UpdateListener(); 48 | private UpdateListener answerListener = new UpdateListener(); 49 | 50 | TestCaseDialog(Frame parent, TestCase testCase) { 51 | super(parent, true); 52 | this.testCase = testCase; 53 | setTitle("Test case " + testCase.getName()); 54 | setContentPane(rootPanel); 55 | setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); 56 | addWindowListener(new WindowAdapter() { 57 | public void windowClosing(WindowEvent evt) { 58 | confirmAndClose(); 59 | } 60 | }); 61 | 62 | inputTextArea.setText(testCase.getInput()); 63 | expectedOutputTextArea.setText(testCase.getExpectedOutput()); 64 | programOutputTextArea.setText(testCase.getProgramOutput()); 65 | inputTextArea.getDocument().addDocumentListener(inputListener); 66 | expectedOutputTextArea.getDocument().addDocumentListener(answerListener); 67 | 68 | saveButton.addActionListener(event -> saveAndClose()); 69 | discardButton.addActionListener(event -> confirmAndClose()); 70 | solvedCheckBox.addActionListener(event -> { 71 | boolean solved = solvedCheckBox.isSelected(); 72 | saveButton.setEnabled(somethingChanged()); 73 | expectedOutputTextArea.setText(solved ? testCase.getProgramOutput() : testCase.getExpectedOutput()); 74 | expectedOutputTextArea.setEnabled(!solved); 75 | }); 76 | setupShortcuts(); 77 | 78 | pack(); 79 | setLocationRelativeTo(parent); 80 | } 81 | 82 | private void setupShortcuts() { 83 | // escape key will close the dialog 84 | getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put( 85 | KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); 86 | getRootPane().getActionMap().put("close", new AbstractAction() { 87 | @Override 88 | public void actionPerformed(ActionEvent event) { confirmAndClose(); } 89 | }); 90 | 91 | getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put( 92 | Configuration.getShortcut("test case save"), "save"); 93 | getRootPane().getActionMap().put("save", new AbstractAction() { 94 | @Override 95 | public void actionPerformed(ActionEvent event) { dispose(); } 96 | }); 97 | 98 | // when TAB is pressed, cycle textAreas instead of writing the \t 99 | inputTextArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); 100 | inputTextArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); 101 | expectedOutputTextArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); 102 | expectedOutputTextArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); 103 | programOutputTextArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); 104 | programOutputTextArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); 105 | } 106 | 107 | boolean inputChanged() { return inputListener.updated; } 108 | 109 | boolean answerChanged() { return answerListener.updated; } 110 | 111 | boolean markedSolved() { return solvedCheckBox.isSelected(); } 112 | 113 | boolean somethingChanged() { return inputChanged() || answerChanged() || markedSolved(); } 114 | 115 | private void saveAndClose() { 116 | if (inputChanged()) { 117 | testCase.setInput(inputTextArea.getText()); 118 | } 119 | if (!markedSolved() && answerChanged()) { 120 | testCase.setExpectedOutput(expectedOutputTextArea.getText()); 121 | } 122 | dispose(); 123 | } 124 | 125 | private void confirmAndClose() { 126 | if (somethingChanged()) { 127 | int confirmed = JOptionPane.showConfirmDialog(this, 128 | "There are unsaved changes. Are you sure you want to discard them?", 129 | Configuration.PROJECT_NAME, 130 | JOptionPane.YES_NO_OPTION); 131 | if (confirmed == JOptionPane.NO_OPTION) { 132 | return; 133 | } 134 | if (inputChanged()) inputListener.updated = false; 135 | if (answerChanged()) answerListener.updated = false; 136 | if (markedSolved()) solvedCheckBox.setSelected(false); 137 | } 138 | dispose(); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/ua/alcash/ui/TestsTableModel.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.ui; 2 | 3 | import ua.alcash.TestCase; 4 | 5 | import javax.swing.table.AbstractTableModel; 6 | import java.util.ArrayList; 7 | 8 | /** 9 | * Created by Al.Cash on 5/9/17. 10 | */ 11 | public class TestsTableModel extends AbstractTableModel { 12 | private ArrayList testCases; 13 | private final String[] columnNames = {"Input", "Expected output", "Program output", "Result"}; 14 | private final Class[] columnClasses = {String.class, String.class, String.class, String.class}; 15 | 16 | public TestsTableModel(ArrayList testCases) { this.testCases = testCases; } 17 | 18 | @Override 19 | public int getRowCount() { return testCases.size(); } 20 | 21 | @Override 22 | public int getColumnCount() { return columnNames.length; } 23 | 24 | @Override 25 | public Class getColumnClass(int columnIndex) { return columnClasses[columnIndex]; } 26 | 27 | @Override 28 | public String getColumnName(int column) { return columnNames[column]; } 29 | 30 | @Override 31 | public Object getValueAt(int rowIndex, int columnIndex) { 32 | switch (columnIndex) { 33 | case 0: 34 | return testCases.get(rowIndex).getInput(); 35 | case 1: 36 | return testCases.get(rowIndex).getExpectedOutput(); 37 | case 2: 38 | return testCases.get(rowIndex).getProgramOutput(); 39 | case 3: 40 | return testCases.get(rowIndex).getExecutionResults("\n"); 41 | default: 42 | throw new UnsupportedOperationException("Implementation error: invalid columnIndex."); 43 | } 44 | } 45 | 46 | public void testCaseUpdated(int index) { fireTableRowsUpdated(index, index); } 47 | 48 | public void testCaseAdded() { fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1); } 49 | 50 | public void testCaseDeleted(int index) { fireTableRowsDeleted(index, index); } 51 | 52 | public void executionResultsUpdated() { 53 | for (int row = 0; row < getRowCount(); ++row) { 54 | fireTableCellUpdated(row, 3); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/ua/alcash/util/AbstractActionWithInteger.java: -------------------------------------------------------------------------------- 1 | package ua.alcash.util; 2 | 3 | import javax.swing.*; 4 | 5 | /** 6 | * Created by Al.Cash on 5/9/17. 7 | */ 8 | public abstract class AbstractActionWithInteger extends AbstractAction { 9 | private final int i; 10 | 11 | public AbstractActionWithInteger(int i) { 12 | super(); 13 | this.i = i; 14 | } 15 | 16 | public int getInteger() { 17 | return i; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /templates/checker.cpp: -------------------------------------------------------------------------------- 1 | #include "testlib.h" 2 | 3 | int main(int argc, char* argv[]) { 4 | registerTestlibCmd(argc, argv); 5 | 6 | quitf(_ok, "ok"); 7 | } 8 | -------------------------------------------------------------------------------- /templates/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.9) 2 | 3 | # custom directories 4 | set(INCLUDES_DIR templates) 5 | set(TEMPLATES_DIR templates/cpp) 6 | set(CHECKERS_DIR templates) 7 | set(CODE_INLINER ../caide-cpp-inliner/build/cmd/cmd) 8 | 9 | # IDE project name 10 | get_filename_component(PROJECT_NAME ${CMAKE_SOURCE_DIR} NAME) 11 | project(${PROJECT_NAME}) 12 | 13 | # C++ standard 14 | set(CMAKE_CXX_STANDARD 17) 15 | 16 | # custom preprocessor definitions to distinguish local and online judge environment 17 | add_definitions(-DAlCash) 18 | 19 | # increase stack size 20 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-stack_size,1000000000") 21 | 22 | # create only the necessary configuration types 23 | set(CMAKE_CONFIGURATION_TYPES Debug RelWithDebInfo) 24 | 25 | # remove ZERO_CHECK target 26 | set(CMAKE_SUPPRESS_REGENERATION true) 27 | 28 | # platform specific stuff 29 | if(APPLE) 30 | if(NOT IOS) 31 | # AppCode support 32 | set(CMAKE_OSX_SYSROOT macosx) 33 | set(CMAKE_XCODE_ATTRIBUTE_CXX_LANGUAGE_STANDARD "с++${CMAKE_CXX_STANDARD}") 34 | set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") 35 | set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "NO") 36 | set(CMAKE_XCODE_GENERATE_SCHEME TRUE) 37 | endif() 38 | elseif(UNIX) 39 | # multithreading support on unix for FHC 40 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") 41 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread") 42 | endif() 43 | 44 | # common include directories for all targets 45 | include_directories(${INCLUDES_DIR} ${TEMPLATES_DIR}) 46 | 47 | # make includes show up in IDE as a separate group 48 | # preserving directory structure 49 | file(GLOB_RECURSE HEADER_FILES ${INCLUDES_DIR}/*.h ${INCLUDES_DIR}/*.hpp) 50 | get_filename_component(FULL_INCLUDES_PATH ${INCLUDES_DIR} ABSOLUTE) 51 | foreach(FILE_NAME ${HEADER_FILES}) 52 | get_filename_component(ABSOLUTE_FILE_NAME ${FILE_NAME} ABSOLUTE) 53 | file(RELATIVE_PATH FILE_RELATIVE_PATH ${FULL_INCLUDES_PATH} ${ABSOLUTE_FILE_NAME}) 54 | get_filename_component(FILE_DIRECTORY ${FILE_RELATIVE_PATH} DIRECTORY) 55 | set(FILE_DIRECTORY "\\${FILE_DIRECTORY}") 56 | string(REPLACE / \\ FILE_DIRECTORY ${FILE_DIRECTORY}) 57 | source_group("${FILE_DIRECTORY}" FILES "${FILE_NAME}") 58 | endforeach() 59 | add_custom_target(includes SOURCES ${HEADER_FILES}) 60 | 61 | # library consisting only of tester main function 62 | source_group("" FILES ${TEMPLATES_DIR}/tester.cpp) 63 | add_library(tester ${TEMPLATES_DIR}/tester.cpp) 64 | 65 | # get system include directories for the code inliner 66 | execute_process(COMMAND g++ -v -x c++ -E /dev/null 67 | OUTPUT_VARIABLE GCC_OUTPUT ERROR_VARIABLE GCC_OUTPUT) 68 | string(REGEX REPLACE "^.*#include <...> search starts here:.|End of search list..*$" "" 69 | GCC_OUTPUT ${GCC_OUTPUT}) 70 | string(REGEX REPLACE "[^|\n][^\n]*\\(framework directory\\)" "" GCC_OUTPUT ${GCC_OUTPUT}) 71 | string(REGEX REPLACE "^ |\n |\n" ";" SYSTEM_DIRS ${GCC_OUTPUT}) 72 | foreach(SYSTEM_DIR ${SYSTEM_DIRS}) 73 | if(NOT ${SYSTEM_DIR} STREQUAL "") 74 | list(APPEND INLINER_PARAMS -isystem ${SYSTEM_DIR}) 75 | endif() 76 | endforeach() 77 | 78 | # set other common inliner params 79 | string(REPLACE 17 1z CAIDE_CXX_STANDARD ${CMAKE_CXX_STANDARD}) 80 | list(APPEND INLINER_PARAMS "-std=c++${CAIDE_CXX_STANDARD}") 81 | list(APPEND INLINER_PARAMS -nostdinc -fparse-all-comments -DONLINE_JUDGE) 82 | list(APPEND INLINER_PARAMS -I ${INCLUDES_DIR} -I ${TEMPLATES_DIR} --) 83 | file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/caide) 84 | list(APPEND INLINER_PARAMS -l 1 -d ${CMAKE_BINARY_DIR}/caide -o submission.cpp) 85 | 86 | # target to view the submission code and validate that it actually compiles :) 87 | file(WRITE submission.cpp) 88 | add_executable(submission submission.cpp) 89 | source_group("" FILES submission.cpp) 90 | 91 | # problems 92 | 93 | set(PROBLEM_DIR @problem_dir@) 94 | # make test files show up in IDE along with source file 95 | file(GLOB PROBLEM_FILES ${PROBLEM_DIR}/source.cpp ${PROBLEM_DIR}/problem_limits.cpp 96 | ${PROBLEM_DIR}/*.txt ${PROBLEM_DIR}/*.in ${PROBLEM_DIR}/*.out ${PROBLEM_DIR}/*.ans) 97 | if(@interactive@) 98 | # run problem solution with console I/O 99 | set(PROBLEM_FILES ${PROBLEM_FILES} ${PROBLEM_DIR}/main.cpp) 100 | add_executable(@problem_id@ ${PROBLEM_FILES}) 101 | if(@platform_id@ STREQUAL new-gcj) 102 | # automatically run interactor provided by Google 103 | add_custom_command(TARGET @problem_id@ POST_BUILD COMMAND 104 | python ${PROBLEM_DIR}/testing_tool.py $/@problem_id@) 105 | endif() 106 | else() 107 | add_executable(@problem_id@ ${PROBLEM_FILES}) 108 | # link problem solution with tester library that will run it on all the tests 109 | target_link_libraries(@problem_id@ tester) 110 | # create a file alongside the binary pointing to tests location 111 | add_custom_command(TARGET @problem_id@ POST_BUILD COMMAND ${CMAKE_COMMAND} -E 112 | echo ${PROBLEM_DIR}/tests > $/@problem_id@Path) 113 | endif() 114 | source_group("" FILES ${PROBLEM_FILES}) 115 | 116 | # run code inliner in the background after the build 117 | add_custom_command(TARGET @problem_id@ POST_BUILD COMMAND 118 | scripts/launcher.sh 119 | ARGS ${CODE_INLINER} ${INLINER_PARAMS} ${PROBLEM_DIR}/source.cpp ${PROBLEM_DIR}/main.cpp 120 | WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) 121 | 122 | if(@custom_checker@) 123 | # custom checker target 124 | set(CHECKER_FILE ${PROBLEM_DIR}/checker.cpp) 125 | source_group("" FILES ${CHECKER_FILE}) 126 | add_executable(@problem_id@Checker ${CHECKER_FILE}) 127 | target_include_directories(@problem_id@Checker PRIVATE ${CHECKERS_DIR}) 128 | endif() 129 | -------------------------------------------------------------------------------- /templates/cpp/CMakeScripts.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.9) 2 | 3 | # custom directories 4 | set(TEMPLATES_DIR templates/cpp) 5 | set(CHECKERS_DIR templates) 6 | 7 | # default checker is compiled in case it wasn't already 8 | if(NOT EXISTS ${RELEASE_DIR}/default_checker) 9 | file(MAKE_DIRECTORY ${RELEASE_DIR}) 10 | execute_process(COMMAND g++ @default checker compiler options@ 11 | -o ${RELEASE_DIR}/default_checker 12 | ${CHECKERS_DIR}/default_checker.cpp) 13 | endif() 14 | 15 | # problems 16 | 17 | set(PROBLEM_DIR @problem_dir@) 18 | set(problem_id @problem_id@) 19 | set(time_limit @time_limit@) 20 | set(memory_limit @memory_limit@) 21 | set(input_file_name @input_file_name@) 22 | set(output_file_name @output_file_name@) 23 | set(interactive @interactive@) 24 | 25 | if(@test_type_changed@ OR @interactive_changed@) 26 | configure_file(${TEMPLATES_DIR}/source_@test_type@.cpp ${PROBLEM_DIR}/source.cpp) 27 | endif() 28 | 29 | if(@time_limit_changed@ OR @memory_limit_changed@) 30 | configure_file(${TEMPLATES_DIR}/problem_limits.cpp ${PROBLEM_DIR}/problem_limits.cpp) 31 | endif() 32 | 33 | if(@input_file_name_changed@ OR @output_file_name_changed@ OR @interactive_changed@) 34 | configure_file(${TEMPLATES_DIR}/main.cpp ${PROBLEM_DIR}/main.cpp) 35 | endif() 36 | 37 | if(@custom_checker@) 38 | set(CHECKER_FILE ${PROBLEM_DIR}/checker.cpp) 39 | if(NOT EXISTS ${CHECKER_FILE}) 40 | configure_file(${CHECKERS_DIR}/checker.cpp ${CHECKER_FILE}) 41 | endif() 42 | else() 43 | if(@custom_checker_changed@ OR @checker_compiler_options_changed@) 44 | if("@checker_compiler_options@" STREQUAL "@default checker compiler options@") 45 | # if the checker has default compiler options, create a symlink 46 | execute_process(COMMAND ln -sf default_checker ${RELEASE_DIR}/@problem_id@Checker) 47 | else() 48 | # otherwise, compile the checker 49 | execute_process(COMMAND g++ @checker_compiler_options@ 50 | -o ${RELEASE_DIR}/@problem_id@Checker 51 | ${CHECKERS_DIR}/default_checker.cpp) 52 | endif() 53 | endif() 54 | endif() 55 | -------------------------------------------------------------------------------- /templates/cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include "solution.h" 2 | 3 | #include 4 | 5 | int main() { 6 | std::cin.tie(0); 7 | std::ios_base::sync_with_stdio(false); 8 | const char* inputFileName = "@input_file_name@"; 9 | if (*inputFileName) std::freopen(inputFileName, "r", stdin); 10 | const char* outputFileName = "@output_file_name@"; 11 | if (*outputFileName) std::freopen(outputFileName, "w", stdout); 12 | solve(std::cin, std::cout); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /templates/cpp/problem_limits.cpp: -------------------------------------------------------------------------------- 1 | #include "problem_limits.h" 2 | 3 | const double TIME_LIMIT = @time_limit@; 4 | 5 | const double CHECKER_TIME_LIMIT = 1.0; 6 | 7 | const double MEMORY_LIMIT = @memory_limit@; 8 | -------------------------------------------------------------------------------- /templates/cpp/problem_limits.h: -------------------------------------------------------------------------------- 1 | extern const double TIME_LIMIT; 2 | 3 | extern const double CHECKER_TIME_LIMIT; 4 | 5 | extern const double MEMORY_LIMIT; 6 | -------------------------------------------------------------------------------- /templates/cpp/solution.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // Powered by ACHelper (https://github.com/AlCash07/ACHelper) 3 | 4 | #include 5 | 6 | void solve(std::istream& in, std::ostream& out); 7 | -------------------------------------------------------------------------------- /templates/cpp/source_multi_eof.cpp: -------------------------------------------------------------------------------- 1 | #include "solution.h" 2 | 3 | class @problem_id@Solver { 4 | public: 5 | bool solve(std::istream& in, std::ostream& out) { 6 | if (!in.good()) return false; 7 | return true; 8 | } 9 | }; 10 | 11 | void solve(std::istream& in, std::ostream& out) { 12 | while (true) { 13 | @problem_id@Solver solver; 14 | if (!solver.solve(in, out)) break; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /templates/cpp/source_multi_number.cpp: -------------------------------------------------------------------------------- 1 | #include "solution.h" 2 | 3 | class @problem_id@Solver { 4 | public: 5 | void solve(std::istream& in, std::ostream& out) { 6 | } 7 | }; 8 | 9 | void solve(std::istream& in, std::ostream& out) { 10 | int testIndex = 1, testCount; 11 | for (in >> testCount; testIndex <= testCount; ++testIndex) { 12 | #if !@interactive@ 13 | out << "Case #" << testIndex << ": "; 14 | #endif 15 | @problem_id@Solver solver; 16 | solver.solve(in, out); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /templates/cpp/source_single.cpp: -------------------------------------------------------------------------------- 1 | #include "solution.h" 2 | 3 | class @problem_id@Solver { 4 | public: 5 | void solve(std::istream& in, std::ostream& out) { 6 | } 7 | }; 8 | 9 | void solve(std::istream& in, std::ostream& out) { 10 | @problem_id@Solver solver; 11 | solver.solve(in, out); 12 | } 13 | -------------------------------------------------------------------------------- /templates/cpp/tester.cpp: -------------------------------------------------------------------------------- 1 | #include "problem_limits.h" 2 | #include "solution.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | using namespace std; 19 | 20 | string testsDirectory; 21 | 22 | struct TestCase { 23 | TestCase(const string& fileName) 24 | : inputFileName(testsDirectory + fileName + ".in") 25 | , outputFileName(testsDirectory + fileName + ".out") 26 | , answerFileName(testsDirectory + fileName + ".ans") 27 | {} 28 | 29 | void run() const { 30 | ifstream in(inputFileName); 31 | ofstream out(outputFileName); 32 | solve(in, out); 33 | } 34 | 35 | string inputFileName; 36 | string outputFileName; 37 | string answerFileName; 38 | }; 39 | 40 | // std::getline analog for file descriptors 41 | bool getline(FILE* file, string& line) { 42 | line.clear(); 43 | while (true) { 44 | int c = fgetc(file); 45 | if (c == EOF || c == '\n') break; 46 | line += c; 47 | } 48 | return !line.empty(); 49 | } 50 | 51 | // return codes: 52 | // 0 : success 53 | // -1 : execution failed 54 | // 1 : runtime error (error string may be TLE indicating time limit exceeded) 55 | template 56 | int executeProcess(Function f, double timeLimit, string& error) { 57 | int pipefd[2]; 58 | pipe(pipefd); 59 | auto pid = fork(); 60 | if (pid == 0) { // child process 61 | close(pipefd[0]); // close input pipe 62 | dup2(pipefd[1], STDERR_FILENO); // redirect stderr to output pipe 63 | signal(SIGALRM, [](int sigNum) { exit(sigNum); }); // exit after timer 64 | itimerval itimer; 65 | itimer.it_interval = {0, 0}; 66 | itimer.it_value.tv_sec = static_cast(timeLimit); 67 | itimer.it_value.tv_usec = static_cast((timeLimit - itimer.it_value.tv_sec) * 1000000); 68 | if (setitimer(ITIMER_REAL, &itimer, nullptr) != 0) { 69 | exit(SIGKILL); // failed to start timer 70 | } 71 | f(); // function is executed here 72 | exit(0); 73 | } else if (pid < 0) { // fork failed 74 | return -1; 75 | } 76 | // parent process 77 | close(pipefd[1]); // close output pipe 78 | int status = 0; 79 | int returnedPid = waitpid(pid, &status, 0); 80 | if (returnedPid != pid) { 81 | kill(pid, SIGKILL); 82 | } 83 | FILE* errorPipe = fdopen(pipefd[0], "r"); 84 | getline(errorPipe, error); // read stderr message 85 | fclose(errorPipe); 86 | if (returnedPid == pid && status == 0) { 87 | return 0; 88 | } 89 | if (WEXITSTATUS(status) == SIGALRM) { 90 | error = "TLE"; 91 | } else if (status == 11) { 92 | error = "segmentation fault"; 93 | } 94 | return 1; 95 | } 96 | 97 | void colorOutput(const string& output, bool green) { 98 | cout << (green ? "\033[32;1m" : "\033[31;1m"); 99 | cout << output << "\033[0m"; 100 | } 101 | 102 | int main(int argc, const char* argv[]) { 103 | using namespace std; 104 | ios_base::sync_with_stdio(0); 105 | 106 | // read the path to tests list file 107 | string binaryPath = argv[0]; 108 | ifstream pathFile(binaryPath + "Path"); 109 | string testsFileName; 110 | pathFile >> testsFileName; 111 | pathFile.close(); 112 | testsDirectory = testsFileName.substr(0, testsFileName.find_last_of("/\\") + 1); 113 | 114 | // read test names 115 | vector> testCases; 116 | FILE* testsListInputFile = fopen(testsFileName.data(), "r"); 117 | string line; 118 | while (getline(testsListInputFile, line)) { 119 | testCases.emplace_back(); 120 | auto spaceIndex = line.find(' '); 121 | testCases.back().push_back(line.substr(0, spaceIndex)); 122 | testCases.back().push_back(spaceIndex < line.size() ? line.substr(spaceIndex + 1) : ""); 123 | } 124 | fclose(testsListInputFile); 125 | auto isSkipped = [&testCases](size_t testIndex) { 126 | return testCases[testIndex][1] == "SKIPPED"; 127 | }; 128 | 129 | #ifndef NDEBUG 130 | // in debug mode, tests are run without validation and updating tests list file 131 | for (size_t testIndex = 0, testCount = testCases.size(); testIndex < testCount; ++testIndex) { 132 | if (isSkipped(testIndex)) continue; 133 | cout << testCases[testIndex][0] << ": running" << endl; 134 | TestCase(testCases[testIndex][0]).run(); 135 | } 136 | #else 137 | int testsTotal = 0, testsPassed = 0; 138 | for (size_t testIndex = 0, testCount = testCases.size();; ++testIndex) { 139 | if (testIndex < testCount) { 140 | cout << testCases[testIndex][0] << ": "; 141 | if (isSkipped(testIndex)) { 142 | cout << "skipping" << endl; 143 | continue; 144 | } 145 | cout << "running" << endl; 146 | ++testsTotal; 147 | } 148 | 149 | // update tests list file 150 | ofstream testsListFile(testsFileName); 151 | for (size_t i = 0; i < testIndex; ++i) { 152 | testsListFile << testCases[i][0] << ' ' << testCases[i][1] << '\n'; 153 | } 154 | if (testIndex < testCount) { 155 | testsListFile << testCases[testIndex][0] << " RUNNING\n"; 156 | } 157 | for (size_t i = testIndex + 1; i < testCount; ++i) { 158 | testsListFile << testCases[i][0] << " PENDING\n"; 159 | } 160 | testsListFile.close(); 161 | if (testIndex == testCount) break; 162 | 163 | // run the test as a subprocess and measure time 164 | TestCase testCase(testCases[testIndex][0]); 165 | auto start = chrono::system_clock::now(); 166 | string error; 167 | int status = executeProcess([&testCase](){ 168 | testCase.run(); 169 | }, TIME_LIMIT, error); 170 | auto end = chrono::system_clock::now(); 171 | double elapsed = chrono::duration_cast>(end - start).count(); 172 | 173 | // evaluation 174 | ostringstream resultStream; 175 | resultStream << fixed << setprecision(3) << elapsed << ' '; 176 | if (status == 0) { 177 | // check if answer file is not empty 178 | ifstream answerFile(testCase.answerFileName); 179 | if (!answerFile || answerFile.peek() == ifstream::traits_type::eof()) { 180 | error = "UNKNOWN"; 181 | } else { // run checker 182 | string checkerCommand = binaryPath + "Checker"; 183 | status = executeProcess([&checkerCommand, &testCase]() { 184 | execl(checkerCommand.data(), 185 | checkerCommand.data(), 186 | testCase.inputFileName.data(), 187 | testCase.outputFileName.data(), 188 | testCase.answerFileName.data()); 189 | }, CHECKER_TIME_LIMIT, error); 190 | if (status == 1 && error == "TLE") { 191 | status = -1; 192 | } 193 | } 194 | answerFile.close(); 195 | } 196 | if (status == -1) { 197 | resultStream << "judgement error"; 198 | } else if (error == "TLE") { 199 | resultStream << "time limit exceeded"; 200 | } else { 201 | resultStream << error; 202 | } 203 | if (status == 0) { 204 | ++testsPassed; 205 | } 206 | line = testCases[testIndex][1] = resultStream.str(); 207 | auto spaceIndex = line.find(' '); 208 | cout << line.substr(0, spaceIndex); 209 | colorOutput(line.substr(spaceIndex), status == 0); 210 | cout << "\n"; 211 | } 212 | cout << "========================================\n"; 213 | if (testsPassed == testsTotal) { 214 | colorOutput("All tests passed:", true); 215 | } else { 216 | colorOutput("Not all tests passed:", false); 217 | } 218 | cout << " " << testsPassed << " / " << testsTotal << "\n"; 219 | #endif 220 | return 0; 221 | } 222 | -------------------------------------------------------------------------------- /templates/default_checker.cpp: -------------------------------------------------------------------------------- 1 | #include "testlib.h" 2 | #include 3 | #include 4 | 5 | // returns false for integers to avoid comparing big integers as doubles with precision loss 6 | bool convertToDouble(const std::string src, double& dst) { 7 | char* endptr = 0; 8 | dst = std::strtod(src.data(), &endptr); 9 | if (*endptr != '\0') { 10 | dst = std::numeric_limits::quiet_NaN(); 11 | return false; 12 | } 13 | static std::regex integerRegex(R"~([+-]?\d+)~"); 14 | return !std::regex_match(src.data(), integerRegex); 15 | } 16 | 17 | bool compareDoubles(double expected, double result) { 18 | if (std::isnan(expected)) return std::isnan(result); 19 | if (std::isinf(expected)) return expected == result; 20 | if (std::isnan(result) || std::isinf(result)) return false; 21 | bool equal = false; 22 | #ifdef ABSOLUTE 23 | equal = equal || std::abs(expected - result) < EPSILON; 24 | #endif 25 | #ifdef RELATIVE 26 | equal = equal || std::abs((expected - result) / expected) < EPSILON; 27 | #endif 28 | return equal; 29 | } 30 | 31 | std::string outputCharacter(char c) { 32 | if (c) return std::string("'") + c + "'"; 33 | else return "null"; 34 | } 35 | 36 | int main(int argc, char* argv[]) { 37 | const int maxTokenLengthToOutput = 22; // to fit standard integer numbers 38 | 39 | registerTestlibCmd(argc, argv); 40 | 41 | int index = 0; 42 | while (!ans.seekEof() && !ouf.seekEof()) { 43 | ++index; 44 | std::string answer = ans.readToken(); 45 | std::string output = ouf.readToken(); 46 | double doubleAnswer, doubleOutput; 47 | bool isAnswerDouble = convertToDouble(answer, doubleAnswer); 48 | bool isOutputDouble = convertToDouble(output, doubleOutput); 49 | if (isAnswerDouble || isOutputDouble) { 50 | if (!compareDoubles(doubleAnswer, doubleOutput)) { 51 | if (answer.size() > maxTokenLengthToOutput) { 52 | answer = answer.substr(0, maxTokenLengthToOutput - 3) + "..."; 53 | } 54 | if (output.size() > maxTokenLengthToOutput) { 55 | output = output.substr(0, maxTokenLengthToOutput - 3) + "..."; 56 | } 57 | quitf(_wa, "%d%s floating point numbers differ - expected: '%s', found: '%s'", 58 | index, englishEnding(index).data(), answer.data(), output.data()); 59 | } 60 | } else if (answer != output) { 61 | if (answer.size() <= maxTokenLengthToOutput && output.size() <= maxTokenLengthToOutput) { 62 | quitf(_wa, "%d%s tokens differ - expected: '%s', found: '%s'", 63 | index, englishEnding(index).data(), answer.data(), output.data()); 64 | } else { 65 | int diff = 0; 66 | while (answer[diff] == output[diff]) ++diff; 67 | quitf(_wa, "%d%s tokens differ in %d%s character - expected: %s, found: %s", 68 | index, englishEnding(index).data(), 69 | diff + 1, englishEnding(diff + 1).data(), 70 | outputCharacter(answer[diff]).data(), outputCharacter(output[diff]).data()); 71 | } 72 | } 73 | } 74 | 75 | int answerCount = index; 76 | while (!ans.seekEof()) { 77 | ans.readToken(); 78 | ++answerCount; 79 | } 80 | 81 | int outputCount = index; 82 | while (!ouf.seekEof()) { 83 | ouf.readToken(); 84 | ++outputCount; 85 | } 86 | 87 | if (answerCount != outputCount) { 88 | quitf(_wa, "token count differs - expected: %d, found: %d", answerCount, outputCount); 89 | } 90 | 91 | quitf(_ok, "%d tokens", index); 92 | } 93 | --------------------------------------------------------------------------------